graphql_test.go 15.5 KB
Newer Older
1
// Copyright 2019 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package graphql

import (
20 21
	"context"
	"encoding/json"
22
	"fmt"
23
	"io"
24
	"math/big"
25 26
	"net/http"
	"strings"
27
	"testing"
28
	"time"
29

30
	"github.com/ethereum/go-ethereum/common"
31 32
	"github.com/ethereum/go-ethereum/consensus/ethash"
	"github.com/ethereum/go-ethereum/core"
33 34 35
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/crypto"
36
	"github.com/ethereum/go-ethereum/eth"
37
	"github.com/ethereum/go-ethereum/eth/ethconfig"
38
	"github.com/ethereum/go-ethereum/eth/filters"
39
	"github.com/ethereum/go-ethereum/node"
40
	"github.com/ethereum/go-ethereum/params"
41 42

	"github.com/stretchr/testify/assert"
43 44 45
)

func TestBuildSchema(t *testing.T) {
46
	ddir := t.TempDir()
47 48 49 50
	// Copy config
	conf := node.DefaultConfig
	conf.DataDir = ddir
	stack, err := node.New(&conf)
51 52 53
	if err != nil {
		t.Fatalf("could not create new node: %v", err)
	}
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 58 59
		t.Errorf("Could not construct GraphQL handler: %v", err)
	}
}
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 66 67 68 69 70
	genesis := &core.Genesis{
		Config:     params.AllEthashProtocolChanges,
		GasLimit:   11500000,
		Difficulty: big.NewInt(1048576),
	}
	newGQLService(t, stack, genesis, 10, func(i int, gen *core.BlockGen) {})
71 72 73 74
	// start node
	if err := stack.Start(); err != nil {
		t.Fatalf("could not start node: %v", err)
	}
