graphql.go 38.6 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
// Transaction represents an Ethereum transaction.
187 188
// backend and hash are mandatory; all others will be fetched when required.
type Transaction struct {
189 190 191 192
	r    *Resolver
	hash common.Hash // Must be present after initialization
	mu   sync.Mutex
	// mu protects following resources
193 194 195
	tx    *types.Transaction
	block *Block
	index uint64
196 197 198
}

// resolve returns the internal transaction object, fetching it if needed.
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
// It also returns the block the tx blongs to, unless it is a pending tx.
func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, *Block, error) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.tx != nil {
		return t.tx, t.block, nil
	}
	// 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,
215
		}
216 217
		t.index = index
		return t.tx, t.block, nil
218
	}
219 220 221
	// No finalized transaction, try to retrieve it from the pool
	t.tx = t.r.backend.GetPoolTransaction(t.hash)
	return t.tx, nil, nil
222 223
}

224 225
func (t *Transaction) Hash(ctx context.Context) common.Hash {
	return t.hash
226 227 228
}

func (t *Transaction) InputData(ctx context.Context) (hexutil.Bytes, error) {
229
	tx, _, err := t.resolve(ctx)
230 231 232
	if err != nil || tx == nil {
		return hexutil.Bytes{}, err
	}
233
	return tx.Data(), nil
234 235 236
}

func (t *Transaction) Gas(ctx context.Context) (hexutil.Uint64, error) {
237
	tx, _, err := t.resolve(ctx)
238 239 240 241 242 243 244
	if err != nil || tx == nil {
		return 0, err
	}
	return hexutil.Uint64(tx.Gas()), nil
}

func (t *Transaction) GasPrice(ctx context.Context) (hexutil.Big, error) {
245
	tx, block, err := t.resolve(ctx)
246 247 248
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
249 250 251 252
	switch tx.Type() {
	case types.AccessListTxType:
		return hexutil.Big(*tx.GasPrice()), nil
	case types.DynamicFeeTxType:
253 254
		if block != nil {
			if baseFee, _ := block.BaseFeePerGas(ctx); baseFee != nil {
255 256 257 258 259 260 261 262 263 264
				// price = min(tip, gasFeeCap - baseFee) + baseFee
				return (hexutil.Big)(*math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee.ToInt()), tx.GasFeeCap())), nil
			}
		}
		return hexutil.Big(*tx.GasPrice()), nil
	default:
		return hexutil.Big(*tx.GasPrice()), nil
	}
}

265
func (t *Transaction) EffectiveGasPrice(ctx context.Context) (*hexutil.Big, error) {
266
	tx, block, err := t.resolve(ctx)
267 268 269
	if err != nil || tx == nil {
		return nil, err
	}
270
	// Pending tx
271
	if block == nil {
272 273
		return nil, nil
	}
274
	header, err := block.resolveHeader(ctx)
275 276 277 278 279 280 281 282 283
	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
}

284
func (t *Transaction) MaxFeePerGas(ctx context.Context) (*hexutil.Big, error) {
285
	tx, _, err := t.resolve(ctx)
286 287 288 289 290 291 292 293 294 295 296 297 298 299
	if err != nil || tx == nil {
		return nil, err
	}
	switch tx.Type() {
	case types.AccessListTxType:
		return nil, nil
	case types.DynamicFeeTxType:
		return (*hexutil.Big)(tx.GasFeeCap()), nil
	default:
		return nil, nil
	}
}

func (t *Transaction) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) {
300
	tx, _, err := t.resolve(ctx)
301 302 303 304 305 306 307 308 309 310 311
	if err != nil || tx == nil {
		return nil, err
	}
	switch tx.Type() {
	case types.AccessListTxType:
		return nil, nil
	case types.DynamicFeeTxType:
		return (*hexutil.Big)(tx.GasTipCap()), nil
	default:
		return nil, nil
	}
312 313
}

314
func (t *Transaction) EffectiveTip(ctx context.Context) (*hexutil.Big, error) {
315
	tx, block, err := t.resolve(ctx)
316 317 318 319
	if err != nil || tx == nil {
		return nil, err
	}
	// Pending tx
320
	if block == nil {
321 322
		return nil, nil
	}
323
	header, err := block.resolveHeader(ctx)
324 325 326 327 328 329 330 331 332 333 334 335 336 337
	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
}

