github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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/ethash" 32 "github.com/ethereum/go-ethereum/core" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/core/vm" 35 "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 // Copy config 48 conf := node.DefaultConfig 49 conf.DataDir = ddir 50 stack, err := node.New(&conf) 51 if err != nil { 52 t.Fatalf("could not create new node: %v", err) 53 } 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 t.Errorf("Could not construct GraphQL handler: %v", err) 58 } 59 } 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 genesis := &core.Genesis{ 66 Config: params.AllEthashProtocolChanges, 67 GasLimit: 11500000, 68 Difficulty: big.NewInt(1048576), 69 } 70 newGQLService(t, stack, genesis, 10, func(i int, gen *core.BlockGen) {}) 71 // start node 72 if err := stack.Start(); err != nil { 73 t.Fatalf("could not start node: %v", err) 74 } 75 76 for i, tt := range []struct { 77 body string 78 want string 79 code int 80 }{ 81 { // Should return latest block 82 body: `{"query": "{block{number}}","variables": null}`, 83 want: `{"data":{"block":{"number":10}}}`, 84 code: 200, 85 }, 86 { // Should return info about latest block 87 body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`, 88 want: `{"data":{"block":{"number":10,"gasUsed":0,"gasLimit":11500000}}}`, 89 code: 200, 90 }, 91 { 92 body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`, 93 want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`, 94 code: 200, 95 }, 96 { 97 body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`, 98 want: `{"data":{"block":null}}`, 99 code: 200, 100 }, 101 { 102 body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`, 103 want: `{"data":{"block":null}}`, 104 code: 200, 105 }, 106 { 107 body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`, 108 want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`, 109 code: 200, 110 }, 111 { 112 body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`, 113 want: `{"data":{"block":null}}`, 114 code: 200, 115 }, 116 { 117 body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`, 118 want: `{"data":{"block":null}}`, 119 code: 200, 120 }, 121 { 122 body: `{"query": "{block(number:\"0xbad\"){number,gasUsed,gasLimit}}","variables": null}`, 123 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0xbad\": invalid syntax"}],"data":{}}`, 124 code: 400, 125 }, 126 { // hex strings are currently not supported. If that's added to the spec, this test will need to change 127 body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`, 128 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`, 129 code: 400, 130 }, 131 { 132 body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`, 133 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`, 134 code: 400, 135 }, 136 { 137 body: `{"query": "{bleh{number}}","variables": null}"`, 138 want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`, 139 code: 400, 140 }, 141 // should return `estimateGas` as decimal 142 { 143 body: `{"query": "{block{ estimateGas(data:{}) }}"}`, 144 want: `{"data":{"block":{"estimateGas":53000}}}`, 145 code: 200, 146 }, 147 // should return `status` as decimal 148 { 149 body: `{"query": "{block {number call (data : {from : \"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\", to: \"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\", data :\"0x12a7b914\"}){data status}}}"}`, 150 want: `{"data":{"block":{"number":10,"call":{"data":"0x","status":1}}}}`, 151 code: 200, 152 }, 153 } { 154 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 155 if err != nil { 156 t.Fatalf("could not post: %v", err) 157 } 158 bodyBytes, err := io.ReadAll(resp.Body) 159 if err != nil { 160 t.Fatalf("could not read from response body: %v", err) 161 } 162 if have := string(bodyBytes); have != tt.want { 163 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 164 } 165 if tt.code != resp.StatusCode { 166 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 167 } 168 } 169 } 170 171 func TestGraphQLBlockSerializationEIP2718(t *testing.T) { 172 // Account for signing txes 173 var ( 174 key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 175 address = crypto.PubkeyToAddress(key.PublicKey) 176 funds = big.NewInt(1000000000000000) 177 dad = common.HexToAddress("0x0000000000000000000000000000000000000dad") 178 ) 179 stack := createNode(t) 180 defer stack.Close() 181 genesis := &core.Genesis{ 182 Config: params.AllEthashProtocolChanges, 183 GasLimit: 11500000, 184 Difficulty: big.NewInt(1048576), 185 Alloc: core.GenesisAlloc{ 186 address: {Balance: funds}, 187 // The address 0xdad sloads 0x00 and 0x01 188 dad: { 189 Code: []byte{byte(vm.PC), byte(vm.PC), byte(vm.SLOAD), byte(vm.SLOAD)}, 190 Nonce: 0, 191 Balance: big.NewInt(0), 192 }, 193 }, 194 BaseFee: big.NewInt(params.InitialBaseFee), 195 } 196 signer := types.LatestSigner(genesis.Config) 197 newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) { 198 gen.SetCoinbase(common.Address{1}) 199 tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{ 200 Nonce: uint64(0), 201 To: &dad, 202 Value: big.NewInt(100), 203 Gas: 50000, 204 GasPrice: big.NewInt(params.InitialBaseFee), 205 }) 206 gen.AddTx(tx) 207 tx, _ = types.SignNewTx(key, signer, &types.AccessListTx{ 208 ChainID: genesis.Config.ChainID, 209 Nonce: uint64(1), 210 To: &dad, 211 Gas: 30000, 212 GasPrice: big.NewInt(params.InitialBaseFee), 213 Value: big.NewInt(50), 214 AccessList: types.AccessList{{ 215 Address: dad, 216 StorageKeys: []common.Hash{{0}}, 217 }}, 218 }) 219 gen.AddTx(tx) 220 }) 221 // start node 222 if err := stack.Start(); err != nil { 223 t.Fatalf("could not start node: %v", err) 224 } 225 226 for i, tt := range []struct { 227 body string 228 want string 229 code int 230 }{ 231 { 232 body: `{"query": "{block {number transactions { from { address } to { address } value hash type accessList { address storageKeys } index}}}"}`, 233 want: `{"data":{"block":{"number":1,"transactions":[{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x64","hash":"0xd864c9d7d37fade6b70164740540c06dd58bb9c3f6b46101908d6339db6a6a7b","type":0,"accessList":[],"index":0},{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x32","hash":"0x19b35f8187b4e15fb59a9af469dca5dfa3cd363c11d372058c12f6482477b474","type":1,"accessList":[{"address":"0x0000000000000000000000000000000000000dad","storageKeys":["0x0000000000000000000000000000000000000000000000000000000000000000"]}],"index":1}]}}}`, 234 code: 200, 235 }, 236 } { 237 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 238 if err != nil { 239 t.Fatalf("could not post: %v", err) 240 } 241 bodyBytes, err := io.ReadAll(resp.Body) 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 // make sure the request is not handled successfully 267 assert.Equal(t, http.StatusNotFound, resp.StatusCode) 268 } 269 270 func TestGraphQLTransactionLogs(t *testing.T) { 271 var ( 272 key, _ = crypto.GenerateKey() 273 addr = crypto.PubkeyToAddress(key.PublicKey) 274 dadStr = "0x0000000000000000000000000000000000000dad" 275 dad = common.HexToAddress(dadStr) 276 genesis = &core.Genesis{ 277 Config: params.AllEthashProtocolChanges, 278 GasLimit: 11500000, 279 Difficulty: big.NewInt(1048576), 280 Alloc: core.GenesisAlloc{ 281 addr: {Balance: big.NewInt(params.Ether)}, 282 dad: { 283 // LOG0(0, 0), LOG0(0, 0), RETURN(0, 0) 284 Code: common.Hex2Bytes("60006000a060006000a060006000f3"), 285 Nonce: 0, 286 Balance: big.NewInt(0), 287 }, 288 }, 289 } 290 signer = types.LatestSigner(genesis.Config) 291 stack = createNode(t) 292 ) 293 defer stack.Close() 294 295 handler := newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) { 296 tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 297 gen.AddTx(tx) 298 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 1, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 299 gen.AddTx(tx) 300 tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 2, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)}) 301 gen.AddTx(tx) 302 }) 303 // start node 304 if err := stack.Start(); err != nil { 305 t.Fatalf("could not start node: %v", err) 306 } 307 query := `{block { transactions { logs { account { address } } } } }` 308 res := handler.Schema.Exec(context.Background(), query, "", map[string]interface{}{}) 309 if res.Errors != nil { 310 t.Fatalf("graphql query failed: %v", res.Errors) 311 } 312 have, err := json.Marshal(res.Data) 313 if err != nil { 314 t.Fatalf("failed to encode graphql response: %s", err) 315 } 316 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) 317 if string(have) != want { 318 t.Errorf("response unmatch. expected %s, got %s", want, have) 319 } 320 } 321 322 func createNode(t *testing.T) *node.Node { 323 stack, err := node.New(&node.Config{ 324 HTTPHost: "127.0.0.1", 325 HTTPPort: 0, 326 WSHost: "127.0.0.1", 327 WSPort: 0, 328 }) 329 if err != nil { 330 t.Fatalf("could not create node: %v", err) 331 } 332 return stack 333 } 334 335 func newGQLService(t *testing.T, stack *node.Node, gspec *core.Genesis, genBlocks int, genfunc func(i int, gen *core.BlockGen)) *handler { 336 ethConf := ðconfig.Config{ 337 Genesis: gspec, 338 Ethash: ethash.Config{ 339 PowMode: ethash.ModeFake, 340 }, 341 NetworkId: 1337, 342 TrieCleanCache: 5, 343 TrieCleanCacheJournal: "triecache", 344 TrieCleanCacheRejournal: 60 * time.Minute, 345 TrieDirtyCache: 5, 346 TrieTimeout: 60 * time.Minute, 347 SnapshotCache: 5, 348 } 349 ethBackend, err := eth.New(stack, ethConf) 350 if err != nil { 351 t.Fatalf("could not create eth backend: %v", err) 352 } 353 // Create some blocks and import them 354 chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(), 355 ethash.NewFaker(), ethBackend.ChainDb(), genBlocks, genfunc) 356 _, err = ethBackend.BlockChain().InsertChain(chain) 357 if err != nil { 358 t.Fatalf("could not create import blocks: %v", err) 359 } 360 // Set up handler 361 filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{}) 362 handler, err := newHandler(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{}) 363 if err != nil { 364 t.Fatalf("could not create graphql service: %v", err) 365 } 366 return handler 367 }