75 76 77 78 79 80 81 82

	for i, tt := range []struct {
		body string
		want string
		code int
	}{
		{ // Should return latest block
			body: `{"query": "{block{number}}","variables": null}`,
83
			want: `{"data":{"block":{"number":"0xa"}}}`,
84 85 86 87
			code: 200,
		},
		{ // Should return info about latest block
			body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`,
88
			want: `{"data":{"block":{"number":"0xa","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
89 90 91 92
			code: 200,
		},
		{
			body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`,
93
			want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
94 95 96 97 98 99 100 101 102 103 104 105 106 107
			code: 200,
		},
		{
			body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`,
			want: `{"data":{"block":null}}`,
			code: 200,
		},
		{
			body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`,
			want: `{"data":{"block":null}}`,
			code: 200,
		},
		{
			body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`,
108
			want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
109 110 111 112 113 114 115 116 117 118 119 120 121 122
			code: 200,
		},
		{
			body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`,
			want: `{"data":{"block":null}}`,
			code: 200,
		},
		{
			body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`,
			want: `{"data":{"block":null}}`,
			code: 200,
		},
		{
			body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`,
123 124 125
			want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`,
			//want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`,
			code: 200,
126 127 128 129 130 131 132 133 134 135 136
		},
		{
			body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`,
			want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`,
			code: 400,
		},
		{
			body: `{"query": "{bleh{number}}","variables": null}"`,
			want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`,
			code: 400,
		},
137 138 139
		// should return `estimateGas` as decimal
		{
			body: `{"query": "{block{ estimateGas(data:{}) }}"}`,
140
			want: `{"data":{"block":{"estimateGas":"0xcf08"}}}`,
141 142
			code: 200,
		},
143 144 145
		// should return `status` as decimal
		{
			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 148
			code: 200,
		},
149
	} {
150
		resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
151 152 153
		if err != nil {
			t.Fatalf("could not post: %v", err)
		}
154
		bodyBytes, err := io.ReadAll(resp.Body)
155
		resp.Body.Close()
156 157 158 159 160 161 162 163 164
		if err != nil {
			t.Fatalf("could not read from response body: %v", err)
		}
		if have := string(bodyBytes); have != tt.want {
			t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
		}
		if tt.code != resp.StatusCode {
			t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
		}
165 166 167
	}
}

168
func TestGraphQLBlockSerializationEIP2718(t *testing.T) {
169 170 171 172 173 174 175 176
	// Account for signing txes
	var (
		key, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
		address = crypto.PubkeyToAddress(key.PublicKey)
		funds   = big.NewInt(1000000000000000)
		dad     = common.HexToAddress("0x0000000000000000000000000000000000000dad")
	)
	stack := createNode(t)
177
	defer stack.Close()
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
	genesis := &core.Genesis{
		Config:     params.AllEthashProtocolChanges,
		GasLimit:   11500000,
		Difficulty: big.NewInt(1048576),
		Alloc: core.GenesisAlloc{
			address: {Balance: funds},
			// The address 0xdad sloads 0x00 and 0x01
			dad: {
				Code:    []byte{byte(vm.PC), byte(vm.PC), byte(vm.SLOAD), byte(vm.SLOAD)},
				Nonce:   0,
				Balance: big.NewInt(0),
			},
		},
		BaseFee: big.NewInt(params.InitialBaseFee),
	}
	signer := types.LatestSigner(genesis.Config)
	newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) {
		gen.SetCoinbase(common.Address{1})
		tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{
			Nonce:    uint64(0),
			To:       &dad,
			Value:    big.NewInt(100),
			Gas:      50000,
			GasPrice: big.NewInt(params.InitialBaseFee),
		})
		gen.AddTx(tx)
		tx, _ = types.SignNewTx(key, signer, &types.AccessListTx{
			ChainID:  genesis.Config.ChainID,
			Nonce:    uint64(1),
			To:       &dad,
			Gas:      30000,
			GasPrice: big.NewInt(params.InitialBaseFee),
			Value:    big.NewInt(50),
			AccessList: types.AccessList{{
				Address:     dad,
				StorageKeys: []common.Hash{{0}},
			}},
		})
		gen.AddTx(tx)
	})
218 219 220 221 222 223 224 225 226 227 228 229
	// start node
	if err := stack.Start(); err != nil {
		t.Fatalf("could not start node: %v", err)
	}

	for i, tt := range []struct {
		body string
		want string
		code int
	}{
		{
			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 232 233 234 235 236 237
			code: 200,
		},
	} {
		resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
		if err != nil {
			t.Fatalf("could not post: %v", err)
		}
238
		bodyBytes, err := io.ReadAll(resp.Body)
239
		resp.Body.Close()
240 241 242 243 244 245 246 247 248 249 250 251
		if err != nil {
			t.Fatalf("could not read from response body: %v", err)
		}
		if have := string(bodyBytes); have != tt.want {
			t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
		}
		if tt.code != resp.StatusCode {
			t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
		}
	}
}

252 253
// Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
254
	stack := createNode(t)
255 256 257 258
	defer stack.Close()
	if err := stack.Start(); err != nil {
		t.Fatalf("could not start node: %v", err)
	}
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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
	var (
		key, _  = crypto.GenerateKey()
		addr    = crypto.PubkeyToAddress(key.PublicKey)
		dadStr  = "0x0000000000000000000000000000000000000dad"
		dad     = common.HexToAddress(dadStr)
		genesis = &core.Genesis{
			Config:     params.AllEthashProtocolChanges,
			GasLimit:   11500000,
			Difficulty: big.NewInt(1048576),
			Alloc: core.GenesisAlloc{
				addr: {Balance: big.NewInt(params.Ether)},
				dad: {
					// LOG0(0, 0), LOG0(0, 0), RETURN(0, 0)
					Code:    common.Hex2Bytes("60006000a060006000a060006000f3"),
					Nonce:   0,
					Balance: big.NewInt(0),
				},
			},
		}
		signer = types.LatestSigner(genesis.Config)
		stack  = createNode(t)
	)
	defer stack.Close()

294 295 296
	var tx *types.Transaction
	handler, chain := newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) {
		tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
297 298 299 300 301 302 303 304 305 306
		gen.AddTx(tx)
		tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 1, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
		gen.AddTx(tx)
		tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 2, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
		gen.AddTx(tx)
	})
	// start node
	if err := stack.Start(); err != nil {
		t.Fatalf("could not start node: %v", err)
	}
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

	for i, tt := range []struct {
		body string
		want string
	}{
		// Multiple txes race to get/set the block hash.
		{
			body: "{block { transactions { logs { account { address } } } } }",
			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),
		},
		// Multiple fields of a tx race to resolve it. Happens in this case
		// because resolving the tx body belonging to a log is delayed.
		{
			body: `{block { logs(filter: {}) { transaction { nonce value gasPrice }}}}`,
			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"}}]}}`,
		},
		// Multiple txes of a block race to set/retrieve receipts of a block.
		{
			body: "{block { transactions { status gasUsed } } }",
326
			want: `{"block":{"transactions":[{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"}]}}`,
327 328 329 330
		},
		// Multiple fields of block race to resolve header and body.
		{
			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 334 335
		},
		// Multiple fields of a block race to resolve the header and body.
		{
			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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
		},
		// Account fields race the resolve the state object.
		{
			body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, dadStr),
			want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x60006000a060006000a060006000f3"}}}`,
		},
		// Test values for a non-existent account.
		{
			body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, "0x1111111111111111111111111111111111111111"),
			want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x"}}}`,
		},
	} {
		res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{})
		if res.Errors != nil {
			t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors)
		}
		have, err := json.Marshal(res.Data)
		if err != nil {
			t.Fatalf("failed to encode graphql response for testcase #%d: %s", i, err)
		}
		if string(have) != tt.want {
			t.Errorf("response unmatch for testcase #%d.\nExpected:\n%s\nGot:\n%s\n", i, tt.want, have)
		}
360 361 362 363
	}
}

func createNode(t *testing.T) *node.Node {
364
	stack, err := node.New(&node.Config{
365 366 367 368 369
		HTTPHost:     "127.0.0.1",
		HTTPPort:     0,
		WSHost:       "127.0.0.1",
		WSPort:       0,
		HTTPTimeouts: node.DefaultConfig.HTTPTimeouts,
370 371 372 373 374 375 376
	})
	if err != nil {
		t.Fatalf("could not create node: %v", err)
	}
	return stack
}

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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
		Ethash: ethash.Config{
			PowMode: ethash.ModeFake,
		},
		NetworkId:               1337,
		TrieCleanCache:          5,
		TrieCleanCacheJournal:   "triecache",
		TrieCleanCacheRejournal: 60 * time.Minute,
		TrieDirtyCache:          5,
		TrieTimeout:             60 * time.Minute,
		SnapshotCache:           5,
	}
	ethBackend, err := eth.New(stack, ethConf)
	if err != nil {
		t.Fatalf("could not create eth backend: %v", err)
	}
	// Create some blocks and import them
	chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
397
		ethash.NewFaker(), ethBackend.ChainDb(), genBlocks, genfunc)
398 399 400 401
	_, err = ethBackend.BlockChain().InsertChain(chain)
	if err != nil {
		t.Fatalf("could not create import blocks: %v", err)
	}
402
	// Set up handler
403
	filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{})
404
	handler, err := newHandler(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
405 406 407
	if err != nil {
		t.Fatalf("could not create graphql service: %v", err)
	}
408
	return handler, chain
409
}