338
func (t *Transaction) Value(ctx context.Context) (hexutil.Big, error) {
339
	tx, _, err := t.resolve(ctx)
340 341 342
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
343 344 345
	if tx.Value() == nil {
		return hexutil.Big{}, fmt.Errorf("invalid transaction value %x", t.hash)
	}
346 347 348 349
	return hexutil.Big(*tx.Value()), nil
}

func (t *Transaction) Nonce(ctx context.Context) (hexutil.Uint64, error) {
350
	tx, _, err := t.resolve(ctx)
351 352 353 354 355 356 357
	if err != nil || tx == nil {
		return 0, err
	}
	return hexutil.Uint64(tx.Nonce()), nil
}

func (t *Transaction) To(ctx context.Context, args BlockNumberArgs) (*Account, error) {
358
	tx, _, err := t.resolve(ctx)
359 360 361 362 363 364 365 366
	if err != nil || tx == nil {
		return nil, err
	}
	to := tx.To()
	if to == nil {
		return nil, nil
	}
	return &Account{
367
		r:             t.r,
368 369
		address:       *to,
		blockNrOrHash: args.NumberOrLatest(),
370 371 372 373
	}, nil
}

func (t *Transaction) From(ctx context.Context, args BlockNumberArgs) (*Account, error) {
374
	tx, _, err := t.resolve(ctx)
375 376 377
	if err != nil || tx == nil {
		return nil, err
	}
378
	signer := types.LatestSigner(t.r.backend.ChainConfig())
379 380
	from, _ := types.Sender(signer, tx)
	return &Account{
381
		r:             t.r,
382 383
		address:       from,
		blockNrOrHash: args.NumberOrLatest(),
384 385 386 387
	}, nil
}

func (t *Transaction) Block(ctx context.Context) (*Block, error) {
388 389
	_, block, err := t.resolve(ctx)
	if err != nil {
390 391
		return nil, err
	}
392
	return block, nil
393 394
}

395
func (t *Transaction) Index(ctx context.Context) (*hexutil.Uint64, error) {
396 397
	_, block, err := t.resolve(ctx)
	if err != nil {
398 399
		return nil, err
	}
400 401
	// Pending tx
	if block == nil {
402 403
		return nil, nil
	}
404
	index := hexutil.Uint64(t.index)
405 406 407 408 409
	return &index, nil
}

// getReceipt returns the receipt associated with this transaction, if any.
func (t *Transaction) getReceipt(ctx context.Context) (*types.Receipt, error) {
410 411
	_, block, err := t.resolve(ctx)
	if err != nil {
412 413
		return nil, err
	}
414 415
	// Pending tx
	if block == nil {
416 417
		return nil, nil
	}
418
	receipts, err := block.resolveReceipts(ctx)
419 420 421 422 423 424
	if err != nil {
		return nil, err
	}
	return receipts[t.index], nil
}

425
func (t *Transaction) Status(ctx context.Context) (*hexutil.Uint64, error) {
426 427 428 429
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
430 431 432
	if len(receipt.PostState) != 0 {
		return nil, nil
	}
433
	ret := hexutil.Uint64(receipt.Status)
434 435 436
	return &ret, nil
}

437
func (t *Transaction) GasUsed(ctx context.Context) (*hexutil.Uint64, error) {
438 439 440 441
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
442
	ret := hexutil.Uint64(receipt.GasUsed)
443 444 445
	return &ret, nil
}

446
func (t *Transaction) CumulativeGasUsed(ctx context.Context) (*hexutil.Uint64, error) {
447 448 449 450
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
451
	ret := hexutil.Uint64(receipt.CumulativeGasUsed)
452 453 454 455 456 457 458 459 460
	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{
461
		r:             t.r,
462 463
		address:       receipt.ContractAddress,
		blockNrOrHash: args.NumberOrLatest(),
464 465 466 467
	}, nil
}

