graphql.go 39.1 KB
Newer Older
1
// Copyright 2019 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

// Package graphql provides a GraphQL interface to Ethereum node data.
package graphql

import (
	"context"
22
	"errors"
23
	"fmt"
24
	"math/big"
25
	"sort"
26
	"strconv"
27
	"strings"
28
	"sync"
29 30 31 32

	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
33
	"github.com/ethereum/go-ethereum/common/math"
34
	"github.com/ethereum/go-ethereum/consensus/misc"
35 36 37 38
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/eth/filters"
	"github.com/ethereum/go-ethereum/internal/ethapi"
39
	"github.com/ethereum/go-ethereum/rlp"
40 41 42
	"github.com/ethereum/go-ethereum/rpc"
)

43
var (
44
	errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash")
45
)
46

47 48 49 50 51 52 53 54 55 56 57
type Long int64

// ImplementsGraphQLType returns true if Long implements the provided GraphQL type.
func (b Long) ImplementsGraphQLType(name string) bool { return name == "Long" }

// UnmarshalGraphQL unmarshals the provided GraphQL query data.
func (b *Long) UnmarshalGraphQL(input interface{}) error {
	var err error
	switch input := input.(type) {
	case string:
		// uncomment to support hex values
58 59 60 61 62 63 64 65 66 67
		if strings.HasPrefix(input, "0x") {
			// apply leniency and support hex representations of longs.
			value, err := hexutil.DecodeUint64(input)
			*b = Long(value)
			return err
		} else {
			value, err := strconv.ParseInt(input, 10, 64)
			*b = Long(value)
			return err
		}
68 69 70 71
	case int32:
		*b = Long(input)
	case int64:
		*b = Long(input)
72 73
	case float64:
		*b = Long(input)
74 75 76 77 78 79
	default:
		err = fmt.Errorf("unexpected type %T for Long", input)
	}
	return err
}

80 81
// Account represents an Ethereum account at a particular block.
type Account struct {
82
	r             *Resolver
83 84
	address       common.Address
	blockNrOrHash rpc.BlockNumberOrHash
85 86 87 88
}

// getState fetches the StateDB object for an account.
func (a *Account) getState(ctx context.Context) (*state.StateDB, error) {
89
	state, _, err := a.r.backend.StateAndHeaderByNumberOrHash(ctx, a.blockNrOrHash)
90
	return state, err
91 92 93 94 95 96 97 98 99 100 101
}

func (a *Account) Address(ctx context.Context) (common.Address, error) {
	return a.address, nil
}

func (a *Account) Balance(ctx context.Context) (hexutil.Big, error) {
	state, err := a.getState(ctx)
	if err != nil {
		return hexutil.Big{}, err
	}
102 103 104 105 106
	balance := state.GetBalance(a.address)
	if balance == nil {
		return hexutil.Big{}, fmt.Errorf("failed to load balance %x", a.address)
	}
	return hexutil.Big(*balance), nil
107 108 109
}

func (a *Account) TransactionCount(ctx context.Context) (hexutil.Uint64, error) {
110 111
	// Ask transaction pool for the nonce which includes pending transactions
	if blockNr, ok := a.blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
112
		nonce, err := a.r.backend.GetPoolNonce(ctx, a.address)
113 114 115 116 117
		if err != nil {
			return 0, err
		}
		return hexutil.Uint64(nonce), nil
	}
118 119 120 121 122 123 124 125 126 127 128 129
	state, err := a.getState(ctx)
	if err != nil {
		return 0, err
	}
	return hexutil.Uint64(state.GetNonce(a.address)), nil
}

func (a *Account) Code(ctx context.Context) (hexutil.Bytes, error) {
	state, err := a.getState(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
130
	return state.GetCode(a.address), nil
131 132 133 134 135 136 137 138 139 140 141 142
}

func (a *Account) Storage(ctx context.Context, args struct{ Slot common.Hash }) (common.Hash, error) {
	state, err := a.getState(ctx)
	if err != nil {
		return common.Hash{}, err
	}
	return state.GetState(a.address, args.Slot), nil
}

// Log represents an individual log message. All arguments are mandatory.
type Log struct {
143
	r           *Resolver
144 145 146 147 148 149 150 151 152 153
	transaction *Transaction
	log         *types.Log
}

func (l *Log) Transaction(ctx context.Context) *Transaction {
	return l.transaction
}

func (l *Log) Account(ctx context.Context, args BlockNumberArgs) *Account {
	return &Account{
154
		r:             l.r,
155 156
		address:       l.log.Address,
		blockNrOrHash: args.NumberOrLatest(),
157 158 159
	}
}

160 161
func (l *Log) Index(ctx context.Context) hexutil.Uint64 {
	return hexutil.Uint64(l.log.Index)
162 163 164 165 166 167 168
}

func (l *Log) Topics(ctx context.Context) []common.Hash {
	return l.log.Topics
}

func (l *Log) Data(ctx context.Context) hexutil.Bytes {
169
	return l.log.Data
170 171
}

172 173 174
// AccessTuple represents EIP-2930
type AccessTuple struct {
	address     common.Address
175
	storageKeys []common.Hash
176 177 178 179 180 181
}

func (at *AccessTuple) Address(ctx context.Context) common.Address {
	return at.address
}

182
func (at *AccessTuple) StorageKeys(ctx context.Context) []common.Hash {
183 184 185
	return at.storageKeys
}

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
// Withdrawal represents a withdrawal of value from the beacon chain
// by a validator. For details see EIP-4895.
type Withdrawal struct {
	index     uint64
	validator uint64
	address   common.Address
	amount    uint64
}

func (w *Withdrawal) Index(ctx context.Context) hexutil.Uint64 {
	return hexutil.Uint64(w.index)
}

func (w *Withdrawal) Validator(ctx context.Context) hexutil.Uint64 {
	return hexutil.Uint64(w.validator)
}

func (w *Withdrawal) Address(ctx context.Context) common.Address {
	return w.address
}

func (w *Withdrawal) Amount(ctx context.Context) hexutil.Uint64 {
	return hexutil.Uint64(w.amount)
}

211
// Transaction represents an Ethereum transaction.
212 213
// backend and hash are mandatory; all others will be fetched when required.
type Transaction struct {
214 215 216 217
	r    *Resolver
	hash common.Hash // Must be present after initialization
	mu   sync.Mutex
	// mu protects following resources
218 219 220
	tx    *types.Transaction
	block *Block
	index uint64
221 222 223
}

// resolve returns the internal transaction object, fetching it if needed.
224
// It also returns the block the tx belongs to, unless it is a pending tx.
225
func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, *Block) {
226 227 228
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.tx != nil {
229
		return t.tx, t.block
230 231 232 233 234 235 236 237 238 239
	}
	// Try to return an already finalized transaction
	tx, blockHash, _, index, err := t.r.backend.GetTransaction(ctx, t.hash)
	if err == nil && tx != nil {
		t.tx = tx
		blockNrOrHash := rpc.BlockNumberOrHashWithHash(blockHash, false)
		t.block = &Block{
			r:            t.r,
			numberOrHash: &blockNrOrHash,
			hash:         blockHash,
240
		}
241
		t.index = index
242
		return t.tx, t.block
243
	}
244 245
	// No finalized transaction, try to retrieve it from the pool
	t.tx = t.r.backend.GetPoolTransaction(t.hash)
246
	return t.tx, nil
247 248
}

