graphql_test.go 12 KB

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