func (t *Transaction) Logs(ctx context.Context) (*[]*Log, error) {
468 469
	_, block, err := t.resolve(ctx)
	if err != nil {
470 471
		return nil, err
	}
472 473
	// Pending tx
	if block == nil {
474 475
		return nil, nil
	}
476 477 478
	h, err := block.Hash(ctx)
	if err != nil {
		return nil, err
479
	}
480
	return t.getLogs(ctx, h)
481 482 483 484
}

// getLogs returns log objects for the given tx.
// Assumes block hash is resolved.
485
func (t *Transaction) getLogs(ctx context.Context, hash common.Hash) (*[]*Log, error) {
486 487 488 489 490 491 492
	var (
		filter    = t.r.filterSystem.NewBlockFilter(hash, nil, nil)
		logs, err = filter.Logs(ctx)
	)
	if err != nil {
		return nil, err
	}
493 494
	var ret []*Log
	// Select tx logs from all block logs
495
	ix := sort.Search(len(logs), func(i int) bool { return uint64(logs[i].TxIndex) >= t.index })
496
	for ix < len(logs) && uint64(logs[ix].TxIndex) == t.index {
497
		ret = append(ret, &Log{
498
			r:           t.r,
499
			transaction: t,
500
			log:         logs[ix],
501
		})
502
		ix++
503 504 505 506
	}
	return &ret, nil
}

507
func (t *Transaction) Type(ctx context.Context) (*hexutil.Uint64, error) {
508
	tx, _, err := t.resolve(ctx)
509 510 511
	if err != nil {
		return nil, err
	}
512
	txType := hexutil.Uint64(tx.Type())
513 514 515 516
	return &txType, nil
}

func (t *Transaction) AccessList(ctx context.Context) (*[]*AccessTuple, error) {
517
	tx, _, err := t.resolve(ctx)
518 519 520 521 522 523 524 525
	if err != nil || tx == nil {
		return nil, err
	}
	accessList := tx.AccessList()
	ret := make([]*AccessTuple, 0, len(accessList))
	for _, al := range accessList {
		ret = append(ret, &AccessTuple{
			address:     al.Address,
526
			storageKeys: al.StorageKeys,
527 528 529 530 531
		})
	}
	return &ret, nil
}

532
func (t *Transaction) R(ctx context.Context) (hexutil.Big, error) {
533
	tx, _, err := t.resolve(ctx)
534 535 536 537 538 539 540 541
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
	_, r, _ := tx.RawSignatureValues()
	return hexutil.Big(*r), nil
}

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

func (t *Transaction) V(ctx context.Context) (hexutil.Big, error) {
551
	tx, _, err := t.resolve(ctx)
552 553 554 555 556 557 558
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
	v, _, _ := tx.RawSignatureValues()
	return hexutil.Big(*v), nil
}

559
func (t *Transaction) Raw(ctx context.Context) (hexutil.Bytes, error) {
560
	tx, _, err := t.resolve(ctx)
561 562 563 564 565 566
	if err != nil || tx == nil {
		return hexutil.Bytes{}, err
	}
	return tx.MarshalBinary()
}

567 568 569
func (t *Transaction) RawReceipt(ctx context.Context) (hexutil.Bytes, error) {
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
570
		return hexutil.Bytes{}, err
571 572 573 574
	}
	return receipt.MarshalBinary()
}

575 576 577
type BlockType int

// Block represents an Ethereum block.
578
// backend, and numberOrHash are mandatory. All other fields are lazily fetched
579 580
// when required.
type Block struct {
581
	r            *Resolver
582 583 584 585 586 587 588
	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
589 590 591 592 593
}

// resolve returns the internal Block object representing this block, fetching
// it if necessary.
func (b *Block) resolve(ctx context.Context) (*types.Block, error) {
594 595
	b.mu.Lock()
	defer b.mu.Unlock()
596 597 598
	if b.block != nil {
		return b.block, nil
	}
599 600 601
	if b.numberOrHash == nil {
		latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
		b.numberOrHash = &latest
602
	}
603
	var err error
604
	b.block, err = b.r.backend.BlockByNumberOrHash(ctx, *b.numberOrHash)
605 606 607 608
	if b.block != nil {
		b.hash = b.block.Hash()
		if b.header == nil {
			b.header = b.block.Header()
609
		}
610 611 612 613 614 615 616 617
	}
	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) {
618 619 620 621 622
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.header != nil {
		return b.header, nil
	}
623
	if b.numberOrHash == nil && b.hash == (common.Hash{}) {
624
		return nil, errBlockInvariant
625
	}
626
	var err error
627 628 629 630 631 632
	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()
633
	}