249 250
func (t *Transaction) Hash(ctx context.Context) common.Hash {
	return t.hash
251 252
}

253 254 255 256
func (t *Transaction) InputData(ctx context.Context) hexutil.Bytes {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return hexutil.Bytes{}
257
	}
258
	return tx.Data()
259 260
}

261 262 263 264
func (t *Transaction) Gas(ctx context.Context) hexutil.Uint64 {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return 0
265
	}
266
	return hexutil.Uint64(tx.Gas())
267 268
}

269 270 271 272
func (t *Transaction) GasPrice(ctx context.Context) hexutil.Big {
	tx, block := t.resolve(ctx)
	if tx == nil {
		return hexutil.Big{}
273
	}
274 275
	switch tx.Type() {
	case types.AccessListTxType:
276
		return hexutil.Big(*tx.GasPrice())
277
	case types.DynamicFeeTxType:
278 279
		if block != nil {
			if baseFee, _ := block.BaseFeePerGas(ctx); baseFee != nil {
280
				// price = min(tip, gasFeeCap - baseFee) + baseFee
281
				return (hexutil.Big)(*math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee.ToInt()), tx.GasFeeCap()))
282 283
			}
		}
284
		return hexutil.Big(*tx.GasPrice())
285
	default:
286
		return hexutil.Big(*tx.GasPrice())
287 288 289
	}
}

290
func (t *Transaction) EffectiveGasPrice(ctx context.Context) (*hexutil.Big, error) {
291 292 293
	tx, block := t.resolve(ctx)
	if tx == nil {
		return nil, nil
294
	}
295
	// Pending tx
296
	if block == nil {
297 298
		return nil, nil
	}
299
	header, err := block.resolveHeader(ctx)
300 301 302 303 304 305 306 307 308
	if err != nil || header == nil {
		return nil, err
	}
	if header.BaseFee == nil {
		return (*hexutil.Big)(tx.GasPrice()), nil
	}
	return (*hexutil.Big)(math.BigMin(new(big.Int).Add(tx.GasTipCap(), header.BaseFee), tx.GasFeeCap())), nil
}

309 310 311 312
func (t *Transaction) MaxFeePerGas(ctx context.Context) *hexutil.Big {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return nil
313 314 315
	}
	switch tx.Type() {
	case types.AccessListTxType:
316
		return nil
317
	case types.DynamicFeeTxType:
318
		return (*hexutil.Big)(tx.GasFeeCap())
319
	default:
320
		return nil
321 322 323
	}
}

324 325 326 327
func (t *Transaction) MaxPriorityFeePerGas(ctx context.Context) *hexutil.Big {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return nil
328 329 330
	}
	switch tx.Type() {
	case types.AccessListTxType:
331
		return nil
332
	case types.DynamicFeeTxType:
333
		return (*hexutil.Big)(tx.GasTipCap())
334
	default:
335
		return nil
336
	}
337 338
}

339
func (t *Transaction) EffectiveTip(ctx context.Context) (*hexutil.Big, error) {
340 341 342
	tx, block := t.resolve(ctx)
	if tx == nil {
		return nil, nil
343 344
	}
	// Pending tx
345
	if block == nil {
346 347
		return nil, nil
	}
348
	header, err := block.resolveHeader(ctx)
349 350 351 352 353 354 355 356 357 358 359 360 361 362
	if err != nil || header == nil {
		return nil, err
	}
	if header.BaseFee == nil {
		return (*hexutil.Big)(tx.GasPrice()), nil
	}

	tip, err := tx.EffectiveGasTip(header.BaseFee)
	if err != nil {
		return nil, err
	}
	return (*hexutil.Big)(tip), nil
}

363
func (t *Transaction) Value(ctx context.Context) (hexutil.Big, error) {
364 365 366
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return hexutil.Big{}, nil
367
	}
368 369 370
	if tx.Value() == nil {
		return hexutil.Big{}, fmt.Errorf("invalid transaction value %x", t.hash)
	}
371 372 373
	return hexutil.Big(*tx.Value()), nil
}

374 375 376 377
func (t *Transaction) Nonce(ctx context.Context) hexutil.Uint64 {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return 0
378
	}
379
	return hexutil.Uint64(tx.Nonce())
380 381
}

