github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/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 "fmt" 21 "io/ioutil" 22 "math/big" 23 "net/http" 24 "strings" 25 "testing" 26 "time" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/consensus/ethash" 30 "github.com/ethereum/go-ethereum/core" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/core/vm" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/eth" 35 "github.com/ethereum/go-ethereum/eth/ethconfig" 36 "github.com/ethereum/go-ethereum/node" 37 "github.com/ethereum/go-ethereum/params" 38 39 "github.com/stretchr/testify/assert" 40 ) 41 42 func TestBuildSchema(t *testing.T) { 43 ddir := t.TempDir() 44 // Copy config 45 conf := node.DefaultConfig 46 conf.DataDir = ddir 47 stack, err := node.New(&conf) 48 defer stack.Close() 49 if err != nil { 50 t.Fatalf("could not create new node: %v", err) 51 } 52 // Make sure the schema can be parsed and matched up to the object model. 53 if err := newHandler(stack, nil, []string{}, []string{}); err != nil { 54 t.Errorf("Could not construct GraphQL handler: %v", err) 55 } 56 } 57 58 // Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint 59 func TestGraphQLBlockSerialization(t *testing.T) { 60 stack := createNode(t, true, false) 61 defer stack.Close() 62 // start node 63 if err := stack.Start(); err != nil { 64 t.Fatalf("could not start node: %v", err) 65 } 66 67 for i, tt := range []struct { 68 body string 69 want string 70 code int 71 }{ 72 { // Should return latest block 73 body: `{"query": "{block{number}}","variables": null}`, 74 want: `{"data":{"block":{"number":10}}}`, 75 code: 200, 76 }, 77 { // Should return info about latest block 78 body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`, 79 want: `{"data":{"block":{"number":10,"gasUsed":0,"gasLimit":11500000}}}`, 80 code: 200, 81 }, 82 { 83 body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`, 84 want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`, 85 code: 200, 86 }, 87 { 88 body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`, 89 want: `{"data":{"block":null}}`, 90 code: 200, 91 }, 92 { 93 body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`, 94 want: `{"data":{"block":null}}`, 95 code: 200, 96 }, 97 { 98 body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`, 99 want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`, 100 code: 200, 101 }, 102 { 103 body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`, 104 want: `{"data":{"block":null}}`, 105 code: 200, 106 }, 107 { 108 body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`, 109 want: `{"data":{"block":null}}`, 110 code: 200, 111 }, 112 { 113 body: `{"query": "{block(number:\"0xbad\"){number,gasUsed,gasLimit}}","variables": null}`, 114 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0xbad\": invalid syntax"}],"data":{}}`, 115 code: 400, 116 }, 117 { // hex strings are currently not supported. If that's added to the spec, this test will need to change 118 body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`, 119 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`, 120 code: 400, 121 }, 122 { 123 body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`, 124 want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`, 125 code: 400, 126 }, 127 { 128 body: `{"query": "{bleh{number}}","variables": null}"`, 129 want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`, 130 code: 400, 131 }, 132 // should return `estimateGas` as decimal 133 { 134 body: `{"query": "{block{ estimateGas(data:{}) }}"}`, 135 want: `{"data":{"block":{"estimateGas":53000}}}`, 136 code: 200, 137 }, 138 // should return `status` as decimal 139 { 140 body: `{"query": "{block {number call (data : {from : \"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\", to: \"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\", data :\"0x12a7b914\"}){data status}}}"}`, 141 want: `{"data":{"block":{"number":10,"call":{"data":"0x","status":1}}}}`, 142 code: 200, 143 }, 144 } { 145 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 146 if err != nil { 147 t.Fatalf("could not post: %v", err) 148 } 149 bodyBytes, err := ioutil.ReadAll(resp.Body) 150 if err != nil { 151 t.Fatalf("could not read from response body: %v", err) 152 } 153 if have := string(bodyBytes); have != tt.want { 154 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 155 } 156 if tt.code != resp.StatusCode { 157 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 158 } 159 } 160 } 161 162 func TestGraphQLBlockSerializationEIP2718(t *testing.T) { 163 stack := createNode(t, true, true) 164 defer stack.Close() 165 // start node 166 if err := stack.Start(); err != nil { 167 t.Fatalf("could not start node: %v", err) 168 } 169 170 for i, tt := range []struct { 171 body string 172 want string 173 code int 174 }{ 175 { 176 body: `{"query": "{block {number transactions { from { address } to { address } value hash type accessList { address storageKeys } index}}}"}`, 177 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}]}}}`, 178 code: 200, 179 }, 180 } { 181 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body)) 182 if err != nil { 183 t.Fatalf("could not post: %v", err) 184 } 185 bodyBytes, err := ioutil.ReadAll(resp.Body) 186 if err != nil { 187 t.Fatalf("could not read from response body: %v", err) 188 } 189 if have := string(bodyBytes); have != tt.want { 190 t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want) 191 } 192 if tt.code != resp.StatusCode { 193 t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code) 194 } 195 } 196 } 197 198 // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint 199 func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) { 200 stack := createNode(t, false, false) 201 defer stack.Close() 202 if err := stack.Start(); err != nil { 203 t.Fatalf("could not start node: %v", err) 204 } 205 body := strings.NewReader(`{"query": "{block{number}}","variables": null}`) 206 resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", body) 207 if err != nil { 208 t.Fatalf("could not post: %v", err) 209 } 210 // make sure the request is not handled successfully 211 assert.Equal(t, http.StatusNotFound, resp.StatusCode) 212 } 213 214 func createNode(t *testing.T, gqlEnabled bool, txEnabled bool) *node.Node { 215 stack, err := node.New(&node.Config{ 216 HTTPHost: "127.0.0.1", 217 HTTPPort: 0, 218 WSHost: "127.0.0.1", 219 WSPort: 0, 220 }) 221 if err != nil { 222 t.Fatalf("could not create node: %v", err) 223 } 224 if !gqlEnabled { 225 return stack 226 } 227 if !txEnabled { 228 createGQLService(t, stack) 229 } else { 230 createGQLServiceWithTransactions(t, stack) 231 } 232 return stack 233 } 234 235 func createGQLService(t *testing.T, stack *node.Node) { 236 // create backend 237 ethConf := ðconfig.Config{ 238 Genesis: &core.Genesis{ 239 Config: params.AllEthashProtocolChanges, 240 GasLimit: 11500000, 241 Difficulty: big.NewInt(1048576), 242 }, 243 Ethash: ethash.Config{ 244 PowMode: ethash.ModeFake, 245 }, 246 NetworkId: 1337, 247 TrieCleanCache: 5, 248 TrieCleanCacheJournal: "triecache", 249 TrieCleanCacheRejournal: 60 * time.Minute, 250 TrieDirtyCache: 5, 251 TrieTimeout: 60 * time.Minute, 252 SnapshotCache: 5, 253 } 254 ethBackend, err := eth.New(stack, ethConf) 255 if err != nil { 256 t.Fatalf("could not create eth backend: %v", err) 257 } 258 // Create some blocks and import them 259 chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(), 260 ethash.NewFaker(), ethBackend.ChainDb(), 10, func(i int, gen *core.BlockGen) {}) 261 _, err = ethBackend.BlockChain().InsertChain(chain) 262 if err != nil { 263 t.Fatalf("could not create import blocks: %v", err) 264 } 265 // create gql service 266 err = New(stack, ethBackend.APIBackend, []string{}, []string{}) 267 if err != nil { 268 t.Fatalf("could not create graphql service: %v", err) 269 } 270 } 271 272 func createGQLServiceWithTransactions(t *testing.T, stack *node.Node) { 273 // create backend 274 key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 275 address := crypto.PubkeyToAddress(key.PublicKey) 276 funds := big.NewInt(1000000000000000) 277 dad := common.HexToAddress("0x0000000000000000000000000000000000000dad") 278 279 ethConf := ðconfig.Config{ 280 Genesis: &core.Genesis{ 281 Config: params.AllEthashProtocolChanges, 282 GasLimit: 11500000, 283 Difficulty: big.NewInt(1048576), 284 Alloc: core.GenesisAlloc{ 285 address: {Balance: funds}, 286 // The address 0xdad sloads 0x00 and 0x01 287 dad: { 288 Code: []byte{ 289 byte(vm.PC), 290 byte(vm.PC), 291 byte(vm.SLOAD), 292 byte(vm.SLOAD), 293 }, 294 Nonce: 0, 295 Balance: big.NewInt(0), 296 }, 297 }, 298 BaseFee: big.NewInt(params.InitialBaseFee), 299 }, 300 Ethash: ethash.Config{ 301 PowMode: ethash.ModeFake, 302 }, 303 NetworkId: 1337, 304 TrieCleanCache: 5, 305 TrieCleanCacheJournal: "triecache", 306 TrieCleanCacheRejournal: 60 * time.Minute, 307 TrieDirtyCache: 5, 308 TrieTimeout: 60 * time.Minute, 309 SnapshotCache: 5, 310 } 311 312 ethBackend, err := eth.New(stack, ethConf) 313 if err != nil { 314 t.Fatalf("could not create eth backend: %v", err) 315 } 316 signer := types.LatestSigner(ethConf.Genesis.Config) 317 318 legacyTx, _ := types.SignNewTx(key, signer, &types.LegacyTx{ 319 Nonce: uint64(0), 320 To: &dad, 321 Value: big.NewInt(100), 322 Gas: 50000, 323 GasPrice: big.NewInt(params.InitialBaseFee), 324 }) 325 envelopTx, _ := types.SignNewTx(key, signer, &types.AccessListTx{ 326 ChainID: ethConf.Genesis.Config.ChainID, 327 Nonce: uint64(1), 328 To: &dad, 329 Gas: 30000, 330 GasPrice: big.NewInt(params.InitialBaseFee), 331 Value: big.NewInt(50), 332 AccessList: types.AccessList{{ 333 Address: dad, 334 StorageKeys: []common.Hash{{0}}, 335 }}, 336 }) 337 338 // Create some blocks and import them 339 chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(), 340 ethash.NewFaker(), ethBackend.ChainDb(), 1, func(i int, b *core.BlockGen) { 341 b.SetCoinbase(common.Address{1}) 342 b.AddTx(legacyTx) 343 b.AddTx(envelopTx) 344 }) 345 346 _, err = ethBackend.BlockChain().InsertChain(chain) 347 if err != nil { 348 t.Fatalf("could not create import blocks: %v", err) 349 } 350 // create gql service 351 err = New(stack, ethBackend.APIBackend, []string{}, []string{}) 352 if err != nil { 353 t.Fatalf("could not create graphql service: %v", err) 354 } 355 }