634
	return b.header, nil
635 636 637 638 639
}

// resolveReceipts returns the list of receipts for this block, fetching them
// if necessary.
func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) {
640 641 642 643
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.receipts != nil {
		return b.receipts, nil
644
	}
645 646 647 648 649 650
	receipts, err := b.r.backend.GetReceipts(ctx, b.hash)
	if err != nil {
		return nil, err
	}
	b.receipts = receipts
	return receipts, nil
651 652
}

653
func (b *Block) Number(ctx context.Context) (hexutil.Uint64, error) {
654 655 656
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
657
	}
658

659
	return hexutil.Uint64(header.Number.Uint64()), nil
660 661 662
}

func (b *Block) Hash(ctx context.Context) (common.Hash, error) {
663 664
	b.mu.Lock()
	defer b.mu.Unlock()
665 666 667
	return b.hash, nil
}

668
func (b *Block) GasLimit(ctx context.Context) (hexutil.Uint64, error) {
669 670 671 672
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
	}
673
	return hexutil.Uint64(header.GasLimit), nil
674 675
}

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

684 685 686 687 688 689 690 691 692 693 694
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
}

695 696 697 698 699
func (b *Block) NextBaseFeePerGas(ctx context.Context) (*hexutil.Big, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return nil, err
	}
700
	chaincfg := b.r.backend.ChainConfig()
701 702 703 704 705 706 707 708 709 710
	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
}

711
func (b *Block) Parent(ctx context.Context) (*Block, error) {
712 713
	if _, err := b.resolveHeader(ctx); err != nil {
		return nil, err
714
	}
715 716
	if b.header == nil || b.header.Number.Uint64() < 1 {
		return nil, nil
717
	}
718 719 720 721 722 723 724 725
	var (
		num       = rpc.BlockNumber(b.header.Number.Uint64() - 1)
		hash      = b.header.ParentHash
		numOrHash = rpc.BlockNumberOrHash{
			BlockNumber: &num,
			BlockHash:   &hash,
		}
	)
726
	return &Block{
727
		r:            b.r,
728 729
		numberOrHash: &numOrHash,
		hash:         hash,
730
	}, nil
731 732 733 734 735 736 737 738 739 740
}

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
}

741
func (b *Block) Timestamp(ctx context.Context) (hexutil.Uint64, error) {
742 743
	header, err := b.resolveHeader(ctx)
	if err != nil {
744
		return 0, err
745
	}
746
	return hexutil.Uint64(header.Time), nil
747 748 749 750 751 752 753
}

func (b *Block) Nonce(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
754
	return header.Nonce[:], nil
755 756 757 758 759 760 761 762 763 764 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
}

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
}

797
func (b *Block) OmmerCount(ctx context.Context) (*hexutil.Uint64, error) {
798 799 800 801
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
802
	count := hexutil.Uint64(len(block.Uncles()))
803 804 805 806 807 808 809 810 811 812
	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() {
813
		blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
814
		ret = append(ret, &Block{
815
			r:            b.r,
816 817
			numberOrHash: &blockNumberOrHash,
			header:       uncle,
818
			hash:         uncle.Hash(),
819 820 821 822 823 824 825 826 827 828
		})
	}
	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
	}
829
	return header.Extra, nil
830 831 832 833 834 835 836
}

func (b *Block) LogsBloom(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
837
	return header.Bloom.Bytes(), nil
838 839 840
}

func (b *Block) TotalDifficulty(ctx context.Context) (hexutil.Big, error) {
841 842 843
	hash, err := b.Hash(ctx)
	if err != nil {
		return hexutil.Big{}, err
844
	}
845
	td := b.r.backend.GetTd(ctx, hash)
846
	if td == nil {
847
		return hexutil.Big{}, fmt.Errorf("total difficulty not found %x", hash)
848 849
	}
	return hexutil.Big(*td), nil
850 851
}

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
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)
}

