github.com/ethereum/go-ethereum@v1.16.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/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/consensus/beacon" 32 "github.com/ethereum/go-ethereum/consensus/ethash" 33 "github.com/ethereum/go-ethereum/core" 34 "github.com/ethereum/go-ethereum/core/rawdb" 35 "github.com/ethereum/go-ethereum/core/types" 36 "github.com/ethereum/go-ethereum/core/vm" 37 "github.com/ethereum/go-ethereum/crypto" 38 "github.com/ethereum/go-ethereum/eth" 39 "github.com/ethereum/go-ethereum/eth/ethconfig" 40 "github.com/ethereum/go-ethereum/eth/filters" 41 "github.com/ethereum/go-ethereum/node" 42 "github.com/ethereum/go-ethereum/params" 43 44 "github.com/stretchr/testify/assert" 45 ) 46 47 func TestBuildSchema(t *testing.T) { 48 ddir := t.TempDir() 49 // Copy config 50 conf := node.DefaultConfig 51 conf.DataDir = ddir 52 stack, err := node.New(&conf) 53 if err != nil { 54 t.Fatalf("could not create new node: %v", err) 55 } 56 defer stack.Close() 57 // Make sure the schema can be parsed and matched up to the object model. 58 if _, err := newHandler(stack, nil, nil, []string{}, []string{}); err != nil { 59 t.Errorf("Could not construct GraphQL handler: %v", err) 60 } 61 } 62 63 // Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint 64 func TestGraphQLBlockSerialization(t *testing.T) { 65 stack := createNode(t) 66 defer stack.Close() 67 genesis := &core.Genesis{ 68 Config: params.AllEthashProtocolChanges, 69 GasLimit: 11500000, 70 Difficulty: big.NewInt(1048576), 71 } 72 newGQLService(t, stack, false, genesis, 10, func(i int, gen *core.BlockGen) {}) 73 // start node 74 if err := stack.Start(); err != nil { 75 t.Fatalf("could not start node: %v", err) 76 } 77 78 for i, tt := range []struct { 79 body string 80 want string 81 code int 82 }{ 83 { // Should return latest block 84 body: `{"query": "{block{number}}","variables": null}`, 85 want: `{"data":{"block":{"number":"0xa"}}}`, 86 code: 200, 87 }, 88 { // Should return info about latest block 89 body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`, 90 want: `{"data":{"block":{"number":"0xa","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`, 91 code: 200, 92 }, 93 { 94 body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`, 95 want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`, 96 code: 200, 97 }, 98 { 99 body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`, 100 want: `{"data":{"block":null}}`, 101 code: 200, 102 }, 103 { 104 body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`, 105 want: `{"data":{"block":null}}`, 106 code: 200, 107 }, 108 { 109 body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`, 110 want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`, 111 code: 200, 112 }, 113 { 114 body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`, 115 want: `{"data":{"block":null}}`, 116 code: 200, 117 }, 118 { 119 body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`, 120 want: `{"data":{"block":null}}`, 121 code: 200, 122 }, 123 { 124 body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`, 125 want: `{"data":{"block":{"number":"0x0","gasUsed":"0x0","gasLimit":"0xaf79e0"}}}`, 126 //want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`, 127 code: 200, 128 }, 129 { 130 body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`, 131 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`, 132 code: 400, 133 }, 134 { 135 body: `{"query": "{bleh{number}}","variables": null}"`, 136 want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`, 137 code: 400, 138 }, 139 // should return `estimateGas` as decimal 140 { 141 body: `{"query": "{block{ estimateGas(data:{}) }}"}`, 142 want: `{"data":{"block":{"estimateGas":"0xd221"}}}`, 143 code: 200, 144 }, 145 // should return `status` as decimal 146 { 147 body: `{"query": "{block {number call (data : {from : \"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\", to: \"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\", data :\"0x12a7b914\"}){data status}}}"}`, 148 want: `{"data":{"block":{"number":"0xa","call":{"data":"0x","status":"0x1"}}}}`, 149 code: 200, 150 }, 151 { 152 body: `{"query": "{blocks {number}}"}`, 153 want: `{"errors":[{"message":"from block number must be specified","path":["blocks"]}],"data":null}`, 154 code: 400, 155 }, 156 } { 157 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 158 if err != nil { 159 t.Fatalf("could not post: %v", err) 160 } 161 bodyBytes, err := io.ReadAll(resp.Body) 162 resp.Body.Close() 163 if err != nil { 164 t.Fatalf("could not read from response body: %v", err) 165 } 166 if have := string(bodyBytes); have != tt.want { 167 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 168 } 169 if tt.code != resp.StatusCode { 170 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 171 } 172 if ctype := resp.Header.Get("Content-Type"); ctype != "application/json" { 173 t.Errorf("testcase %d \nwrong Content-Type, have: %v, want: %v", i, ctype, "application/json") 174 } 175 } 176 } 177 178 func TestGraphQLBlockSerializationEIP2718(t *testing.T) { 179 // Account for signing txes 180 var ( 181 key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 182 address = crypto.PubkeyToAddress(key.PublicKey) 183 funds = big.NewInt(1000000000000000) 184 dad = common.HexToAddress("0x0000000000000000000000000000000000000dad") 185 ) 186 stack := createNode(t) 187 defer stack.Close() 188 genesis := &core.Genesis{ 189 Config: params.AllEthashProtocolChanges, 190 GasLimit: 11500000, 191 Difficulty: big.NewInt(1048576), 192 Alloc: types.GenesisAlloc{ 193 address: {Balance: funds}, 194 // The address 0xdad sloads 0x00 and 0x01 195 dad: { 196 Code: []byte{byte(vm.PC), byte(vm.PC), byte(vm.SLOAD), byte(vm.SLOAD)}, 197 Nonce: 0, 198 Balance: big.NewInt(0), 199 }, 200 }, 201 BaseFee: big.NewInt(params.InitialBaseFee), 202 } 203 signer := types.LatestSigner(genesis.Config) 204 newGQLService(t, stack, false, genesis, 1, func(i int, gen *core.BlockGen) { 205 gen.SetCoinbase(common.Address{1}) 206 tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{ 207 Nonce: uint64(0), 208 To: &dad, 209 Value: big.NewInt(100), 210 Gas: 50000, 211 GasPrice: big.NewInt(params.InitialBaseFee), 212 }) 213 gen.AddTx(tx) 214 tx, _ = types.SignNewTx(key, signer, &types.AccessListTx{ 215 ChainID: genesis.Config.ChainID, 216 Nonce: uint64(1), 217 To: &dad, 218 Gas: 30000, 219 GasPrice: big.NewInt(params.InitialBaseFee), 220 Value: big.NewInt(50), 221 AccessList: types.AccessList{{ 222 Address: dad, 223 StorageKeys: []common.Hash{{0}}, 224 }}, 225 }) 226 gen.AddTx(tx) 227 }) 228 // start node 229 if err := stack.Start(); err != nil { 230 t.Fatalf("could not start node: %v", err) 231 } 232 233 for i, tt := range []struct { 234 body string 235 want string 236 code int 237 }{ 238 { 239 body: `{"query": "{block {number transactions { from { address } to { address } value hash type accessList { address storageKeys } index}}}"}`, 240 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"}]}}}`, 241 code: 200, 242 }, 243 } { 244 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 245 if err != nil { 246 t.Fatalf("could not post: %v", err) 247 } 248 bodyBytes, err := io.ReadAll(resp.Body) 249 resp.Body.Close() 250 if err != nil { 251 t.Fatalf("could not read from response body: %v", err) 252 } 253 if have := string(bodyBytes); have != tt.want { 254 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 255 } 256 if tt.code != resp.StatusCode { 257 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 258 } 259 } 260 } 261 262 // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint 263 func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) { 264 stack := createNode(t) 265 defer stack.Close() 266 if err := stack.Start(); err != nil { 267 t.Fatalf("could not start node: %v", err) 268 } 269 body := strings.NewReader(`{"query": "{block{number}}","variables": null}`) 270 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", body) 271 if err != nil { 272 t.Fatalf("could not post: %v", err) 273 } 274 resp.Body.Close() 275 // make sure the request is not handled successfully 276 assert.Equal(t, http.StatusNotFound, resp.StatusCode) 277 } 278 279 func TestGraphQLConcurrentResolvers(t *testing.T) { 280 var ( 281 key, _ = crypto.GenerateKey() 282 addr = crypto.PubkeyToAddress(key.PublicKey) 283 dadStr = "0x0000000000000000000000000000000000000dad" 284 dad = common.HexToAddress(dadStr) 285 genesis = &core.Genesis{ 286 Config: params.AllEthashProtocolChanges, 287 GasLimit: 11500000, 288 Difficulty: big.NewInt(1048576), 289 Alloc: types.GenesisAlloc{ 290 addr: {Balance: big.NewInt(params.Ether)}, 291 dad: { 292 // LOG0(0, 0), LOG0(0, 0), RETURN(0, 0) 293 Code: common.Hex2Bytes("60006000a060006000a060006000f3"), 294 Nonce: 0, 295 Balance: big.NewInt(0), 296 }, 297 }, 298 } 299 signer = types.LatestSigner(genesis.Config) 300 stack = createNode(t) 301 ) 302 defer stack.Close() 303 304 var tx *types.Transaction 305 handler, chain := newGQLService(t, stack, false, genesis, 1, func(i int, gen *core.BlockGen) { 306 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 307 gen.AddTx(tx) 308 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 1, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 309 gen.AddTx(tx) 310 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 2, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 311 gen.AddTx(tx) 312 }) 313 // start node 314 if err := stack.Start(); err != nil { 315 t.Fatalf("could not start node: %v", err) 316 } 317 318 for i, tt := range []struct { 319 body string 320 want string 321 }{ 322 // Multiple txes race to get/set the block hash. 323 { 324 body: "{block { transactions { logs { account { address } } } } }", 325 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), 326 }, 327 // Multiple fields of a tx race to resolve it. Happens in this case 328 // because resolving the tx body belonging to a log is delayed. 329 { 330 body: `{block { logs(filter: {}) { transaction { nonce value gasPrice }}}}`, 331 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"}}]}}`, 332 }, 333 // Multiple txes of a block race to set/retrieve receipts of a block. 334 { 335 body: "{block { transactions { status gasUsed } } }", 336 want: `{"block":{"transactions":[{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"}]}}`, 337 }, 338 // Multiple fields of block race to resolve header and body. 339 { 340 body: "{ block { number hash gasLimit ommerCount transactionCount } }", 341 want: fmt.Sprintf(`{"block":{"number":"0x1","hash":"%s","gasLimit":"0xaf79e0","ommerCount":"0x0","transactionCount":"0x3"}}`, chain[len(chain)-1].Hash()), 342 }, 343 // Multiple fields of a block race to resolve the header and body. 344 { 345 body: fmt.Sprintf(`{ transaction(hash: "%s") { block { number hash gasLimit ommerCount transactionCount } } }`, tx.Hash()), 346 want: fmt.Sprintf(`{"transaction":{"block":{"number":"0x1","hash":"%s","gasLimit":"0xaf79e0","ommerCount":"0x0","transactionCount":"0x3"}}}`, chain[len(chain)-1].Hash()), 347 }, 348 // Account fields race the resolve the state object. 349 { 350 body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, dadStr), 351 want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x60006000a060006000a060006000f3"}}}`, 352 }, 353 // Test values for a non-existent account. 354 { 355 body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, "0x1111111111111111111111111111111111111111"), 356 want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x"}}}`, 357 }, 358 } { 359 res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{}) 360 if res.Errors != nil { 361 t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors) 362 } 363 have, err := json.Marshal(res.Data) 364 if err != nil { 365 t.Fatalf("failed to encode graphql response for testcase #%d: %s", i, err) 366 } 367 if string(have) != tt.want { 368 t.Errorf("response unmatch for testcase #%d.\nExpected:\n%s\nGot:\n%s\n", i, tt.want, have) 369 } 370 } 371 } 372 373 func TestWithdrawals(t *testing.T) { 374 var ( 375 key, _ = crypto.GenerateKey() 376 addr = crypto.PubkeyToAddress(key.PublicKey) 377 378 genesis = &core.Genesis{ 379 Config: params.AllEthashProtocolChanges, 380 GasLimit: 11500000, 381 Difficulty: common.Big1, 382 Alloc: types.GenesisAlloc{ 383 addr: {Balance: big.NewInt(params.Ether)}, 384 }, 385 } 386 signer = types.LatestSigner(genesis.Config) 387 stack = createNode(t) 388 ) 389 defer stack.Close() 390 391 handler, _ := newGQLService(t, stack, true, genesis, 1, func(i int, gen *core.BlockGen) { 392 tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{To: &common.Address{}, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 393 gen.AddTx(tx) 394 gen.AddWithdrawal(&types.Withdrawal{ 395 Validator: 5, 396 Address: common.Address{}, 397 Amount: 10, 398 }) 399 }) 400 // start node 401 if err := stack.Start(); err != nil { 402 t.Fatalf("could not start node: %v", err) 403 } 404 405 for i, tt := range []struct { 406 body string 407 want string 408 }{ 409 // Genesis block has no withdrawals. 410 { 411 body: "{block(number: 0) { withdrawalsRoot withdrawals { index } } }", 412 want: `{"block":{"withdrawalsRoot":null,"withdrawals":null}}`, 413 }, 414 { 415 body: "{block(number: 1) { withdrawalsRoot withdrawals { validator amount } } }", 416 want: `{"block":{"withdrawalsRoot":"0x8418fc1a48818928f6692f148e9b10e99a88edc093b095cb8ca97950284b553d","withdrawals":[{"validator":"0x5","amount":"0xa"}]}}`, 417 }, 418 } { 419 res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{}) 420 if res.Errors != nil { 421 t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors) 422 } 423 have, err := json.Marshal(res.Data) 424 if err != nil { 425 t.Fatalf("failed to encode graphql response for testcase #%d: %s", i, err) 426 } 427 if string(have) != tt.want { 428 t.Errorf("response unmatch for testcase #%d.\nhave:\n%s\nwant:\n%s", i, have, tt.want) 429 } 430 } 431 } 432 433 func createNode(t *testing.T) *node.Node { 434 stack, err := node.New(&node.Config{ 435 HTTPHost: "127.0.0.1", 436 HTTPPort: 0, 437 WSHost: "127.0.0.1", 438 WSPort: 0, 439 HTTPTimeouts: node.DefaultConfig.HTTPTimeouts, 440 }) 441 if err != nil { 442 t.Fatalf("could not create node: %v", err) 443 } 444 return stack 445 } 446 447 func newGQLService(t *testing.T, stack *node.Node, shanghai bool, gspec *core.Genesis, genBlocks int, genfunc func(i int, gen *core.BlockGen)) (*handler, []*types.Block) { 448 ethConf := ðconfig.Config{ 449 Genesis: gspec, 450 NetworkId: 1337, 451 TrieCleanCache: 5, 452 TrieDirtyCache: 5, 453 TrieTimeout: 60 * time.Minute, 454 SnapshotCache: 5, 455 RPCGasCap: 1000000, 456 StateScheme: rawdb.HashScheme, 457 } 458 var engine = beacon.New(ethash.NewFaker()) 459 if shanghai { 460 gspec.Config.TerminalTotalDifficulty = common.Big0 461 gspec.Config.MergeNetsplitBlock = common.Big0 462 // GenerateChain will increment timestamps by 10. 463 // Shanghai upgrade at block 1. 464 shanghaiTime := uint64(5) 465 gspec.Config.ShanghaiTime = &shanghaiTime 466 } 467 468 ethBackend, err := eth.New(stack, ethConf) 469 if err != nil { 470 t.Fatalf("could not create eth backend: %v", err) 471 } 472 // Create some blocks and import them 473 chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(), 474 engine, ethBackend.ChainDb(), genBlocks, genfunc) 475 _, err = ethBackend.BlockChain().InsertChain(chain) 476 if err != nil { 477 t.Fatalf("could not create import blocks: %v", err) 478 } 479 // Set up handler 480 filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{}) 481 handler, err := newHandler(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{}) 482 if err != nil { 483 t.Fatalf("could not create graphql service: %v", err) 484 } 485 return handler, chain 486 }