382 383 384 385
func (t *Transaction) To(ctx context.Context, args BlockNumberArgs) *Account {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return nil
386 387 388
	}
	to := tx.To()
	if to == nil {
389
		return nil
390 391
	}
	return &Account{
392
		r:             t.r,
393 394
		address:       *to,
		blockNrOrHash: args.NumberOrLatest(),
395
	}
396 397
}

398 399 400 401
func (t *Transaction) From(ctx context.Context, args BlockNumberArgs) *Account {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return nil
402
	}
403
	signer := types.LatestSigner(t.r.backend.ChainConfig())
404 405
	from, _ := types.Sender(signer, tx)
	return &Account{
406
		r:             t.r,
407 408
		address:       from,
		blockNrOrHash: args.NumberOrLatest(),
409
	}
410 411
}

412 413 414
func (t *Transaction) Block(ctx context.Context) *Block {
	_, block := t.resolve(ctx)
	return block
415 416
}

417 418
func (t *Transaction) Index(ctx context.Context) *hexutil.Uint64 {
	_, block := t.resolve(ctx)
419 420
	// Pending tx
	if block == nil {
421
		return nil
422
	}
423
	index := hexutil.Uint64(t.index)
424
	return &index
425 426 427 428
}

// getReceipt returns the receipt associated with this transaction, if any.
func (t *Transaction) getReceipt(ctx context.Context) (*types.Receipt, error) {
429
	_, block := t.resolve(ctx)
430 431
	// Pending tx
	if block == nil {
432 433
		return nil, nil
	}
434
	receipts, err := block.resolveReceipts(ctx)
435 436 437 438 439 440
	if err != nil {
		return nil, err
	}
	return receipts[t.index], nil
}

441
func (t *Transaction) Status(ctx context.Context) (*hexutil.Uint64, error) {
442 443 444 445
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
446 447 448
	if len(receipt.PostState) != 0 {
		return nil, nil
	}
449
	ret := hexutil.Uint64(receipt.Status)
450 451 452
	return &ret, nil
}

453
func (t *Transaction) GasUsed(ctx context.Context) (*hexutil.Uint64, error) {
454 455 456 457
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
458
	ret := hexutil.Uint64(receipt.GasUsed)
459 460 461
	return &ret, nil
}

462
func (t *Transaction) CumulativeGasUsed(ctx context.Context) (*hexutil.Uint64, error) {
463 464 465 466
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
467
	ret := hexutil.Uint64(receipt.CumulativeGasUsed)
468 469 470 471 472 473 474 475 476
	return &ret, nil
}

func (t *Transaction) CreatedContract(ctx context.Context, args BlockNumberArgs) (*Account, error) {
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil || receipt.ContractAddress == (common.Address{}) {
		return nil, err
	}
	return &Account{
477
		r:             t.r,
478 479
		address:       receipt.ContractAddress,
		blockNrOrHash: args.NumberOrLatest(),
480 481 482 483
	}, nil
}

func (t *Transaction) Logs(ctx context.Context) (*[]*Log, error) {
484
	_, block := t.resolve(ctx)
485 486
	// Pending tx
	if block == nil {
487 488
		return nil, nil
	}
489 490 491
	h, err := block.Hash(ctx)
	if err != nil {
		return nil, err
492
	}
493
	return t.getLogs(ctx, h)
494 495 496 497
}

// getLogs returns log objects for the given tx.
// Assumes block hash is resolved.
498
func (t *Transaction) getLogs(ctx context.Context, hash common.Hash) (*[]*Log, error) {
499 500 501 502 503 504 505
	var (
		filter    = t.r.filterSystem.NewBlockFilter(hash, nil, nil)
		logs, err = filter.Logs(ctx)
	)
	if err != nil {
		return nil, err
	}
506 507
	var ret []*Log
	// Select tx logs from all block logs
508
	ix := sort.Search(len(logs), func(i int) bool { return uint64(logs[i].TxIndex) >= t.index })
509
	for ix < len(logs) && uint64(logs[ix].TxIndex) == t.index {
510
		ret = append(ret, &Log{
511
			r:           t.r,
512
			transaction: t,
513
			log:         logs[ix],
514
		})
515
		ix++
516 517 518 519
	}
	return &ret, nil
}

520 521
func (t *Transaction) Type(ctx context.Context) *hexutil.Uint64 {
	tx, _ := t.resolve(ctx)
522
	txType := hexutil.Uint64(tx.Type())
523
	return &txType
524 525
}

526 527 528 529
func (t *Transaction) AccessList(ctx context.Context) *[]*AccessTuple {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return nil
530 531 532 533 534 535
	}
	accessList := tx.AccessList()
	ret := make([]*AccessTuple, 0, len(accessList))
	for _, al := range accessList {
		ret = append(ret, &AccessTuple{
			address:     al.Address,
536
			storageKeys: al.StorageKeys,
537 538
		})
	}
539
	return &ret
540 541
}

542 543 544 545
func (t *Transaction) R(ctx context.Context) hexutil.Big {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return hexutil.Big{}
546 547
	}
	_, r, _ := tx.RawSignatureValues()
548
	return hexutil.Big(*r)
549 550
}

551 552 553 554
func (t *Transaction) S(ctx context.Context) hexutil.Big {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return hexutil.Big{}
555 556
	}
	_, _, s := tx.RawSignatureValues()
557
	return hexutil.Big(*s)
558 559
}

560 561 562 563
func (t *Transaction) V(ctx context.Context) hexutil.Big {
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return hexutil.Big{}
564 565
	}
	v, _, _ := tx.RawSignatureValues()
566
	return hexutil.Big(*v)
567 568
}

569
func (t *Transaction) Raw(ctx context.Context) (hexutil.Bytes, error) {
570 571 572
	tx, _ := t.resolve(ctx)
	if tx == nil {
		return hexutil.Bytes{}, nil
573 574 575 576
	}
	return tx.MarshalBinary()
}