868 869
// BlockNumberArgs encapsulates arguments to accessors that specify a block number.
type BlockNumberArgs struct {
870 871 872
	// 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
873
	Block *Long
874 875
}

876
// NumberOr returns the provided block number argument, or the "current" block number or hash if none
877
// was provided.
878
func (a BlockNumberArgs) NumberOr(current rpc.BlockNumberOrHash) rpc.BlockNumberOrHash {
879
	if a.Block != nil {
880 881
		blockNr := rpc.BlockNumber(*a.Block)
		return rpc.BlockNumberOrHashWithNumber(blockNr)
882
	}
883 884 885 886 887 888 889
	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))
890 891 892
}

func (b *Block) Miner(ctx context.Context, args BlockNumberArgs) (*Account, error) {
893
	header, err := b.resolveHeader(ctx)
894 895 896 897
	if err != nil {
		return nil, err
	}
	return &Account{
898
		r:             b.r,
899 900
		address:       header.Coinbase,
		blockNrOrHash: args.NumberOrLatest(),
901 902 903
	}, nil
}

904
func (b *Block) TransactionCount(ctx context.Context) (*hexutil.Uint64, error) {
905 906 907 908
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
909
	count := hexutil.Uint64(len(block.Transactions()))
910 911 912 913 914 915 916 917 918 919 920
	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{
921 922 923 924 925
			r:     b.r,
			hash:  tx.Hash(),
			tx:    tx,
			block: b,
			index: uint64(i),
926 927 928 929 930
		})
	}
	return &ret, nil
}

931
func (b *Block) TransactionAt(ctx context.Context, args struct{ Index Long }) (*Transaction, error) {
932 933 934 935
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
936 937
	txs := block.Transactions()
	if args.Index < 0 || int(args.Index) >= len(txs) {
938 939
		return nil, nil
	}
940
	tx := txs[args.Index]
941
	return &Transaction{
942 943 944 945 946
		r:     b.r,
		hash:  tx.Hash(),
		tx:    tx,
		block: b,
		index: uint64(args.Index),
947 948 949
	}, nil
}

950
func (b *Block) OmmerAt(ctx context.Context, args struct{ Index Long }) (*Block, error) {
951 952 953 954 955 956 957 958 959
	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]
960
	blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
961
	return &Block{
962
		r:            b.r,
963 964
		numberOrHash: &blockNumberOrHash,
		header:       uncle,
965
		hash:         uncle.Hash(),
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
	}, nil
}

