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