577 578 579
func (t *Transaction) RawReceipt(ctx context.Context) (hexutil.Bytes, error) {
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
580
		return hexutil.Bytes{}, err
581 582 583 584
	}
	return receipt.MarshalBinary()
}

585 586 587
type BlockType int

// Block represents an Ethereum block.
588
// backend, and numberOrHash are mandatory. All other fields are lazily fetched
589 590
// when required.
type Block struct {
591
	r            *Resolver
592 593 594 595 596 597 598
	numberOrHash *rpc.BlockNumberOrHash // Field resolvers assume numberOrHash is always present
	mu           sync.Mutex
	// mu protects following resources
	hash     common.Hash // Must be resolved during initialization
	header   *types.Header
	block    *types.Block
	receipts []*types.Receipt
599 600 601 602 603
}

// resolve returns the internal Block object representing this block, fetching
// it if necessary.
func (b *Block) resolve(ctx context.Context) (*types.Block, error) {
604 605
	b.mu.Lock()
	defer b.mu.Unlock()
606 607 608
	if b.block != nil {
		return b.block, nil
	}
609 610 611
	if b.numberOrHash == nil {
		latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
		b.numberOrHash = &latest
612
	}
613
	var err error
614
	b.block, err = b.r.backend.BlockByNumberOrHash(ctx, *b.numberOrHash)
615 616 617 618
	if b.block != nil {
		b.hash = b.block.Hash()
		if b.header == nil {
			b.header = b.block.Header()
619
		}
620 621 622 623 624 625 626 627
	}
	return b.block, err
}

// resolveHeader returns the internal Header object for this block, fetching it
// if necessary. Call this function instead of `resolve` unless you need the
// additional data (transactions and uncles).
func (b *Block) resolveHeader(ctx context.Context) (*types.Header, error) {
628 629 630 631 632
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.header != nil {
		return b.header, nil
	}
633
	if b.numberOrHash == nil && b.hash == (common.Hash{}) {
634
		return nil, errBlockInvariant
635
	}
636
	var err error
637 638 639 640 641 642
	b.header, err = b.r.backend.HeaderByNumberOrHash(ctx, *b.numberOrHash)
	if err != nil {
		return nil, err
	}
	if b.hash == (common.Hash{}) {
		b.hash = b.header.Hash()
643
	}
644
	return b.header, nil
645 646 647 648 649
}

// resolveReceipts returns the list of receipts for this block, fetching them
// if necessary.
func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) {
650 651 652 653
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.receipts != nil {
		return b.receipts, nil
654
	}
655 656 657 658 659 660
	receipts, err := b.r.backend.GetReceipts(ctx, b.hash)
	if err != nil {
		return nil, err
	}
	b.receipts = receipts
	return receipts, nil
661 662
}

663
func (b *Block) Number(ctx context.Context) (hexutil.Uint64, error) {
664 665 666
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
667
	}
668

669
	return hexutil.Uint64(header.Number.Uint64()), nil
670 671 672
}

func (b *Block) Hash(ctx context.Context) (common.Hash, error) {
673 674
	b.mu.Lock()
	defer b.mu.Unlock()
675 676 677
	return b.hash, nil
}

678
func (b *Block) GasLimit(ctx context.Context) (hexutil.Uint64, error) {
679 680 681 682
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
	}
683
	return hexutil.Uint64(header.GasLimit), nil
684 685
}

686
func (b *Block) GasUsed(ctx context.Context) (hexutil.Uint64, error) {
687 688 689 690
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
	}
691
	return hexutil.Uint64(header.GasUsed), nil
692 693
}

694 695 696 697 698 699 700 701 702 703 704
func (b *Block) BaseFeePerGas(ctx context.Context) (*hexutil.Big, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return nil, err
	}
	if header.BaseFee == nil {
		return nil, nil
	}
	return (*hexutil.Big)(header.BaseFee), nil
}

705 706 707 708 709
func (b *Block) NextBaseFeePerGas(ctx context.Context) (*hexutil.Big, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return nil, err
	}
710
	chaincfg := b.r.backend.ChainConfig()
711 712 713 714 715 716 717 718 719 720
	if header.BaseFee == nil {
		// Make sure next block doesn't enable EIP-1559
		if !chaincfg.IsLondon(new(big.Int).Add(header.Number, common.Big1)) {
			return nil, nil
		}
	}
	nextBaseFee := misc.CalcBaseFee(chaincfg, header)
	return (*hexutil.Big)(nextBaseFee), nil
}

721
func (b *Block) Parent(ctx context.Context) (*Block, error) {
722 723
	if _, err := b.resolveHeader(ctx); err != nil {
		return nil, err
724
	}
725 726
	if b.header == nil || b.header.Number.Uint64() < 1 {
		return nil, nil
727
	}
728 729 730 731 732 733 734 735
	var (
		num       = rpc.BlockNumber(b.header.Number.Uint64() - 1)
		hash      = b.header.ParentHash
		numOrHash = rpc.BlockNumberOrHash{
			BlockNumber: &num,
			BlockHash:   &hash,
		}
	)
736
	return &Block{
737
		r:            b.r,
738 739
		numberOrHash: &numOrHash,
		hash:         hash,
740
	}, nil
741 742 743 744 745 746 747 748 749 750
}

func (b *Block) Difficulty(ctx context.Context) (hexutil.Big, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Big{}, err
	}
	return hexutil.Big(*header.Difficulty), nil
}

751
func (b *Block) Timestamp(ctx context.Context) (hexutil.Uint64, error) {
752 753
	header, err := b.resolveHeader(ctx)
	if err != nil {
754
		return 0, err
755
	}
756
	return hexutil.Uint64(header.Time), nil
757 758 759 760 761 762 763
}

func (b *Block) Nonce(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
764
	return header.Nonce[:], nil
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
}

