github.com/calmw/ethereum@v0.1.1/graphql/graphql_test.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package graphql
    18  
    19  import (
    20  	"context"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"net/http"
    26  	"strings"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/calmw/ethereum/common"
    31  	"github.com/calmw/ethereum/consensus/ethash"
    32  	"github.com/calmw/ethereum/core"
    33  	"github.com/calmw/ethereum/core/types"
    34  	"github.com/calmw/ethereum/core/vm"
    35  	"github.com/calmw/ethereum/crypto"
    36  	"github.com/calmw/ethereum/eth"
    37  	"github.com/calmw/ethereum/eth/ethconfig"
    38  	"github.com/calmw/ethereum/eth/filters"
    39  	"github.com/calmw/ethereum/node"
    40  	"github.com/calmw/ethereum/params"
    41  
    42  	"github.com/stretchr/testify/assert"
    43  )
    44  
    45  func TestBuildSchema(t *testing.T) {
    46  	ddir := t.TempDir()
    47  	// Copy config
    48  	conf := node.DefaultConfig
    49  	conf.DataDir = ddir
    50  	stack, err := node.New(&conf)
    51  	if err != nil {
    52  		t.Fatalf("could not create new node: %v", err)
    53  	}
    54  	defer stack.Close()
    55  	// Make sure the schema can be parsed and matched up to the object model.
    56  	if _, err := newHandler(stack, nil, nil, []string{}, []string{}); err != nil {
    57  		t.Errorf("Could not construct GraphQL handler: %v", err)
    58  	}
    59  }
    60  
    61  // Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint
    62  func TestGraphQLBlockSerialization(t *testing.T) {
    63  	stack := createNode(t)
    64  	defer stack.Close()
    65  	genesis := &core.Genesis{
    66  		Config:     params.AllEthashProtocolChanges,
    67  		GasLimit:   11500000,
    68  		Difficulty: big.NewInt(1048576),
    69  	}
    70  	newGQLService(t, stack, genesis, 10, func(i int, gen *core.BlockGen) {})
    71  	// start node
    72  	if err := stack.Start(); err != nil {
    73  		t.Fatalf("could not start node: %v", err)
    74  	}
    75  
    76  	for i, tt := range []struct {
    77  		body string
    78  		want string
    79  		code int
    80  	}{
    81  		{ // Should return latest block
    82  			body: `{"query": "{block{number}}","variables": null}`,
    83  			want: `{"data":{"block":{"number":"0xa"}}}`,
    84  			code: 200,
    85  		},
    86  		{ // Should return info about latest block
    87  			body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`,
    88  			want: `{"data":{"block":{"number":"0xa","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
    89  			code: 200,
    90  		},
    91  		{
    92  			body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`,
    93  			want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
    94  			code: 200,
    95  		},
    96  		{
    97  			body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`,
    98  			want: `{"data":{"block":null}}`,
    99  			code: 200,
   100  		},
   101  		{
   102  			body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`,
   103  			want: `{"data":{"block":null}}`,
   104  			code: 200,
   105  		},
   106  		{
   107  			body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`,
   108  			want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
   109  			code: 200,
   110  		},
   111  		{
   112  			body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`,
   113  			want: `{"data":{"block":null}}`,
   114  			code: 200,
   115  		},
   116  		{
   117  			body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`,
   118  			want: `{"data":{"block":null}}`,
   119  			code: 200,
   120  		},
   121  		{
   122  			body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`,
   123  			want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
   124  			//want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`,
   125  			code: 200,
   126  		},
   127  		{
   128  			body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`,
   129  			want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`,
   130  			code: 400,
   131  		},
   132  		{
   133  			body: `{"query": "{bleh{number}}","variables": null}"`,
   134  			want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`,
   135  			code: 400,
   136  		},
   137  		// should return `estimateGas` as decimal
   138  		{
   139  			body: `{"query": "{block{ estimateGas(data:{}) }}"}`,
   140  			want: `{"data":{"block":{"estimateGas":"0xcf08"}}}`,
   141  			code: 200,
   142  		},
   143  		// should return `status` as decimal
   144  		{
   145  			body: `{"query": "{block {number call (data : {from : \"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\", to: \"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\", data :\"0x12a7b914\"}){data status}}}"}`,
   146  			want: `{"data":{"block":{"number":"0xa","call":{"data":"0x","status":"0x1"}}}}`,
   147  			code: 200,
   148  		},
   149  	} {
   150  		resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
   151  		if err != nil {
   152  			t.Fatalf("could not post: %v", err)
   153  		}
   154  		bodyBytes, err := io.ReadAll(resp.Body)
   155  		resp.Body.Close()
   156  		if err != nil {
   157  			t.Fatalf("could not read from response body: %v", err)
   158  		}
   159  		if have := string(bodyBytes); have != tt.want {
   160  			t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
   161  		}
   162  		if tt.code != resp.StatusCode {
   163  			t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
   164  		}
   165  	}
   166  }
   167  
   168  func TestGraphQLBlockSerializationEIP2718(t *testing.T) {
   169  	// Account for signing txes
   170  	var (
   171  		key, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   172  		address = crypto.PubkeyToAddress(key.PublicKey)
   173  		funds   = big.NewInt(1000000000000000)
   174  		dad     = common.HexToAddress("0x0000000000000000000000000000000000000dad")
   175  	)
   176  	stack := createNode(t)
   177  	defer stack.Close()
   178  	genesis := &core.Genesis{
   179  		Config:     params.AllEthashProtocolChanges,
   180  		GasLimit:   11500000,
   181  		Difficulty: big.NewInt(1048576),
   182  		Alloc: core.GenesisAlloc{
   183  			address: {Balance: funds},
   184  			// The address 0xdad sloads 0x00 and 0x01
   185  			dad: {
   186  				Code:    []byte{byte(vm.PC), byte(vm.PC), byte(vm.SLOAD), byte(vm.SLOAD)},
   187  				Nonce:   0,
   188  				Balance: big.NewInt(0),
   189  			},
   190  		},
   191  		BaseFee: big.NewInt(params.InitialBaseFee),
   192  	}
   193  	signer := types.LatestSigner(genesis.Config)
   194  	newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) {
   195  		gen.SetCoinbase(common.Address{1})
   196  		tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{
   197  			Nonce:    uint64(0),
   198  			To:       &dad,
   199  			Value:    big.NewInt(100),
   200  			Gas:      50000,
   201  			GasPrice: big.NewInt(params.InitialBaseFee),
   202  		})
   203  		gen.AddTx(tx)
   204  		tx, _ = types.SignNewTx(key, signer, &types.AccessListTx{
   205  			ChainID:  genesis.Config.ChainID,
   206  			Nonce:    uint64(1),
   207  			To:       &dad,
   208  			Gas:      30000,
   209  			GasPrice: big.NewInt(params.InitialBaseFee),
   210  			Value:    big.NewInt(50),
   211  			AccessList: types.AccessList{{
   212  				Address:     dad,
   213  				StorageKeys: []common.Hash{{0}},
   214  			}},
   215  		})
   216  		gen.AddTx(tx)
   217  	})
   218  	// start node
   219  	if err := stack.Start(); err != nil {
   220  		t.Fatalf("could not start node: %v", err)
   221  	}
   222  
   223  	for i, tt := range []struct {
   224  		body string
   225  		want string
   226  		code int
   227  	}{
   228  		{
   229  			body: `{"query": "{block {number transactions { from { address } to { address } value hash type accessList { address storageKeys } index}}}"}`,
   230  			want: `{"data":{"block":{"number":"0x1","transactions":[{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x64","hash":"0xd864c9d7d37fade6b70164740540c06dd58bb9c3f6b46101908d6339db6a6a7b","type":"0x0","accessList":[],"index":"0x0"},{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x32","hash":"0x19b35f8187b4e15fb59a9af469dca5dfa3cd363c11d372058c12f6482477b474","type":"0x1","accessList":[{"address":"0x0000000000000000000000000000000000000dad","storageKeys":["0x0000000000000000000000000000000000000000000000000000000000000000"]}],"index":"0x1"}]}}}`,
   231  			code: 200,
   232  		},
   233  	} {
   234  		resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
   235  		if err != nil {
   236  			t.Fatalf("could not post: %v", err)
   237  		}
   238  		bodyBytes, err := io.ReadAll(resp.Body)
   239  		resp.Body.Close()
   240  		if err != nil {
   241  			t.Fatalf("could not read from response body: %v", err)
   242  		}
   243  		if have := string(bodyBytes); have != tt.want {
   244  			t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
   245  		}
   246  		if tt.code != resp.StatusCode {
   247  			t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
   248  		}
   249  	}
   250  }
   251  
   252  // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
   253  func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
   254  	stack := createNode(t)
   255  	defer stack.Close()
   256  	if err := stack.Start(); err != nil {
   257  		t.Fatalf("could not start node: %v", err)
   258  	}
   259  	body := strings.NewReader(`{"query": "{block{number}}","variables": null}`)
   260  	resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", body)
   261  	if err != nil {
   262  		t.Fatalf("could not post: %v", err)
   263  	}
   264  	resp.Body.Close()
   265  	// make sure the request is not handled successfully
   266  	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
   267  }
   268  
   269  func TestGraphQLConcurrentResolvers(t *testing.T) {
   270  	var (
   271  		key, _  = crypto.GenerateKey()
   272  		addr    = crypto.PubkeyToAddress(key.PublicKey)
   273  		dadStr  = "0x0000000000000000000000000000000000000dad"
   274  		dad     = common.HexToAddress(dadStr)
   275  		genesis = &core.Genesis{
   276  			Config:     params.AllEthashProtocolChanges,
   277  			GasLimit:   11500000,
   278  			Difficulty: big.NewInt(1048576),
   279  			Alloc: core.GenesisAlloc{
   280  				addr: {Balance: big.NewInt(params.Ether)},
   281  				dad: {
   282  					// LOG0(0, 0), LOG0(0, 0), RETURN(0, 0)
   283  					Code:    common.Hex2Bytes("60006000a060006000a060006000f3"),
   284  					Nonce:   0,
   285  					Balance: big.NewInt(0),
   286  				},
   287  			},
   288  		}
   289  		signer = types.LatestSigner(genesis.Config)
   290  		stack  = createNode(t)
   291  	)
   292  	defer stack.Close()
   293  
   294  	var tx *types.Transaction
   295  	handler, chain := newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) {
   296  		tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
   297  		gen.AddTx(tx)
   298  		tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 1, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
   299  		gen.AddTx(tx)
   300  		tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 2, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
   301  		gen.AddTx(tx)
   302  	})
   303  	// start node
   304  	if err := stack.Start(); err != nil {
   305  		t.Fatalf("could not start node: %v", err)
   306  	}
   307  
   308  	for i, tt := range []struct {
   309  		body string
   310  		want string
   311  	}{
   312  		// Multiple txes race to get/set the block hash.
   313  		{
   314  			body: "{block { transactions { logs { account { address } } } } }",
   315  			want: fmt.Sprintf(`{"block":{"transactions":[{"logs":[{"account":{"address":"%s"}},{"account":{"address":"%s"}}]},{"logs":[{"account":{"address":"%s"}},{"account":{"address":"%s"}}]},{"logs":[{"account":{"address":"%s"}},{"account":{"address":"%s"}}]}]}}`, dadStr, dadStr, dadStr, dadStr, dadStr, dadStr),
   316  		},
   317  		// Multiple fields of a tx race to resolve it. Happens in this case
   318  		// because resolving the tx body belonging to a log is delayed.
   319  		{
   320  			body: `{block { logs(filter: {}) { transaction { nonce value gasPrice }}}}`,
   321  			want: `{"block":{"logs":[{"transaction":{"nonce":"0x0","value":"0x0","gasPrice":"0x3b9aca00"}},{"transaction":{"nonce":"0x0","value":"0x0","gasPrice":"0x3b9aca00"}},{"transaction":{"nonce":"0x1","value":"0x0","gasPrice":"0x3b9aca00"}},{"transaction":{"nonce":"0x1","value":"0x0","gasPrice":"0x3b9aca00"}},{"transaction":{"nonce":"0x2","value":"0x0","gasPrice":"0x3b9aca00"}},{"transaction":{"nonce":"0x2","value":"0x0","gasPrice":"0x3b9aca00"}}]}}`,
   322  		},
   323  		// Multiple txes of a block race to set/retrieve receipts of a block.
   324  		{
   325  			body: "{block { transactions { status gasUsed } } }",
   326  			want: `{"block":{"transactions":[{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"}]}}`,
   327  		},
   328  		// Multiple fields of block race to resolve header and body.
   329  		{
   330  			body: "{ block { number hash gasLimit ommerCount transactionCount totalDifficulty } }",
   331  			want: fmt.Sprintf(`{"block":{"number":"0x1","hash":"%s","gasLimit":"0xaf79e0","ommerCount":"0x0","transactionCount":"0x3","totalDifficulty":"0x200000"}}`, chain[len(chain)-1].Hash()),
   332  		},
   333  		// Multiple fields of a block race to resolve the header and body.
   334  		{
   335  			body: fmt.Sprintf(`{ transaction(hash: "%s") { block { number hash gasLimit ommerCount transactionCount } } }`, tx.Hash()),
   336  			want: fmt.Sprintf(`{"transaction":{"block":{"number":"0x1","hash":"%s","gasLimit":"0xaf79e0","ommerCount":"0x0","transactionCount":"0x3"}}}`, chain[len(chain)-1].Hash()),
   337  		},
   338  		// Account fields race the resolve the state object.
   339  		{
   340  			body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, dadStr),
   341  			want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x60006000a060006000a060006000f3"}}}`,
   342  		},
   343  		// Test values for a non-existent account.
   344  		{
   345  			body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, "0x1111111111111111111111111111111111111111"),
   346  			want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x"}}}`,
   347  		},
   348  	} {
   349  		res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{})
   350  		if res.Errors != nil {
   351  			t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors)
   352  		}
   353  		have, err := json.Marshal(res.Data)
   354  		if err != nil {
   355  			t.Fatalf("failed to encode graphql response for testcase #%d: %s", i, err)
   356  		}
   357  		if string(have) != tt.want {
   358  			t.Errorf("response unmatch for testcase #%d.\nExpected:\n%s\nGot:\n%s\n", i, tt.want, have)
   359  		}
   360  	}
   361  }
   362  
   363  func createNode(t *testing.T) *node.Node {
   364  	stack, err := node.New(&node.Config{
   365  		HTTPHost:     "127.0.0.1",
   366  		HTTPPort:     0,
   367  		WSHost:       "127.0.0.1",
   368  		WSPort:       0,
   369  		HTTPTimeouts: node.DefaultConfig.HTTPTimeouts,
   370  	})
   371  	if err != nil {
   372  		t.Fatalf("could not create node: %v", err)
   373  	}
   374  	return stack
   375  }
   376  
   377  func newGQLService(t *testing.T, stack *node.Node, gspec *core.Genesis, genBlocks int, genfunc func(i int, gen *core.BlockGen)) (*handler, []*types.Block) {
   378  	ethConf := &ethconfig.Config{
   379  		Genesis:                 gspec,
   380  		NetworkId:               1337,
   381  		TrieCleanCache:          5,
   382  		TrieCleanCacheJournal:   "triecache",
   383  		TrieCleanCacheRejournal: 60 * time.Minute,
   384  		TrieDirtyCache:          5,
   385  		TrieTimeout:             60 * time.Minute,
   386  		SnapshotCache:           5,
   387  	}
   388  	ethBackend, err := eth.New(stack, ethConf)
   389  	if err != nil {
   390  		t.Fatalf("could not create eth backend: %v", err)
   391  	}
   392  	// Create some blocks and import them
   393  	chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
   394  		ethash.NewFaker(), ethBackend.ChainDb(), genBlocks, genfunc)
   395  	_, err = ethBackend.BlockChain().InsertChain(chain)
   396  	if err != nil {
   397  		t.Fatalf("could not create import blocks: %v", err)
   398  	}
   399  	// Set up handler
   400  	filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{})
   401  	handler, err := newHandler(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
   402  	if err != nil {
   403  		t.Fatalf("could not create graphql service: %v", err)
   404  	}
   405  	return handler, chain
   406  }