github.com/theQRL/go-zond@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/theQRL/go-zond/common" 31 "github.com/theQRL/go-zond/consensus" 32 "github.com/theQRL/go-zond/consensus/beacon" 33 "github.com/theQRL/go-zond/consensus/ethash" 34 "github.com/theQRL/go-zond/core" 35 "github.com/theQRL/go-zond/core/types" 36 "github.com/theQRL/go-zond/core/vm" 37 "github.com/theQRL/go-zond/crypto" 38 "github.com/theQRL/go-zond/node" 39 "github.com/theQRL/go-zond/params" 40 "github.com/theQRL/go-zond/zond" 41 "github.com/theQRL/go-zond/zond/ethconfig" 42 "github.com/theQRL/go-zond/zond/filters" 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":"0xcf08"}}}`, 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 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 153 if err != nil { 154 t.Fatalf("could not post: %v", err) 155 } 156 bodyBytes, err := io.ReadAll(resp.Body) 157 resp.Body.Close() 158 if err != nil { 159 t.Fatalf("could not read from response body: %v", err) 160 } 161 if have := string(bodyBytes); have != tt.want { 162 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 163 } 164 if tt.code != resp.StatusCode { 165 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 166 } 167 } 168 } 169 170 func TestGraphQLBlockSerializationEIP2718(t *testing.T) { 171 // Account for signing txes 172 var ( 173 key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 174 address = crypto.PubkeyToAddress(key.PublicKey) 175 funds = big.NewInt(1000000000000000) 176 dad = common.HexToAddress("0x0000000000000000000000000000000000000dad") 177 ) 178 stack := createNode(t) 179 defer stack.Close() 180 genesis := &core.Genesis{ 181 Config: params.AllEthashProtocolChanges, 182 GasLimit: 11500000, 183 Difficulty: big.NewInt(1048576), 184 Alloc: core.GenesisAlloc{ 185 address: {Balance: funds}, 186 // The address 0xdad sloads 0x00 and 0x01 187 dad: { 188 Code: []byte{byte(vm.PC), byte(vm.PC), byte(vm.SLOAD), byte(vm.SLOAD)}, 189 Nonce: 0, 190 Balance: big.NewInt(0), 191 }, 192 }, 193 BaseFee: big.NewInt(params.InitialBaseFee), 194 } 195 signer := types.LatestSigner(genesis.Config) 196 newGQLService(t, stack, false, genesis, 1, func(i int, gen *core.BlockGen) { 197 gen.SetCoinbase(common.Address{1}) 198 tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{ 199 Nonce: uint64(0), 200 To: &dad, 201 Value: big.NewInt(100), 202 Gas: 50000, 203 GasPrice: big.NewInt(params.InitialBaseFee), 204 }) 205 gen.AddTx(tx) 206 tx, _ = types.SignNewTx(key, signer, &types.AccessListTx{ 207 ChainID: genesis.Config.ChainID, 208 Nonce: uint64(1), 209 To: &dad, 210 Gas: 30000, 211 GasPrice: big.NewInt(params.InitialBaseFee), 212 Value: big.NewInt(50), 213 AccessList: types.AccessList{{ 214 Address: dad, 215 StorageKeys: []common.Hash{{0}}, 216 }}, 217 }) 218 gen.AddTx(tx) 219 }) 220 // start node 221 if err := stack.Start(); err != nil { 222 t.Fatalf("could not start node: %v", err) 223 } 224 225 for i, tt := range []struct { 226 body string 227 want string 228 code int 229 }{ 230 { 231 body: `{"query": "{block {number transactions { from { address } to { address } value hash type accessList { address storageKeys } index}}}"}`, 232 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"}]}}}`, 233 code: 200, 234 }, 235 } { 236 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 237 if err != nil { 238 t.Fatalf("could not post: %v", err) 239 } 240 bodyBytes, err := io.ReadAll(resp.Body) 241 resp.Body.Close() 242 if err != nil { 243 t.Fatalf("could not read from response body: %v", err) 244 } 245 if have := string(bodyBytes); have != tt.want { 246 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 247 } 248 if tt.code != resp.StatusCode { 249 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 250 } 251 } 252 } 253 254 // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint 255 func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) { 256 stack := createNode(t) 257 defer stack.Close() 258 if err := stack.Start(); err != nil { 259 t.Fatalf("could not start node: %v", err) 260 } 261 body := strings.NewReader(`{"query": "{block{number}}","variables": null}`) 262 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", body) 263 if err != nil { 264 t.Fatalf("could not post: %v", err) 265 } 266 resp.Body.Close() 267 // make sure the request is not handled successfully 268 assert.Equal(t, http.StatusNotFound, resp.StatusCode) 269 } 270 271 func TestGraphQLConcurrentResolvers(t *testing.T) { 272 var ( 273 key, _ = crypto.GenerateKey() 274 addr = crypto.PubkeyToAddress(key.PublicKey) 275 dadStr = "0x0000000000000000000000000000000000000dad" 276 dad = common.HexToAddress(dadStr) 277 genesis = &core.Genesis{ 278 Config: params.AllEthashProtocolChanges, 279 GasLimit: 11500000, 280 Difficulty: big.NewInt(1048576), 281 Alloc: core.GenesisAlloc{ 282 addr: {Balance: big.NewInt(params.Ether)}, 283 dad: { 284 // LOG0(0, 0), LOG0(0, 0), RETURN(0, 0) 285 Code: common.Hex2Bytes("60006000a060006000a060006000f3"), 286 Nonce: 0, 287 Balance: big.NewInt(0), 288 }, 289 }, 290 } 291 signer = types.LatestSigner(genesis.Config) 292 stack = createNode(t) 293 ) 294 defer stack.Close() 295 296 var tx *types.Transaction 297 handler, chain := newGQLService(t, stack, false, genesis, 1, func(i int, gen *core.BlockGen) { 298 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 299 gen.AddTx(tx) 300 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 1, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 301 gen.AddTx(tx) 302 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 2, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 303 gen.AddTx(tx) 304 }) 305 // start node 306 if err := stack.Start(); err != nil { 307 t.Fatalf("could not start node: %v", err) 308 } 309 310 for i, tt := range []struct { 311 body string 312 want string 313 }{ 314 // Multiple txes race to get/set the block hash. 315 { 316 body: "{block { transactions { logs { account { address } } } } }", 317 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), 318 }, 319 // Multiple fields of a tx race to resolve it. Happens in this case 320 // because resolving the tx body belonging to a log is delayed. 321 { 322 body: `{block { logs(filter: {}) { transaction { nonce value gasPrice }}}}`, 323 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"}}]}}`, 324 }, 325 // Multiple txes of a block race to set/retrieve receipts of a block. 326 { 327 body: "{block { transactions { status gasUsed } } }", 328 want: `{"block":{"transactions":[{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"},{"status":"0x1","gasUsed":"0x5508"}]}}`, 329 }, 330 // Multiple fields of block race to resolve header and body. 331 { 332 body: "{ block { number hash gasLimit ommerCount transactionCount totalDifficulty } }", 333 want: fmt.Sprintf(`{"block":{"number":"0x1","hash":"%s","gasLimit":"0xaf79e0","ommerCount":"0x0","transactionCount":"0x3","totalDifficulty":"0x200000"}}`, chain[len(chain)-1].Hash()), 334 }, 335 // Multiple fields of a block race to resolve the header and body. 336 { 337 body: fmt.Sprintf(`{ transaction(hash: "%s") { block { number hash gasLimit ommerCount transactionCount } } }`, tx.Hash()), 338 want: fmt.Sprintf(`{"transaction":{"block":{"number":"0x1","hash":"%s","gasLimit":"0xaf79e0","ommerCount":"0x0","transactionCount":"0x3"}}}`, chain[len(chain)-1].Hash()), 339 }, 340 // Account fields race the resolve the state object. 341 { 342 body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, dadStr), 343 want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x60006000a060006000a060006000f3"}}}`, 344 }, 345 // Test values for a non-existent account. 346 { 347 body: fmt.Sprintf(`{ block { account(address: "%s") { balance transactionCount code } } }`, "0x1111111111111111111111111111111111111111"), 348 want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x"}}}`, 349 }, 350 } { 351 res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{}) 352 if res.Errors != nil { 353 t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors) 354 } 355 have, err := json.Marshal(res.Data) 356 if err != nil { 357 t.Fatalf("failed to encode graphql response for testcase #%d: %s", i, err) 358 } 359 if string(have) != tt.want { 360 t.Errorf("response unmatch for testcase #%d.\nExpected:\n%s\nGot:\n%s\n", i, tt.want, have) 361 } 362 } 363 } 364 365 func TestWithdrawals(t *testing.T) { 366 var ( 367 key, _ = crypto.GenerateKey() 368 addr = crypto.PubkeyToAddress(key.PublicKey) 369 370 genesis = &core.Genesis{ 371 Config: params.AllEthashProtocolChanges, 372 GasLimit: 11500000, 373 Difficulty: common.Big1, 374 Alloc: core.GenesisAlloc{ 375 addr: {Balance: big.NewInt(params.Ether)}, 376 }, 377 } 378 signer = types.LatestSigner(genesis.Config) 379 stack = createNode(t) 380 ) 381 defer stack.Close() 382 383 handler, _ := newGQLService(t, stack, true, genesis, 1, func(i int, gen *core.BlockGen) { 384 tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{To: &common.Address{}, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 385 gen.AddTx(tx) 386 gen.AddWithdrawal(&types.Withdrawal{ 387 Validator: 5, 388 Address: common.Address{}, 389 Amount: 10, 390 }) 391 }) 392 // start node 393 if err := stack.Start(); err != nil { 394 t.Fatalf("could not start node: %v", err) 395 } 396 397 for i, tt := range []struct { 398 body string 399 want string 400 }{ 401 // Genesis block has no withdrawals. 402 { 403 body: "{block(number: 0) { withdrawalsRoot withdrawals { index } } }", 404 want: `{"block":{"withdrawalsRoot":null,"withdrawals":null}}`, 405 }, 406 { 407 body: "{block(number: 1) { withdrawalsRoot withdrawals { validator amount } } }", 408 want: `{"block":{"withdrawalsRoot":"0x8418fc1a48818928f6692f148e9b10e99a88edc093b095cb8ca97950284b553d","withdrawals":[{"validator":"0x5","amount":"0xa"}]}}`, 409 }, 410 } { 411 res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{}) 412 if res.Errors != nil { 413 t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors) 414 } 415 have, err := json.Marshal(res.Data) 416 if err != nil { 417 t.Fatalf("failed to encode graphql response for testcase #%d: %s", i, err) 418 } 419 if string(have) != tt.want { 420 t.Errorf("response unmatch for testcase #%d.\nhave:\n%s\nwant:\n%s", i, have, tt.want) 421 } 422 } 423 } 424 425 func createNode(t *testing.T) *node.Node { 426 stack, err := node.New(&node.Config{ 427 HTTPHost: "127.0.0.1", 428 HTTPPort: 0, 429 WSHost: "127.0.0.1", 430 WSPort: 0, 431 HTTPTimeouts: node.DefaultConfig.HTTPTimeouts, 432 }) 433 if err != nil { 434 t.Fatalf("could not create node: %v", err) 435 } 436 return stack 437 } 438 439 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) { 440 ethConf := ðconfig.Config{ 441 Genesis: gspec, 442 NetworkId: 1337, 443 TrieCleanCache: 5, 444 TrieDirtyCache: 5, 445 TrieTimeout: 60 * time.Minute, 446 SnapshotCache: 5, 447 } 448 var engine consensus.Engine = ethash.NewFaker() 449 if shanghai { 450 engine = beacon.NewFaker() 451 chainCfg := gspec.Config 452 chainCfg.TerminalTotalDifficultyPassed = true 453 chainCfg.TerminalTotalDifficulty = common.Big0 454 // GenerateChain will increment timestamps by 10. 455 // Shanghai upgrade at block 1. 456 shanghaiTime := uint64(5) 457 chainCfg.ShanghaiTime = &shanghaiTime 458 } 459 ethBackend, err := eth.New(stack, ethConf) 460 if err != nil { 461 t.Fatalf("could not create eth backend: %v", err) 462 } 463 // Create some blocks and import them 464 chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(), 465 engine, ethBackend.ChainDb(), genBlocks, genfunc) 466 _, err = ethBackend.BlockChain().InsertChain(chain) 467 if err != nil { 468 t.Fatalf("could not create import blocks: %v", err) 469 } 470 // Set up handler 471 filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{}) 472 handler, err := newHandler(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{}) 473 if err != nil { 474 t.Fatalf("could not create graphql service: %v", err) 475 } 476 return handler, chain 477 }