func (b *Block) MixHash(ctx context.Context) (common.Hash, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return common.Hash{}, err
	}
	return header.MixDigest, nil
}

func (b *Block) TransactionsRoot(ctx context.Context) (common.Hash, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return common.Hash{}, err
	}
	return header.TxHash, nil
}

func (b *Block) StateRoot(ctx context.Context) (common.Hash, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return common.Hash{}, err
	}
	return header.Root, nil
}

func (b *Block) ReceiptsRoot(ctx context.Context) (common.Hash, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return common.Hash{}, err
	}
	return header.ReceiptHash, nil
}

func (b *Block) OmmerHash(ctx context.Context) (common.Hash, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return common.Hash{}, err
	}
	return header.UncleHash, nil
}

807
func (b *Block) OmmerCount(ctx context.Context) (*hexutil.Uint64, error) {
808 809 810 811
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
812
	count := hexutil.Uint64(len(block.Uncles()))
813 814 815 816 817 818 819 820 821 822
	return &count, err
}

func (b *Block) Ommers(ctx context.Context) (*[]*Block, error) {
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
	ret := make([]*Block, 0, len(block.Uncles()))
	for _, uncle := range block.Uncles() {
823
		blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
824
		ret = append(ret, &Block{
825
			r:            b.r,
826 827
			numberOrHash: &blockNumberOrHash,
			header:       uncle,
828
			hash:         uncle.Hash(),
829 830 831 832 833 834 835 836 837 838
		})
	}
	return &ret, nil
}

func (b *Block) ExtraData(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
839
	return header.Extra, nil
840 841 842 843 844 845 846
}

func (b *Block) LogsBloom(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
847
	return header.Bloom.Bytes(), nil
848 849 850
}

func (b *Block) TotalDifficulty(ctx context.Context) (hexutil.Big, error) {
851 852 853
	hash, err := b.Hash(ctx)
	if err != nil {
		return hexutil.Big{}, err
854
	}
855
	td := b.r.backend.GetTd(ctx, hash)
856
	if td == nil {
857
		return hexutil.Big{}, fmt.Errorf("total difficulty not found %x", hash)
858 859
	}
	return hexutil.Big(*td), nil
860 861
}

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
func (b *Block) RawHeader(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
	return rlp.EncodeToBytes(header)
}

func (b *Block) Raw(ctx context.Context) (hexutil.Bytes, error) {
	block, err := b.resolve(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
	return rlp.EncodeToBytes(block)
}

878 879
// BlockNumberArgs encapsulates arguments to accessors that specify a block number.
type BlockNumberArgs struct {
880 881 882
	// TODO: Ideally we could use input unions to allow the query to specify the
	// block parameter by hash, block number, or tag but input unions aren't part of the
	// standard GraphQL schema SDL yet, see: https://github.com/graphql/graphql-spec/issues/488
883
	Block *Long
884 885
}

886
// NumberOr returns the provided block number argument, or the "current" block number or hash if none
887
// was provided.
888
func (a BlockNumberArgs) NumberOr(current rpc.BlockNumberOrHash) rpc.BlockNumberOrHash {
889
	if a.Block != nil {
890 891
		blockNr := rpc.BlockNumber(*a.Block)
		return rpc.BlockNumberOrHashWithNumber(blockNr)
892
	}
893 894 895 896 897 898 899
	return current
}

// NumberOrLatest returns the provided block number argument, or the "latest" block number if none
// was provided.
func (a BlockNumberArgs) NumberOrLatest() rpc.BlockNumberOrHash {
	return a.NumberOr(rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber))
900 901 902
}

func (b *Block) Miner(ctx context.Context, args BlockNumberArgs) (*Account, error) {
903
	header, err := b.resolveHeader(ctx)
904 905 906 907
	if err != nil {
		return nil, err
	}
	return &Account{
908
		r:             b.r,
909 910
		address:       header.Coinbase,
		blockNrOrHash: args.NumberOrLatest(),
911 912 913
	}, nil
}

914
func (b *Block) TransactionCount(ctx context.Context) (*hexutil.Uint64, error) {
915 916 917 918
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
919
	count := hexutil.Uint64(len(block.Transactions()))
920 921 922 923 924 925 926 927 928 929 930
	return &count, err
}

func (b *Block) Transactions(ctx context.Context) (*[]*Transaction, error) {
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
	ret := make([]*Transaction, 0, len(block.Transactions()))
	for i, tx := range block.Transactions() {
		ret = append(ret, &Transaction{
931 932 933 934 935
			r:     b.r,
			hash:  tx.Hash(),
			tx:    tx,
			block: b,
			index: uint64(i),
936 937 938 939 940
		})
	}
	return &ret, nil
}

941
func (b *Block) TransactionAt(ctx context.Context, args struct{ Index Long }) (*Transaction, error) {
942 943 944 945
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
946 947
	txs := block.Transactions()
	if args.Index < 0 || int(args.Index) >= len(txs) {
948 949
		return nil, nil
	}
950
	tx := txs[args.Index]
951
	return &Transaction{
952 953 954 955 956
		r:     b.r,
		hash:  tx.Hash(),
		tx:    tx,
		block: b,
		index: uint64(args.Index),
957 958 959
	}, nil
}

960
func (b *Block) OmmerAt(ctx context.Context, args struct{ Index Long }) (*Block, error) {
961 962 963 964 965 966 967 968 969
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
	uncles := block.Uncles()
	if args.Index < 0 || int(args.Index) >= len(uncles) {
		return nil, nil
	}
	uncle := uncles[args.Index]
970
	blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
971
	return &Block{
972
		r:            b.r,
973 974
		numberOrHash: &blockNumberOrHash,
		header:       uncle,
975
		hash:         uncle.Hash(),
976 977 978
	}, nil
}

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
func (b *Block) WithdrawalsRoot(ctx context.Context) (*common.Hash, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return nil, err
	}
	// Pre-shanghai blocks
	if header.WithdrawalsHash == nil {
		return nil, nil
	}
	return header.WithdrawalsHash, nil
}

