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