github.com/ethw3/go-ethereuma@v0.0.0-20221013053120-c14602a4c23c/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  	"fmt"
    21  	"io"
    22  	"math/big"
    23  	"net/http"
    24  	"strings"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/ethw3/go-ethereuma/common"
    29  	"github.com/ethw3/go-ethereuma/consensus/ethash"
    30  	"github.com/ethw3/go-ethereuma/core"
    31  	"github.com/ethw3/go-ethereuma/core/types"
    32  	"github.com/ethw3/go-ethereuma/core/vm"
    33  	"github.com/ethw3/go-ethereuma/crypto"
    34  	"github.com/ethw3/go-ethereuma/eth"
    35  	"github.com/ethw3/go-ethereuma/eth/ethconfig"
    36  	"github.com/ethw3/go-ethereuma/eth/filters"
    37  	"github.com/ethw3/go-ethereuma/node"
    38  	"github.com/ethw3/go-ethereuma/params"
    39  
    40  	"github.com/stretchr/testify/assert"
    41  )
    42  
    43  func TestBuildSchema(t *testing.T) {
    44  	ddir := t.TempDir()
    45  	// Copy config
    46  	conf := node.DefaultConfig
    47  	conf.DataDir = ddir
    48  	stack, err := node.New(&conf)
    49  	if err != nil {
    50  		t.Fatalf("could not create new node: %v", err)
    51  	}
    52  	defer stack.Close()
    53  	// Make sure the schema can be parsed and matched up to the object model.
    54  	if err := newHandler(stack, nil, nil, []string{}, []string{}); err != nil {
    55  		t.Errorf("Could not construct GraphQL handler: %v", err)
    56  	}
    57  }
    58  
    59  // Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint
    60  func TestGraphQLBlockSerialization(t *testing.T) {
    61  	stack := createNode(t, true, false)
    62  	defer stack.Close()
    63  	// start node
    64  	if err := stack.Start(); err != nil {
    65  		t.Fatalf("could not start node: %v", err)
    66  	}
    67  
    68  	for i, tt := range []struct {
    69  		body string
    70  		want string
    71  		code int
    72  	}{
    73  		{ // Should return latest block
    74  			body: `{"query": "{block{number}}","variables": null}`,
    75  			want: `{"data":{"block":{"number":10}}}`,
    76  			code: 200,
    77  		},
    78  		{ // Should return info about latest block
    79  			body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`,
    80  			want: `{"data":{"block":{"number":10,"gasUsed":0,"gasLimit":11500000}}}`,
    81  			code: 200,
    82  		},
    83  		{
    84  			body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`,
    85  			want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`,
    86  			code: 200,
    87  		},
    88  		{
    89  			body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`,
    90  			want: `{"data":{"block":null}}`,
    91  			code: 200,
    92  		},
    93  		{
    94  			body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`,
    95  			want: `{"data":{"block":null}}`,
    96  			code: 200,
    97  		},
    98  		{
    99  			body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`,
   100  			want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`,
   101  			code: 200,
   102  		},
   103  		{
   104  			body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`,
   105  			want: `{"data":{"block":null}}`,
   106  			code: 200,
   107  		},
   108  		{
   109  			body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`,
   110  			want: `{"data":{"block":null}}`,
   111  			code: 200,
   112  		},
   113  		{
   114  			body: `{"query": "{block(number:\"0xbad\"){number,gasUsed,gasLimit}}","variables": null}`,
   115  			want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0xbad\": invalid syntax"}],"data":{}}`,
   116  			code: 400,
   117  		},
   118  		{ // hex strings are currently not supported. If that's added to the spec, this test will need to change
   119  			body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`,
   120  			want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`,
   121  			code: 400,
   122  		},
   123  		{
   124  			body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`,
   125  			want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`,
   126  			code: 400,
   127  		},
   128  		{
   129  			body: `{"query": "{bleh{number}}","variables": null}"`,
   130  			want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`,
   131  			code: 400,
   132  		},
   133  		// should return `estimateGas` as decimal
   134  		{
   135  			body: `{"query": "{block{ estimateGas(data:{}) }}"}`,
   136  			want: `{"data":{"block":{"estimateGas":53000}}}`,
   137  			code: 200,
   138  		},
   139  		// should return `status` as decimal
   140  		{
   141  			body: `{"query": "{block {number call (data : {from : \"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\", to: \"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\", data :\"0x12a7b914\"}){data status}}}"}`,
   142  			want: `{"data":{"block":{"number":10,"call":{"data":"0x","status":1}}}}`,
   143  			code: 200,
   144  		},
   145  	} {
   146  		resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
   147  		if err != nil {
   148  			t.Fatalf("could not post: %v", err)
   149  		}
   150  		bodyBytes, err := io.ReadAll(resp.Body)
   151  		if err != nil {
   152  			t.Fatalf("could not read from response body: %v", err)
   153  		}
   154  		if have := string(bodyBytes); have != tt.want {
   155  			t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
   156  		}
   157  		if tt.code != resp.StatusCode {
   158  			t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
   159  		}
   160  	}
   161  }
   162  
   163  func TestGraphQLBlockSerializationEIP2718(t *testing.T) {
   164  	stack := createNode(t, true, true)
   165  	defer stack.Close()
   166  	// start node
   167  	if err := stack.Start(); err != nil {
   168  		t.Fatalf("could not start node: %v", err)
   169  	}
   170  
   171  	for i, tt := range []struct {
   172  		body string
   173  		want string
   174  		code int
   175  	}{
   176  		{
   177  			body: `{"query": "{block {number transactions { from { address } to { address } value hash type accessList { address storageKeys } index}}}"}`,
   178  			want: `{"data":{"block":{"number":1,"transactions":[{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x64","hash":"0xd864c9d7d37fade6b70164740540c06dd58bb9c3f6b46101908d6339db6a6a7b","type":0,"accessList":[],"index":0},{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x32","hash":"0x19b35f8187b4e15fb59a9af469dca5dfa3cd363c11d372058c12f6482477b474","type":1,"accessList":[{"address":"0x0000000000000000000000000000000000000dad","storageKeys":["0x0000000000000000000000000000000000000000000000000000000000000000"]}],"index":1}]}}}`,
   179  			code: 200,
   180  		},
   181  	} {
   182  		resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
   183  		if err != nil {
   184  			t.Fatalf("could not post: %v", err)
   185  		}
   186  		bodyBytes, err := io.ReadAll(resp.Body)
   187  		if err != nil {
   188  			t.Fatalf("could not read from response body: %v", err)
   189  		}
   190  		if have := string(bodyBytes); have != tt.want {
   191  			t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
   192  		}
   193  		if tt.code != resp.StatusCode {
   194  			t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
   195  		}
   196  	}
   197  }
   198  
   199  // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
   200  func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
   201  	stack := createNode(t, false, false)
   202  	defer stack.Close()
   203  	if err := stack.Start(); err != nil {
   204  		t.Fatalf("could not start node: %v", err)
   205  	}
   206  	body := strings.NewReader(`{"query": "{block{number}}","variables": null}`)
   207  	resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", body)
   208  	if err != nil {
   209  		t.Fatalf("could not post: %v", err)
   210  	}
   211  	// make sure the request is not handled successfully
   212  	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
   213  }
   214  
   215  func createNode(t *testing.T, gqlEnabled bool, txEnabled bool) *node.Node {
   216  	stack, err := node.New(&node.Config{
   217  		HTTPHost: "127.0.0.1",
   218  		HTTPPort: 0,
   219  		WSHost:   "127.0.0.1",
   220  		WSPort:   0,
   221  	})
   222  	if err != nil {
   223  		t.Fatalf("could not create node: %v", err)
   224  	}
   225  	if !gqlEnabled {
   226  		return stack
   227  	}
   228  	if !txEnabled {
   229  		createGQLService(t, stack)
   230  	} else {
   231  		createGQLServiceWithTransactions(t, stack)
   232  	}
   233  	return stack
   234  }
   235  
   236  func createGQLService(t *testing.T, stack *node.Node) {
   237  	// create backend
   238  	ethConf := &ethconfig.Config{
   239  		Genesis: &core.Genesis{
   240  			Config:     params.AllEthashProtocolChanges,
   241  			GasLimit:   11500000,
   242  			Difficulty: big.NewInt(1048576),
   243  		},
   244  		Ethash: ethash.Config{
   245  			PowMode: ethash.ModeFake,
   246  		},
   247  		NetworkId:               1337,
   248  		TrieCleanCache:          5,
   249  		TrieCleanCacheJournal:   "triecache",
   250  		TrieCleanCacheRejournal: 60 * time.Minute,
   251  		TrieDirtyCache:          5,
   252  		TrieTimeout:             60 * time.Minute,
   253  		SnapshotCache:           5,
   254  	}
   255  	ethBackend, err := eth.New(stack, ethConf)
   256  	if err != nil {
   257  		t.Fatalf("could not create eth backend: %v", err)
   258  	}
   259  	// Create some blocks and import them
   260  	chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
   261  		ethash.NewFaker(), ethBackend.ChainDb(), 10, func(i int, gen *core.BlockGen) {})
   262  	_, err = ethBackend.BlockChain().InsertChain(chain)
   263  	if err != nil {
   264  		t.Fatalf("could not create import blocks: %v", err)
   265  	}
   266  	// create gql service
   267  	filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{})
   268  	err = New(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
   269  	if err != nil {
   270  		t.Fatalf("could not create graphql service: %v", err)
   271  	}
   272  }
   273  
   274  func createGQLServiceWithTransactions(t *testing.T, stack *node.Node) {
   275  	// create backend
   276  	key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   277  	address := crypto.PubkeyToAddress(key.PublicKey)
   278  	funds := big.NewInt(1000000000000000)
   279  	dad := common.HexToAddress("0x0000000000000000000000000000000000000dad")
   280  
   281  	ethConf := &ethconfig.Config{
   282  		Genesis: &core.Genesis{
   283  			Config:     params.AllEthashProtocolChanges,
   284  			GasLimit:   11500000,
   285  			Difficulty: big.NewInt(1048576),
   286  			Alloc: core.GenesisAlloc{
   287  				address: {Balance: funds},
   288  				// The address 0xdad sloads 0x00 and 0x01
   289  				dad: {
   290  					Code: []byte{
   291  						byte(vm.PC),
   292  						byte(vm.PC),
   293  						byte(vm.SLOAD),
   294  						byte(vm.SLOAD),
   295  					},
   296  					Nonce:   0,
   297  					Balance: big.NewInt(0),
   298  				},
   299  			},
   300  			BaseFee: big.NewInt(params.InitialBaseFee),
   301  		},
   302  		Ethash: ethash.Config{
   303  			PowMode: ethash.ModeFake,
   304  		},
   305  		NetworkId:               1337,
   306  		TrieCleanCache:          5,
   307  		TrieCleanCacheJournal:   "triecache",
   308  		TrieCleanCacheRejournal: 60 * time.Minute,
   309  		TrieDirtyCache:          5,
   310  		TrieTimeout:             60 * time.Minute,
   311  		SnapshotCache:           5,
   312  	}
   313  
   314  	ethBackend, err := eth.New(stack, ethConf)
   315  	if err != nil {
   316  		t.Fatalf("could not create eth backend: %v", err)
   317  	}
   318  	signer := types.LatestSigner(ethConf.Genesis.Config)
   319  
   320  	legacyTx, _ := types.SignNewTx(key, signer, &types.LegacyTx{
   321  		Nonce:    uint64(0),
   322  		To:       &dad,
   323  		Value:    big.NewInt(100),
   324  		Gas:      50000,
   325  		GasPrice: big.NewInt(params.InitialBaseFee),
   326  	})
   327  	envelopTx, _ := types.SignNewTx(key, signer, &types.AccessListTx{
   328  		ChainID:  ethConf.Genesis.Config.ChainID,
   329  		Nonce:    uint64(1),
   330  		To:       &dad,
   331  		Gas:      30000,
   332  		GasPrice: big.NewInt(params.InitialBaseFee),
   333  		Value:    big.NewInt(50),
   334  		AccessList: types.AccessList{{
   335  			Address:     dad,
   336  			StorageKeys: []common.Hash{{0}},
   337  		}},
   338  	})
   339  
   340  	// Create some blocks and import them
   341  	chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
   342  		ethash.NewFaker(), ethBackend.ChainDb(), 1, func(i int, b *core.BlockGen) {
   343  			b.SetCoinbase(common.Address{1})
   344  			b.AddTx(legacyTx)
   345  			b.AddTx(envelopTx)
   346  		})
   347  
   348  	_, err = ethBackend.BlockChain().InsertChain(chain)
   349  	if err != nil {
   350  		t.Fatalf("could not create import blocks: %v", err)
   351  	}
   352  	// create gql service
   353  	filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{})
   354  	err = New(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
   355  	if err != nil {
   356  		t.Fatalf("could not create graphql service: %v", err)
   357  	}
   358  }