github.com/phillinzzz/newBsc@v1.1.6/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/phillinzzz/newBsc/common" 29 "github.com/phillinzzz/newBsc/consensus/ethash" 30 "github.com/phillinzzz/newBsc/core" 31 "github.com/phillinzzz/newBsc/core/types" 32 "github.com/phillinzzz/newBsc/core/vm" 33 "github.com/phillinzzz/newBsc/crypto" 34 "github.com/phillinzzz/newBsc/eth" 35 "github.com/phillinzzz/newBsc/eth/ethconfig" 36 "github.com/phillinzzz/newBsc/node" 37 "github.com/phillinzzz/newBsc/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":"0x4f7b8d718145233dcf7f29e34a969c63dd4de8715c054ea2af022b66c4f4633e","type":0,"accessList":[],"index":0},{"from":{"address":"0x71562b71999873db5b286df957af199ec94617f7"},"to":{"address":"0x0000000000000000000000000000000000000dad"},"value":"0x32","hash":"0x9c6c2c045b618fe87add0e49ba3ca00659076ecae00fd51de3ba5d4ccf9dbf40","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(1000000000) 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 }, 301 Ethash: ethash.Config{ 302 PowMode: ethash.ModeFake, 303 }, 304 NetworkId: 1337, 305 TrieCleanCache: 5, 306 TrieCleanCacheJournal: "triecache", 307 TrieCleanCacheRejournal: 60 * time.Minute, 308 TrieDirtyCache: 5, 309 TrieTimeout: 60 * time.Minute, 310 SnapshotCache: 5, 311 } 312 313 ethBackend, err := eth.New(stack, ethConf) 314 if err != nil { 315 t.Fatalf("could not create eth backend: %v", err) 316 } 317 signer := types.LatestSigner(ethConf.Genesis.Config) 318 319 legacyTx, _ := types.SignNewTx(key, signer, &types.LegacyTx{ 320 Nonce: uint64(0), 321 To: &dad, 322 Value: big.NewInt(100), 323 Gas: 50000, 324 GasPrice: big.NewInt(1), 325 }) 326 envelopTx, _ := types.SignNewTx(key, signer, &types.AccessListTx{ 327 ChainID: ethConf.Genesis.Config.ChainID, 328 Nonce: uint64(1), 329 To: &dad, 330 Gas: 30000, 331 GasPrice: big.NewInt(1), 332 Value: big.NewInt(50), 333 AccessList: types.AccessList{{ 334 Address: dad, 335 StorageKeys: []common.Hash{{0}}, 336 }}, 337 }) 338 339 // Create some blocks and import them 340 chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(), 341 ethash.NewFaker(), ethBackend.ChainDb(), 1, func(i int, b *core.BlockGen) { 342 b.SetCoinbase(common.Address{1}) 343 b.AddTx(legacyTx) 344 b.AddTx(envelopTx) 345 }) 346 347 _, err = ethBackend.BlockChain().InsertChain(chain) 348 if err != nil { 349 t.Fatalf("could not create import blocks: %v", err) 350 } 351 // create gql service 352 err = New(stack, ethBackend.APIBackend, []string{}, []string{}) 353 if err != nil { 354 t.Fatalf("could not create graphql service: %v", err) 355 } 356 }