func (b *Block) Withdrawals(ctx context.Context) (*[]*Withdrawal, error) {
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
	// Pre-shanghai blocks
	if block.Header().WithdrawalsHash == nil {
		return nil, nil
	}
	ret := make([]*Withdrawal, 0, len(block.Withdrawals()))
	for _, w := range block.Withdrawals() {
		ret = append(ret, &Withdrawal{
			index:     w.Index,
			validator: w.Validator,
			address:   w.Address,
			amount:    w.Amount,
		})
	}
	return &ret, nil
}

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
// BlockFilterCriteria encapsulates criteria passed to a `logs` accessor inside
// a block.
type BlockFilterCriteria struct {
	Addresses *[]common.Address // restricts matches to events created by specific contracts

	// The Topic list restricts matches to particular event topics. Each event has a list
	// of topics. Topics matches a prefix of that list. An empty element slice matches any
	// topic. Non-empty elements represent an alternative that matches any of the
	// contained topics.
	//
	// Examples:
	// {} or nil          matches any topic list
	// {{A}}              matches topic A in first position
	// {{}, {B}}          matches any topic in first position, B in second position
	// {{A}, {B}}         matches topic A in first position, B in second position
	// {{A, B}}, {C, D}}  matches topic (A OR B) in first position, (C OR D) in second position
	Topics *[][]common.Hash
}

// runFilter accepts a filter and executes it, returning all its results as
// `Log` objects.
1033
func runFilter(ctx context.Context, r *Resolver, filter *filters.Filter) ([]*Log, error) {
1034 1035 1036 1037 1038 1039 1040
	logs, err := filter.Logs(ctx)
	if err != nil || logs == nil {
		return nil, err
	}
	ret := make([]*Log, 0, len(logs))
	for _, log := range logs {
		ret = append(ret, &Log{
1041 1042
			r:           r,
			transaction: &Transaction{r: r, hash: log.TxHash},
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
			log:         log,
		})
	}
	return ret, nil
}

func (b *Block) Logs(ctx context.Context, args struct{ Filter BlockFilterCriteria }) ([]*Log, error) {
	var addresses []common.Address
	if args.Filter.Addresses != nil {
		addresses = *args.Filter.Addresses
	}
	var topics [][]common.Hash
	if args.Filter.Topics != nil {
		topics = *args.Filter.Topics
	}
	// Construct the range filter
1059 1060 1061 1062
	hash, err := b.Hash(ctx)
	if err != nil {
		return nil, err
	}
1063
	filter := b.r.filterSystem.NewBlockFilter(hash, addresses, topics)
1064 1065

	// Run the filter and return all the logs
1066
	return runFilter(ctx, b.r, filter)
1067 1068
}

1069 1070 1071 1072
func (b *Block) Account(ctx context.Context, args struct {
	Address common.Address
}) (*Account, error) {
	return &Account{
1073
		r:             b.r,
1074 1075
		address:       args.Address,
		blockNrOrHash: *b.numberOrHash,
1076 1077 1078 1079 1080 1081
	}, nil
}

// CallData encapsulates arguments to `call` or `estimateGas`.
// All arguments are optional.
type CallData struct {
1082 1083
	From                 *common.Address // The Ethereum address the call is from.
	To                   *common.Address // The Ethereum address the call is to.
1084
	Gas                  *Long           // The amount of gas provided for the call.
1085 1086 1087 1088 1089
	GasPrice             *hexutil.Big    // The price of each unit of gas, in wei.
	MaxFeePerGas         *hexutil.Big    // The max price of each unit of gas, in wei (1559).
	MaxPriorityFeePerGas *hexutil.Big    // The max tip of each unit of gas, in wei (1559).
	Value                *hexutil.Big    // The value sent along with the call.
	Data                 *hexutil.Bytes  // Any data sent with the call.
1090 1091 1092 1093
}

// CallResult encapsulates the result of an invocation of the `call` accessor.
type CallResult struct {
1094 1095 1096
	data    hexutil.Bytes  // The return data from the call
	gasUsed hexutil.Uint64 // The amount of gas used
	status  hexutil.Uint64 // The return status of the call - 0 for failure or 1 for success.
1097 1098 1099 1100 1101 1102
}

func (c *CallResult) Data() hexutil.Bytes {
	return c.data
}

1103
func (c *CallResult) GasUsed() hexutil.Uint64 {
1104 1105 1106
	return c.gasUsed
}

1107
func (c *CallResult) Status() hexutil.Uint64 {
1108 1109 1110 1111
	return c.status
}

func (b *Block) Call(ctx context.Context, args struct {
1112
	Data ethapi.TransactionArgs
1113
}) (*CallResult, error) {
1114
	result, err := ethapi.DoCall(ctx, b.r.backend, args.Data, *b.numberOrHash, nil, nil, b.r.backend.RPCEVMTimeout(), b.r.backend.RPCGasCap())
1115 1116 1117
	if err != nil {
		return nil, err
	}
1118
	status := hexutil.Uint64(1)
1119
	if result.Failed() {
1120 1121
		status = 0
	}
1122

1123
	return &CallResult{
1124
		data:    result.ReturnData,
1125
		gasUsed: hexutil.Uint64(result.UsedGas),
1126
		status:  status,
1127
	}, nil
1128 1129 1130
}

func (b *Block) EstimateGas(ctx context.Context, args struct {
1131
	Data ethapi.TransactionArgs
1132 1133
}) (hexutil.Uint64, error) {
	return ethapi.DoEstimateGas(ctx, b.r.backend, args.Data, *b.numberOrHash, b.r.backend.RPCGasCap())
1134 1135 1136
}

