Skip to content

Commit eb2a1df

Browse files
atoulmeholiman
andauthored
graphql: use a decimal representation for gas limit and gas used (#21883)
This changes the JSON encoding of blocks returned by the API to have decimal instead of hexadecimal numbers. The spec wants it this way. Co-authored-by: Martin Holst Swende <martin@swende.se>
1 parent 664903d commit eb2a1df

2 files changed

Lines changed: 150 additions & 81 deletions

File tree

‎graphql/graphql.go‎

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ package graphql
2020
import (
2121
"context"
2222
"errors"
23+
"fmt"
24+
"strconv"
2325
"time"
2426

2527
"github.com/ethereum/go-ethereum"
@@ -39,6 +41,37 @@ var (
3941
errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash")
4042
)
4143

44+
type Long int64
45+
46+
// ImplementsGraphQLType returns true if Long implements the provided GraphQL type.
47+
func (b Long) ImplementsGraphQLType(name string) bool { return name == "Long" }
48+
49+
// UnmarshalGraphQL unmarshals the provided GraphQL query data.
50+
func (b *Long) UnmarshalGraphQL(input interface{}) error {
51+
var err error
52+
switch input := input.(type) {
53+
case string:
54+
// uncomment to support hex values
55+
//if strings.HasPrefix(input, "0x") {
56+
// // apply leniency and support hex representations of longs.
57+
// value, err := hexutil.DecodeUint64(input)
58+
// *b = Long(value)
59+
// return err
60+
//} else {
61+
value, err := strconv.ParseInt(input, 10, 64)
62+
*b = Long(value)
63+
return err
64+
//}
65+
case int32:
66+
*b = Long(input)
67+
case int64:
68+
*b = Long(input)
69+
default:
70+
err = fmt.Errorf("unexpected type %T for Long", input)
71+
}
72+
return err
73+
}
74+
4275
// Account represents an Ethereum account at a particular block.
4376
type Account struct {
4477
backend ethapi.Backend
@@ -415,13 +448,13 @@ func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) {
415448
return b.receipts, nil
416449
}
417450

418-
func (b *Block) Number(ctx context.Context) (hexutil.Uint64, error) {
451+
func (b *Block) Number(ctx context.Context) (Long, error) {
419452
header, err := b.resolveHeader(ctx)
420453
if err != nil {
421454
return 0, err
422455
}
423456

424-
return hexutil.Uint64(header.Number.Uint64()), nil
457+
return Long(header.Number.Uint64()), nil
425458
}
426459

427460
func (b *Block) Hash(ctx context.Context) (common.Hash, error) {
@@ -435,20 +468,20 @@ func (b *Block) Hash(ctx context.Context) (common.Hash, error) {
435468
return b.hash, nil
436469
}
437470

438-
func (b *Block) GasLimit(ctx context.Context) (hexutil.Uint64, error) {
471+
func (b *Block) GasLimit(ctx context.Context) (Long, error) {
439472
header, err := b.resolveHeader(ctx)
440473
if err != nil {
441474
return 0, err
442475
}
443-
return hexutil.Uint64(header.GasLimit), nil
476+
return Long(header.GasLimit), nil
444477
}
445478

446-
func (b *Block) GasUsed(ctx context.Context) (hexutil.Uint64, error) {
479+
func (b *Block) GasUsed(ctx context.Context) (Long, error) {
447480
header, err := b.resolveHeader(ctx)
448481
if err != nil {
449482
return 0, err
450483
}
451-
return hexutil.Uint64(header.GasUsed), nil
484+
return Long(header.GasUsed), nil
452485
}
453486

454487
func (b *Block) Parent(ctx context.Context) (*Block, error) {
@@ -902,11 +935,14 @@ type Resolver struct {
902935
}
903936

904937
func (r *Resolver) Block(ctx context.Context, args struct {
905-
Number *hexutil.Uint64
938+
Number *Long
906939
Hash *common.Hash
907940
}) (*Block, error) {
908941
var block *Block
909942
if args.Number != nil {
943+
if *args.Number < 0 {
944+
return nil, nil
945+
}
910946
number := rpc.BlockNumber(*args.Number)
911947
numberOrHash := rpc.BlockNumberOrHashWithNumber(number)
912948
block = &Block{
@@ -939,10 +975,10 @@ func (r *Resolver) Block(ctx context.Context, args struct {
939975
}
940976

941977
func (r *Resolver) Blocks(ctx context.Context, args struct {
942-
From hexutil.Uint64
943-
To *hexutil.Uint64
978+
From *Long
979+
To *Long
944980
}) ([]*Block, error) {
945-
from := rpc.BlockNumber(args.From)
981+
from := rpc.BlockNumber(*args.From)
946982

947983
var to rpc.BlockNumber
948984
if args.To != nil {

‎graphql/graphql_test.go‎

Lines changed: 104 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,17 @@ package graphql
1919
import (
2020
"fmt"
2121
"io/ioutil"
22+
"math/big"
2223
"net/http"
2324
"strings"
2425
"testing"
2526
"time"
2627

27-
"github.com/ethereum/go-ethereum/common"
2828
"github.com/ethereum/go-ethereum/consensus/ethash"
2929
"github.com/ethereum/go-ethereum/core"
3030
"github.com/ethereum/go-ethereum/eth"
31-
"github.com/ethereum/go-ethereum/miner"
3231
"github.com/ethereum/go-ethereum/node"
33-
"github.com/stretchr/testify/assert"
32+
"github.com/ethereum/go-ethereum/params"
3433
)
3534

3635
func TestBuildSchema(t *testing.T) {
@@ -45,29 +44,95 @@ func TestBuildSchema(t *testing.T) {
4544
}
4645

4746
// Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint
48-
func TestGraphQLHTTPOnSamePort_GQLRequest_Successful(t *testing.T) {
47+
func TestGraphQLBlockSerialization(t *testing.T) {
4948
stack := createNode(t, true)
5049
defer stack.Close()
5150
// start node
5251
if err := stack.Start(); err != nil {
5352
t.Fatalf("could not start node: %v", err)
5453
}
55-
// create http request
56-
body := strings.NewReader("{\"query\": \"{block{number}}\",\"variables\": null}")
57-
gqlReq, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
58-
if err != nil {
59-
t.Error("could not issue new http request ", err)
60-
}
61-
gqlReq.Header.Set("Content-Type", "application/json")
62-
// read from response
63-
resp := doHTTPRequest(t, gqlReq)
64-
bodyBytes, err := ioutil.ReadAll(resp.Body)
65-
if err != nil {
66-
t.Fatalf("could not read from response body: %v", err)
54+
55+
for i, tt := range []struct {
56+
body string
57+
want string
58+
code int
59+
}{
60+
{ // Should return latest block
61+
body: `{"query": "{block{number}}","variables": null}`,
62+
want: `{"data":{"block":{"number":10}}}`,
63+
code: 200,
64+
},
65+
{ // Should return info about latest block
66+
body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`,
67+
want: `{"data":{"block":{"number":10,"gasUsed":0,"gasLimit":11500000}}}`,
68+
code: 200,
69+
},
70+
{
71+
body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`,
72+
want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`,
73+
code: 200,
74+
},
75+
{
76+
body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`,
77+
want: `{"data":{"block":null}}`,
78+
code: 200,
79+
},
80+
{
81+
body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`,
82+
want: `{"data":{"block":null}}`,
83+
code: 200,
84+
},
85+
{
86+
body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`,
87+
want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`,
88+
code: 200,
89+
},
90+
{
91+
body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`,
92+
want: `{"data":{"block":null}}`,
93+
code: 200,
94+
},
95+
{
96+
body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`,
97+
want: `{"data":{"block":null}}`,
98+
code: 200,
99+
},
100+
{
101+
body: `{"query": "{block(number:\"0xbad\"){number,gasUsed,gasLimit}}","variables": null}`,
102+
want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0xbad\": invalid syntax"}],"data":{}}`,
103+
code: 400,
104+
},
105+
{ // hex strings are currently not supported. If that's added to the spec, this test will need to change
106+
body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`,
107+
want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`,
108+
code: 400,
109+
},
110+
{
111+
body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`,
112+
want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`,
113+
code: 400,
114+
},
115+
{
116+
body: `{"query": "{bleh{number}}","variables": null}"`,
117+
want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`,
118+
code: 400,
119+
},
120+
} {
121+
resp, err := http.Post(fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), "application/json", strings.NewReader(tt.body))
122+
if err != nil {
123+
t.Fatalf("could not post: %v", err)
124+
}
125+
bodyBytes, err := ioutil.ReadAll(resp.Body)
126+
if err != nil {
127+
t.Fatalf("could not read from response body: %v", err)
128+
}
129+
if have := string(bodyBytes); have != tt.want {
130+
t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
131+
}
132+
if tt.code != resp.StatusCode {
133+
t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
134+
}
67135
}
68-
expected := "{\"data\":{\"block\":{\"number\":\"0x0\"}}}"
69-
assert.Equal(t, 200, resp.StatusCode)
70-
assert.Equal(t, expected, string(bodyBytes))
71136
}
72137

73138
// Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
@@ -77,49 +142,22 @@ func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
77142
if err := stack.Start(); err != nil {
78143
t.Fatalf("could not start node: %v", err)
79144
}
80-
81-
// create http request
82-
body := strings.NewReader("{\"query\": \"{block{number}}\",\"variables\": null}")
83-
gqlReq, err := http.NewRequest(http.MethodPost, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
145+
body := strings.NewReader(`{"query": "{block{number}}","variables": null}`)
146+
resp, err := http.Post(fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), "application/json", body)
84147
if err != nil {
85-
t.Error("could not issue new http request ", err)
148+
t.Fatalf("could not post: %v", err)
86149
}
87-
gqlReq.Header.Set("Content-Type", "application/json")
88-
// read from response
89-
resp := doHTTPRequest(t, gqlReq)
90150
bodyBytes, err := ioutil.ReadAll(resp.Body)
91151
if err != nil {
92152
t.Fatalf("could not read from response body: %v", err)
93153
}
94154
// make sure the request is not handled successfully
95-
assert.Equal(t, 404, resp.StatusCode)
96-
assert.Equal(t, "404 page not found\n", string(bodyBytes))
97-
}
98-
99-
// Tests that 400 is returned when an invalid RPC request is made.
100-
func TestGraphQL_BadRequest(t *testing.T) {
101-
stack := createNode(t, true)
102-
defer stack.Close()
103-
// start node
104-
if err := stack.Start(); err != nil {
105-
t.Fatalf("could not start node: %v", err)
155+
if want, have := "404 page not found\n", string(bodyBytes); have != want {
156+
t.Errorf("have:\n%v\nwant:\n%v", have, want)
106157
}
107-
// create http request
108-
body := strings.NewReader("{\"query\": \"{bleh{number}}\",\"variables\": null}")
109-
gqlReq, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
110-
if err != nil {
111-
t.Error("could not issue new http request ", err)
112-
}
113-
gqlReq.Header.Set("Content-Type", "application/json")
114-
// read from response
115-
resp := doHTTPRequest(t, gqlReq)
116-
bodyBytes, err := ioutil.ReadAll(resp.Body)
117-
if err != nil {
118-
t.Fatalf("could not read from response body: %v", err)
158+
if want, have := 404, resp.StatusCode; want != have {
159+
t.Errorf("wrong statuscode, have:\n%v\nwant:%v", have, want)
119160
}
120-
expected := "{\"errors\":[{\"message\":\"Cannot query field \\\"bleh\\\" on type \\\"Query\\\".\",\"locations\":[{\"line\":1,\"column\":2}]}]}"
121-
assert.Equal(t, expected, string(bodyBytes))
122-
assert.Equal(t, 400, resp.StatusCode)
123161
}
124162

125163
func createNode(t *testing.T, gqlEnabled bool) *node.Node {
@@ -135,21 +173,20 @@ func createNode(t *testing.T, gqlEnabled bool) *node.Node {
135173
if !gqlEnabled {
136174
return stack
137175
}
138-
139176
createGQLService(t, stack, "127.0.0.1:9393")
140-
141177
return stack
142178
}
143179

144180
func createGQLService(t *testing.T, stack *node.Node, endpoint string) {
145-
// create backend (use a config which is light on mem consumption)
181+
// create backend
146182
ethConf := &eth.Config{
147-
Genesis: core.DeveloperGenesisBlock(15, common.Address{}),
148-
Miner: miner.Config{
149-
Etherbase: common.HexToAddress("0xaabb"),
183+
Genesis: &core.Genesis{
184+
Config: params.AllEthashProtocolChanges,
185+
GasLimit: 11500000,
186+
Difficulty: big.NewInt(1048576),
150187
},
151188
Ethash: ethash.Config{
152-
PowMode: ethash.ModeTest,
189+
PowMode: ethash.ModeFake,
153190
},
154191
NetworkId: 1337,
155192
TrieCleanCache: 5,
@@ -163,20 +200,16 @@ func createGQLService(t *testing.T, stack *node.Node, endpoint string) {
163200
if err != nil {
164201
t.Fatalf("could not create eth backend: %v", err)
165202
}
166-
203+
// Create some blocks and import them
204+
chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
205+
ethash.NewFaker(), ethBackend.ChainDb(), 10, func(i int, gen *core.BlockGen) {})
206+
_, err = ethBackend.BlockChain().InsertChain(chain)
207+
if err != nil {
208+
t.Fatalf("could not create import blocks: %v", err)
209+
}
167210
// create gql service
168211
err = New(stack, ethBackend.APIBackend, []string{}, []string{})
169212
if err != nil {
170213
t.Fatalf("could not create graphql service: %v", err)
171214
}
172215
}
173-
174-
func doHTTPRequest(t *testing.T, req *http.Request) *http.Response {
175-
client := &http.Client{}
176-
resp, err := client.Do(req)
177-
if err != nil {
178-
t.Fatal("could not issue a GET request to the given endpoint", err)
179-
180-
}
181-
return resp
182-
}

0 commit comments

Comments
 (0)