// 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.
990
func runFilter(ctx context.Context, r *Resolver, filter *filters.Filter) ([]*Log, error) {
991 992 993 994 995 996 997
	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{
998 999
			r:           r,
			transaction: &Transaction{r: r, hash: log.TxHash},
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
			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
1016 1017 1018 1019
	hash, err := b.Hash(ctx)
	if err != nil {
		return nil, err
	}
1020
	filter := b.r.filterSystem.NewBlockFilter(hash, addresses, topics)
1021 1022

	// Run the filter and return all the logs
1023
	return runFilter(ctx, b.r, filter)
1024 1025
}

1026 1027 1028 1029
func (b *Block) Account(ctx context.Context, args struct {
	Address common.Address
}) (*Account, error) {
	return &Account{
1030
		r:             b.r,
1031 1032
		address:       args.Address,
		blockNrOrHash: *b.numberOrHash,
1033 1034 1035 1036 1037 1038
	}, nil
}

// CallData encapsulates arguments to `call` or `estimateGas`.
// All arguments are optional.
type CallData struct {
1039 1040
	From                 *common.Address // The Ethereum address the call is from.
	To                   *common.Address // The Ethereum address the call is to.
1041
	Gas                  *Long           // The amount of gas provided for the call.
1042 1043 1044 1045 1046
	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.
1047 1048 1049 1050
}

// CallResult encapsulates the result of an invocation of the `call` accessor.
type CallResult struct {
1051 1052 1053
	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.
1054 1055 1056 1057 1058 1059
}

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

1060
func (c *CallResult) GasUsed() hexutil.Uint64 {
1061 1062 1063
	return c.gasUsed
}

1064
func (c *CallResult) Status() hexutil.Uint64 {
1065 1066 1067 1068
	return c.status
}

func (b *Block) Call(ctx context.Context, args struct {
1069
	Data ethapi.TransactionArgs
1070
}) (*CallResult, error) {
1071
	result, err := ethapi.DoCall(ctx, b.r.backend, args.Data, *b.numberOrHash, nil, b.r.backend.RPCEVMTimeout(), b.r.backend.RPCGasCap())
1072 1073 1074
	if err != nil {
		return nil, err
	}
1075
	status := hexutil.Uint64(1)
1076
	if result.Failed() {
1077 1078
		status = 0
	}
1079

1080
	return &CallResult{
1081
		data:    result.ReturnData,
1082
		gasUsed: hexutil.Uint64(result.UsedGas),
1083
		status:  status,
1084
	}, nil
1085 1086 1087
}

func (b *Block) EstimateGas(ctx context.Context, args struct {
1088
	Data ethapi.TransactionArgs
1089 1090
}) (hexutil.Uint64, error) {
	return ethapi.DoEstimateGas(ctx, b.r.backend, args.Data, *b.numberOrHash, b.r.backend.RPCGasCap())
1091 1092 1093
}

type Pending struct {
1094
	r *Resolver
1095 1096
}

1097
func (p *Pending) TransactionCount(ctx context.Context) (hexutil.Uint64, error) {
1098
	txs, err := p.r.backend.GetPoolTransactions()
1099
	return hexutil.Uint64(len(txs)), err
1100 1101 1102
}

func (p *Pending) Transactions(ctx context.Context) (*[]*Transaction, error) {
1103
	txs, err := p.r.backend.GetPoolTransactions()
1104 1105 1106 1107 1108 1109
	if err != nil {
		return nil, err
	}
	ret := make([]*Transaction, 0, len(txs))
	for i, tx := range txs {
		ret = append(ret, &Transaction{
1110 1111 1112 1113
			r:     p.r,
			hash:  tx.Hash(),
			tx:    tx,
			index: uint64(i),
1114 1115 1116 1117 1118 1119 1120 1121
		})
	}
	return &ret, nil
}

func (p *Pending) Account(ctx context.Context, args struct {
	Address common.Address
}) *Account {
1122
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1123
	return &Account{
1124
		r:             p.r,
1125 1126
		address:       args.Address,
		blockNrOrHash: pendingBlockNr,
1127 1128 1129 1130
	}
}

func (p *Pending) Call(ctx context.Context, args struct {
1131
	Data ethapi.TransactionArgs
1132
}) (*CallResult, error) {
1133
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1134
	result, err := ethapi.DoCall(ctx, p.r.backend, args.Data, pendingBlockNr, nil, p.r.backend.RPCEVMTimeout(), p.r.backend.RPCGasCap())
1135 1136 1137
	if err != nil {
		return nil, err
	}
1138
	status := hexutil.Uint64(1)
1139
	if result.Failed() {
1140 1141
		status = 0
	}
1142

1143
	return &CallResult{
1144
		data:    result.ReturnData,
1145
		gasUsed: hexutil.Uint64(result.UsedGas),
1146
		status:  status,
1147
	}, nil
1148 1149 1150
}

func (p *Pending) EstimateGas(ctx context.Context, args struct {
1151
	Data ethapi.TransactionArgs
1152
}) (hexutil.Uint64, error) {
1153
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1154
	return ethapi.DoEstimateGas(ctx, p.r.backend, args.Data, pendingBlockNr, p.r.backend.RPCGasCap())
1155 1156
}

1157 1158
// Resolver is the top-level object in the GraphQL hierarchy.
type Resolver struct {
1159 1160
	backend      ethapi.Backend
	filterSystem *filters.FilterSystem
1161 1162 1163
}

func (r *Resolver) Block(ctx context.Context, args struct {
1164
	Number *Long
1165 1166
	Hash   *common.Hash
}) (*Block, error) {
1167
	var numberOrHash rpc.BlockNumberOrHash
1168
	if args.Number != nil {
1169 1170 1171
		if *args.Number < 0 {
			return nil, nil
		}
1172
		number := rpc.BlockNumber(*args.Number)
1173
		numberOrHash = rpc.BlockNumberOrHashWithNumber(number)
1174
	} else if args.Hash != nil {
1175
		numberOrHash = rpc.BlockNumberOrHashWithHash(*args.Hash, false)
1176
	} else {
1177 1178 1179 1180 1181
		numberOrHash = rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
	}
	block := &Block{
		r:            r,
		numberOrHash: &numberOrHash,
1182
	}
1183 1184 1185 1186
	// 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)
1187 1188
	if err != nil {
		return nil, err
1189
	} else if h == nil {
1190 1191 1192 1193 1194 1195
		return nil, nil
	}
	return block, nil
}

func (r *Resolver) Blocks(ctx context.Context, args struct {
1196 1197
	From *Long
	To   *Long
1198
}) ([]*Block, error) {
1199
	from := rpc.BlockNumber(*args.From)
1200 1201 1202 1203 1204

	var to rpc.BlockNumber
	if args.To != nil {
		to = rpc.BlockNumber(*args.To)
	} else {
1205
		to = rpc.BlockNumber(r.backend.CurrentBlock().Number.Int64())
1206 1207 1208 1209 1210 1211
	}
	if to < from {
		return []*Block{}, nil
	}
	ret := make([]*Block, 0, to-from+1)
	for i := from; i <= to; i++ {
1212
		numberOrHash := rpc.BlockNumberOrHashWithNumber(i)
1213
		block := &Block{
1214
			r:            r,
1215
			numberOrHash: &numberOrHash,
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
		}
		// 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)
1228 1229 1230 1231
	}
	return ret, nil
}

1232
func (r *Resolver) Pending(ctx context.Context) *Pending {
1233
	return &Pending{r}
1234 1235 1236 1237
}

func (r *Resolver) Transaction(ctx context.Context, args struct{ Hash common.Hash }) (*Transaction, error) {
	tx := &Transaction{
1238 1239
		r:    r,
		hash: args.Hash,
1240 1241
	}
	// Resolve the transaction; if it doesn't exist, return nil.
1242
	t, _, err := tx.resolve(ctx)
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	if err != nil {
		return nil, err
	} else if t == nil {
		return nil, nil
	}
	return tx, nil
}

func (r *Resolver) SendRawTransaction(ctx context.Context, args struct{ Data hexutil.Bytes }) (common.Hash, error) {
	tx := new(types.Transaction)
1253
	if err := tx.UnmarshalBinary(args.Data); err != nil {
1254 1255 1256 1257 1258 1259
		return common.Hash{}, err
	}
	hash, err := ethapi.SubmitTransaction(ctx, r.backend, tx)
	return hash, err
}

1260
// FilterCriteria encapsulates the arguments to `logs` on the root resolver object.
1261
type FilterCriteria struct {
1262 1263
	FromBlock *Long             // beginning of the queried range, nil means genesis block
	ToBlock   *Long             // end of the range, nil means latest block
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
	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
1299
	filter := r.filterSystem.NewRangeFilter(begin, end, addresses, topics)
1300
	return runFilter(ctx, r, filter)
1301 1302 1303
}

func (r *Resolver) GasPrice(ctx context.Context) (hexutil.Big, error) {
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
	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
1320 1321
}

1322 1323 1324 1325
func (r *Resolver) ChainID(ctx context.Context) (hexutil.Big, error) {
	return hexutil.Big(*r.backend.ChainConfig().ChainID), nil
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
// 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)
}
1340 1341
func (s *SyncState) SyncedAccounts() hexutil.Uint64 {
	return hexutil.Uint64(s.progress.SyncedAccounts)
1342
}
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
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)
1375 1376 1377 1378
}

// Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
// yet received the latest block headers from its pears. In case it is synchronizing:
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
// - startingBlock:       block number this node started to synchronise from
// - 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
1394
func (r *Resolver) Syncing() (*SyncState, error) {
1395
	progress := r.backend.SyncProgress()
1396 1397 1398 1399 1400 1401 1402 1403

	// 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
}