type Pending struct {
1137
	r *Resolver
1138 1139
}

1140
func (p *Pending) TransactionCount(ctx context.Context) (hexutil.Uint64, error) {
1141
	txs, err := p.r.backend.GetPoolTransactions()
1142
	return hexutil.Uint64(len(txs)), err
1143 1144 1145
}

func (p *Pending) Transactions(ctx context.Context) (*[]*Transaction, error) {
1146
	txs, err := p.r.backend.GetPoolTransactions()
1147 1148 1149 1150 1151 1152
	if err != nil {
		return nil, err
	}
	ret := make([]*Transaction, 0, len(txs))
	for i, tx := range txs {
		ret = append(ret, &Transaction{
1153 1154 1155 1156
			r:     p.r,
			hash:  tx.Hash(),
			tx:    tx,
			index: uint64(i),
1157 1158 1159 1160 1161 1162 1163 1164
		})
	}
	return &ret, nil
}

func (p *Pending) Account(ctx context.Context, args struct {
	Address common.Address
}) *Account {
1165
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1166
	return &Account{
1167
		r:             p.r,
1168 1169
		address:       args.Address,
		blockNrOrHash: pendingBlockNr,
1170 1171 1172 1173
	}
}

func (p *Pending) Call(ctx context.Context, args struct {
1174
	Data ethapi.TransactionArgs
1175
}) (*CallResult, error) {
1176
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1177
	result, err := ethapi.DoCall(ctx, p.r.backend, args.Data, pendingBlockNr, nil, nil, p.r.backend.RPCEVMTimeout(), p.r.backend.RPCGasCap())
1178 1179 1180
	if err != nil {
		return nil, err
	}
1181
	status := hexutil.Uint64(1)
1182
	if result.Failed() {
1183 1184
		status = 0
	}
1185

1186
	return &CallResult{
1187
		data:    result.ReturnData,
1188
		gasUsed: hexutil.Uint64(result.UsedGas),
1189
		status:  status,
1190
	}, nil
1191 1192 1193
}

func (p *Pending) EstimateGas(ctx context.Context, args struct {
1194
	Data ethapi.TransactionArgs
1195
}) (hexutil.Uint64, error) {
1196 1197
	latestBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
	return ethapi.DoEstimateGas(ctx, p.r.backend, args.Data, latestBlockNr, p.r.backend.RPCGasCap())
1198 1199
}

1200 1201
// Resolver is the top-level object in the GraphQL hierarchy.
type Resolver struct {
1202 1203
	backend      ethapi.Backend
	filterSystem *filters.FilterSystem
1204 1205 1206
}

func (r *Resolver) Block(ctx context.Context, args struct {
1207
	Number *Long
1208 1209
	Hash   *common.Hash
}) (*Block, error) {
1210
	var numberOrHash rpc.BlockNumberOrHash
1211
	if args.Number != nil {
1212 1213 1214
		if *args.Number < 0 {
			return nil, nil
		}
1215
		number := rpc.BlockNumber(*args.Number)
1216
		numberOrHash = rpc.BlockNumberOrHashWithNumber(number)
1217
	} else if args.Hash != nil {
1218
		numberOrHash = rpc.BlockNumberOrHashWithHash(*args.Hash, false)
1219
	} else {
1220 1221 1222 1223 1224
		numberOrHash = rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
	}
	block := &Block{
		r:            r,
		numberOrHash: &numberOrHash,
1225
	}
1226 1227 1228 1229
	// Resolve the header, return nil if it doesn't exist.
	// Note we don't resolve block directly here since it will require an
	// additional network request for light client.
	h, err := block.resolveHeader(ctx)
1230 1231
	if err != nil {
		return nil, err
1232
	} else if h == nil {
1233 1234 1235 1236 1237 1238
		return nil, nil
	}
	return block, nil
}

func (r *Resolver) Blocks(ctx context.Context, args struct {
1239 1240
	From *Long
	To   *Long
1241
}) ([]*Block, error) {
1242
	from := rpc.BlockNumber(*args.From)
1243 1244 1245 1246 1247

	var to rpc.BlockNumber
	if args.To != nil {
		to = rpc.BlockNumber(*args.To)
	} else {
1248
		to = rpc.BlockNumber(r.backend.CurrentBlock().Number.Int64())
1249 1250 1251 1252 1253 1254
	}
	if to < from {
		return []*Block{}, nil
	}
	ret := make([]*Block, 0, to-from+1)
	for i := from; i <= to; i++ {
1255
		numberOrHash := rpc.BlockNumberOrHashWithNumber(i)
1256
		block := &Block{
1257
			r:            r,
1258
			numberOrHash: &numberOrHash,
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
		}
		// Resolve the header to check for existence.
		// Note we don't resolve block directly here since it will require an
		// additional network request for light client.
		h, err := block.resolveHeader(ctx)
		if err != nil {
			return nil, err
		} else if h == nil {
			// Blocks after must be non-existent too, break.
			break
		}
		ret = append(ret, block)
1271 1272 1273 1274
	}
	return ret, nil
}

1275
func (r *Resolver) Pending(ctx context.Context) *Pending {
1276
	return &Pending{r}
1277 1278
}

1279
func (r *Resolver) Transaction(ctx context.Context, args struct{ Hash common.Hash }) *Transaction {
1280
	tx := &Transaction{
1281 1282
		r:    r,
		hash: args.Hash,
1283 1284
	}
	// Resolve the transaction; if it doesn't exist, return nil.
1285 1286 1287
	t, _ := tx.resolve(ctx)
	if t == nil {
		return nil
1288
	}
1289
	return tx
1290 1291 1292 1293
}

