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