func (r *Resolver) SendRawTransaction(ctx context.Context, args struct{ Data hexutil.Bytes }) (common.Hash, error) {
	tx := new(types.Transaction)
1294
	if err := tx.UnmarshalBinary(args.Data); err != nil {
1295 1296 1297 1298 1299 1300
		return common.Hash{}, err
	}
	hash, err := ethapi.SubmitTransaction(ctx, r.backend, tx)
	return hash, err
}

1301
// FilterCriteria encapsulates the arguments to `logs` on the root resolver object.
1302
type FilterCriteria struct {
1303 1304
	FromBlock *Long             // beginning of the queried range, nil means genesis block
	ToBlock   *Long             // end of the range, nil means latest block
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	Addresses *[]common.Address // restricts matches to events created by specific contracts

	// The Topic list restricts matches to particular event topics. Each event has a list
	// of topics. Topics matches a prefix of that list. An empty element slice matches any
	// topic. Non-empty elements represent an alternative that matches any of the
	// contained topics.
	//
	// Examples:
	// {} or nil          matches any topic list
	// {{A}}              matches topic A in first position
	// {{}, {B}}          matches any topic in first position, B in second position
	// {{A}, {B}}         matches topic A in first position, B in second position
	// {{A, B}}, {C, D}}  matches topic (A OR B) in first position, (C OR D) in second position
	Topics *[][]common.Hash
}

func (r *Resolver) Logs(ctx context.Context, args struct{ Filter FilterCriteria }) ([]*Log, error) {
	// Convert the RPC block numbers into internal representations
	begin := rpc.LatestBlockNumber.Int64()
	if args.Filter.FromBlock != nil {
		begin = int64(*args.Filter.FromBlock)
	}
	end := rpc.LatestBlockNumber.Int64()
	if args.Filter.ToBlock != nil {
		end = int64(*args.Filter.ToBlock)
	}
	var addresses []common.Address
	if args.Filter.Addresses != nil {
		addresses = *args.Filter.Addresses
	}
	var topics [][]common.Hash
	if args.Filter.Topics != nil {
		topics = *args.Filter.Topics
	}
	// Construct the range filter
1340
	filter := r.filterSystem.NewRangeFilter(begin, end, addresses, topics)
1341
	return runFilter(ctx, r, filter)
1342 1343 1344
}

func (r *Resolver) GasPrice(ctx context.Context) (hexutil.Big, error) {
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
	tipcap, err := r.backend.SuggestGasTipCap(ctx)
	if err != nil {
		return hexutil.Big{}, err
	}
	if head := r.backend.CurrentHeader(); head.BaseFee != nil {
		tipcap.Add(tipcap, head.BaseFee)
	}
	return (hexutil.Big)(*tipcap), nil
}

func (r *Resolver) MaxPriorityFeePerGas(ctx context.Context) (hexutil.Big, error) {
	tipcap, err := r.backend.SuggestGasTipCap(ctx)
	if err != nil {
		return hexutil.Big{}, err
	}
	return (hexutil.Big)(*tipcap), nil
1361 1362
}

1363 1364 1365 1366
func (r *Resolver) ChainID(ctx context.Context) (hexutil.Big, error) {
	return hexutil.Big(*r.backend.ChainConfig().ChainID), nil
}

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
// SyncState represents the synchronisation status returned from the `syncing` accessor.
type SyncState struct {
	progress ethereum.SyncProgress
}

func (s *SyncState) StartingBlock() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.StartingBlock)
}
func (s *SyncState) CurrentBlock() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.CurrentBlock)
}
func (s *SyncState) HighestBlock() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HighestBlock)
}
1381 1382
func (s *SyncState) SyncedAccounts() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedAccounts)
1383
}
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
func (s *SyncState) SyncedAccountBytes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedAccountBytes)
}
func (s *SyncState) SyncedBytecodes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedBytecodes)
}
func (s *SyncState) SyncedBytecodeBytes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedBytecodeBytes)
}
func (s *SyncState) SyncedStorage() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedStorage)
}
func (s *SyncState) SyncedStorageBytes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedStorageBytes)
}
func (s *SyncState) HealedTrienodes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HealedTrienodes)
}
func (s *SyncState) HealedTrienodeBytes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HealedTrienodeBytes)
}
func (s *SyncState) HealedBytecodes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HealedBytecodes)
}
func (s *SyncState) HealedBytecodeBytes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HealedBytecodeBytes)
}
func (s *SyncState) HealingTrienodes() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HealingTrienodes)
}
func (s *SyncState) HealingBytecode() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.HealingBytecode)
1416 1417
}

1418
// Syncing returns false in case the node is currently not syncing with the network. It can be up-to-date or has not
1419
// yet received the latest block headers from its pears. In case it is synchronizing:
1420
// - startingBlock:       block number this node started to synchronize from
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
// - currentBlock:        block number this node is currently importing
// - highestBlock:        block number of the highest block header this node has received from peers
// - syncedAccounts:      number of accounts downloaded
// - syncedAccountBytes:  number of account trie bytes persisted to disk
// - syncedBytecodes:     number of bytecodes downloaded
// - syncedBytecodeBytes: number of bytecode bytes downloaded
// - syncedStorage:       number of storage slots downloaded
// - syncedStorageBytes:  number of storage trie bytes persisted to disk
// - healedTrienodes:     number of state trie nodes downloaded
// - healedTrienodeBytes: number of state trie bytes persisted to disk
// - healedBytecodes:     number of bytecodes downloaded
// - healedBytecodeBytes: number of bytecodes persisted to disk
// - healingTrienodes:    number of state trie nodes pending
// - healingBytecode:     number of bytecodes pending
1435
func (r *Resolver) Syncing() (*SyncState, error) {
1436
	progress := r.backend.SyncProgress()
1437 1438 1439 1440 1441 1442 1443 1444

	// Return not syncing if the synchronisation already completed
	if progress.CurrentBlock >= progress.HighestBlock {
		return nil, nil
	}
	// Otherwise gather the block sync stats
	return &SyncState{progress}, nil
}