graphql.go 34 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
	"strconv"
26 27 28 29

	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
30
	"github.com/ethereum/go-ethereum/common/math"
31 32 33 34 35 36 37
	"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"
	"github.com/ethereum/go-ethereum/rpc"
)

38
var (
39
	errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash")
40
)
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
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
		//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
		//}
	case int32:
		*b = Long(input)
	case int64:
		*b = Long(input)
	default:
		err = fmt.Errorf("unexpected type %T for Long", input)
	}
	return err
}

73 74
// Account represents an Ethereum account at a particular block.
type Account struct {
75 76 77
	backend       ethapi.Backend
	address       common.Address
	blockNrOrHash rpc.BlockNumberOrHash
78 79 80 81
}

// getState fetches the StateDB object for an account.
func (a *Account) getState(ctx context.Context) (*state.StateDB, error) {
82
	state, _, err := a.backend.StateAndHeaderByNumberOrHash(ctx, a.blockNrOrHash)
83 84 85 86 87 88 89 90 91 92 93 94
	return state, err
}

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
	}
95 96 97 98 99
	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
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
}

func (a *Account) TransactionCount(ctx context.Context) (hexutil.Uint64, error) {
	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
	}
115
	return state.GetCode(a.address), nil
116 117 118 119 120 121 122 123 124 125 126 127
}

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 {
128
	backend     ethapi.Backend
129 130 131 132 133 134 135 136 137 138
	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{
139 140 141
		backend:       l.backend,
		address:       l.log.Address,
		blockNrOrHash: args.NumberOrLatest(),
142 143 144 145 146 147 148 149 150 151 152 153
	}
}

func (l *Log) Index(ctx context.Context) int32 {
	return int32(l.log.Index)
}

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

func (l *Log) Data(ctx context.Context) hexutil.Bytes {
154
	return l.log.Data
155 156
}

157 158 159
// AccessTuple represents EIP-2930
type AccessTuple struct {
	address     common.Address
160
	storageKeys []common.Hash
161 162 163 164 165 166
}

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

167
func (at *AccessTuple) StorageKeys(ctx context.Context) []common.Hash {
168 169 170
	return at.storageKeys
}

171
// Transaction represents an Ethereum transaction.
172 173
// backend and hash are mandatory; all others will be fetched when required.
type Transaction struct {
174
	backend ethapi.Backend
175 176 177 178 179 180 181 182 183
	hash    common.Hash
	tx      *types.Transaction
	block   *Block
	index   uint64
}

// resolve returns the internal transaction object, fetching it if needed.
func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, error) {
	if t.tx == nil {
184 185 186
		// Try to return an already finalized transaction
		tx, blockHash, _, index, err := t.backend.GetTransaction(ctx, t.hash)
		if err == nil && tx != nil {
187
			t.tx = tx
188
			blockNrOrHash := rpc.BlockNumberOrHashWithHash(blockHash, false)
189
			t.block = &Block{
190 191
				backend:      t.backend,
				numberOrHash: &blockNrOrHash,
192 193
			}
			t.index = index
194
			return t.tx, nil
195
		}
196 197
		// No finalized transaction, try to retrieve it from the pool
		t.tx = t.backend.GetPoolTransaction(t.hash)
198 199 200 201
	}
	return t.tx, nil
}

202 203
func (t *Transaction) Hash(ctx context.Context) common.Hash {
	return t.hash
204 205 206 207 208 209 210
}

func (t *Transaction) InputData(ctx context.Context) (hexutil.Bytes, error) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return hexutil.Bytes{}, err
	}
211
	return tx.Data(), nil
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
}

func (t *Transaction) Gas(ctx context.Context) (hexutil.Uint64, error) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return 0, err
	}
	return hexutil.Uint64(tx.Gas()), nil
}

func (t *Transaction) GasPrice(ctx context.Context) (hexutil.Big, error) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	switch tx.Type() {
	case types.AccessListTxType:
		return hexutil.Big(*tx.GasPrice()), nil
	case types.DynamicFeeTxType:
		if t.block != nil {
			if baseFee, _ := t.block.BaseFeePerGas(ctx); baseFee != nil {
				// 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
	}
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
func (t *Transaction) EffectiveGasPrice(ctx context.Context) (*hexutil.Big, error) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return nil, err
	}
	header, err := t.block.resolveHeader(ctx)
	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
}

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
func (t *Transaction) MaxFeePerGas(ctx context.Context) (*hexutil.Big, error) {
	tx, err := t.resolve(ctx)
	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) {
	tx, err := t.resolve(ctx)
	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
	}
286 287 288 289 290 291 292
}

func (t *Transaction) Value(ctx context.Context) (hexutil.Big, error) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
293 294 295
	if tx.Value() == nil {
		return hexutil.Big{}, fmt.Errorf("invalid transaction value %x", t.hash)
	}
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
	return hexutil.Big(*tx.Value()), nil
}

func (t *Transaction) Nonce(ctx context.Context) (hexutil.Uint64, error) {
	tx, err := t.resolve(ctx)
	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) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return nil, err
	}
	to := tx.To()
	if to == nil {
		return nil, nil
	}
	return &Account{
317 318 319
		backend:       t.backend,
		address:       *to,
		blockNrOrHash: args.NumberOrLatest(),
320 321 322 323 324 325 326 327
	}, nil
}

func (t *Transaction) From(ctx context.Context, args BlockNumberArgs) (*Account, error) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return nil, err
	}
328
	signer := types.LatestSigner(t.backend.ChainConfig())
329 330
	from, _ := types.Sender(signer, tx)
	return &Account{
331 332 333
		backend:       t.backend,
		address:       from,
		blockNrOrHash: args.NumberOrLatest(),
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
	}, nil
}

func (t *Transaction) Block(ctx context.Context) (*Block, error) {
	if _, err := t.resolve(ctx); err != nil {
		return nil, err
	}
	return t.block, nil
}

func (t *Transaction) Index(ctx context.Context) (*int32, error) {
	if _, err := t.resolve(ctx); err != nil {
		return nil, err
	}
	if t.block == nil {
		return nil, nil
	}
	index := int32(t.index)
	return &index, nil
}

// getReceipt returns the receipt associated with this transaction, if any.
func (t *Transaction) getReceipt(ctx context.Context) (*types.Receipt, error) {
	if _, err := t.resolve(ctx); err != nil {
		return nil, err
	}
	if t.block == nil {
		return nil, nil
	}
	receipts, err := t.block.resolveReceipts(ctx)
	if err != nil {
		return nil, err
	}
	return receipts[t.index], nil
}

370
func (t *Transaction) Status(ctx context.Context) (*Long, error) {
371 372 373 374
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
375
	ret := Long(receipt.Status)
376 377 378
	return &ret, nil
}

379
func (t *Transaction) GasUsed(ctx context.Context) (*Long, error) {
380 381 382 383
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
384
	ret := Long(receipt.GasUsed)
385 386 387
	return &ret, nil
}

388
func (t *Transaction) CumulativeGasUsed(ctx context.Context) (*Long, error) {
389 390 391 392
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
393
	ret := Long(receipt.CumulativeGasUsed)
394 395 396 397 398 399 400 401 402
	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{
403 404 405
		backend:       t.backend,
		address:       receipt.ContractAddress,
		blockNrOrHash: args.NumberOrLatest(),
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
	}, nil
}

func (t *Transaction) Logs(ctx context.Context) (*[]*Log, error) {
	receipt, err := t.getReceipt(ctx)
	if err != nil || receipt == nil {
		return nil, err
	}
	ret := make([]*Log, 0, len(receipt.Logs))
	for _, log := range receipt.Logs {
		ret = append(ret, &Log{
			backend:     t.backend,
			transaction: t,
			log:         log,
		})
	}
	return &ret, nil
}

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
func (t *Transaction) Type(ctx context.Context) (*int32, error) {
	tx, err := t.resolve(ctx)
	if err != nil {
		return nil, err
	}
	txType := int32(tx.Type())
	return &txType, nil
}

func (t *Transaction) AccessList(ctx context.Context) (*[]*AccessTuple, error) {
	tx, err := t.resolve(ctx)
	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,
444
			storageKeys: al.StorageKeys,
445 446 447 448 449
		})
	}
	return &ret, nil
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
func (t *Transaction) R(ctx context.Context) (hexutil.Big, error) {
	tx, err := t.resolve(ctx)
	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) {
	tx, err := t.resolve(ctx)
	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) {
	tx, err := t.resolve(ctx)
	if err != nil || tx == nil {
		return hexutil.Big{}, err
	}
	v, _, _ := tx.RawSignatureValues()
	return hexutil.Big(*v), nil
}

477 478 479
type BlockType int

// Block represents an Ethereum block.
480
// backend, and numberOrHash are mandatory. All other fields are lazily fetched
481 482
// when required.
type Block struct {
483 484 485 486 487 488
	backend      ethapi.Backend
	numberOrHash *rpc.BlockNumberOrHash
	hash         common.Hash
	header       *types.Header
	block        *types.Block
	receipts     []*types.Receipt
489 490 491 492 493 494 495 496
}

// resolve returns the internal Block object representing this block, fetching
// it if necessary.
func (b *Block) resolve(ctx context.Context) (*types.Block, error) {
	if b.block != nil {
		return b.block, nil
	}
497 498 499
	if b.numberOrHash == nil {
		latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
		b.numberOrHash = &latest
500
	}
501 502
	var err error
	b.block, err = b.backend.BlockByNumberOrHash(ctx, *b.numberOrHash)
503
	if b.block != nil && b.header == nil {
504
		b.header = b.block.Header()
505 506 507
		if hash, ok := b.numberOrHash.Hash(); ok {
			b.hash = hash
		}
508 509 510 511 512 513 514 515
	}
	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) {
516
	if b.numberOrHash == nil && b.hash == (common.Hash{}) {
517
		return nil, errBlockInvariant
518
	}
519
	var err error
520
	if b.header == nil {
521 522 523
		if b.hash != (common.Hash{}) {
			b.header, err = b.backend.HeaderByHash(ctx, b.hash)
		} else {
524
			b.header, err = b.backend.HeaderByNumberOrHash(ctx, *b.numberOrHash)
525 526
		}
	}
527
	return b.header, err
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
}

// resolveReceipts returns the list of receipts for this block, fetching them
// if necessary.
func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) {
	if b.receipts == nil {
		hash := b.hash
		if hash == (common.Hash{}) {
			header, err := b.resolveHeader(ctx)
			if err != nil {
				return nil, err
			}
			hash = header.Hash()
		}
		receipts, err := b.backend.GetReceipts(ctx, hash)
		if err != nil {
			return nil, err
		}
546
		b.receipts = receipts
547 548 549 550
	}
	return b.receipts, nil
}

551
func (b *Block) Number(ctx context.Context) (Long, error) {
552 553 554
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
555
	}
556

557
	return Long(header.Number.Uint64()), nil
558 559 560 561 562 563 564 565 566 567 568 569 570
}

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

571
func (b *Block) GasLimit(ctx context.Context) (Long, error) {
572 573 574 575
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
	}
576
	return Long(header.GasLimit), nil
577 578
}

579
func (b *Block) GasUsed(ctx context.Context) (Long, error) {
580 581 582 583
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return 0, err
	}
584
	return Long(header.GasUsed), nil
585 586
}

587 588 589 590 591 592 593 594 595 596 597
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
}

598
func (b *Block) Parent(ctx context.Context) (*Block, error) {
599
	// If the block header hasn't been fetched, and we'll need it, fetch it.
600
	if b.numberOrHash == nil && b.header == nil {
601
		if _, err := b.resolveHeader(ctx); err != nil {
602 603 604
			return nil, err
		}
	}
605
	if b.header != nil && b.header.Number.Uint64() > 0 {
606
		num := rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(b.header.Number.Uint64() - 1))
607
		return &Block{
608 609 610
			backend:      b.backend,
			numberOrHash: &num,
			hash:         b.header.ParentHash,
611 612 613 614 615 616 617 618 619 620 621 622 623
		}, nil
	}
	return nil, nil
}

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
}

624
func (b *Block) Timestamp(ctx context.Context) (hexutil.Uint64, error) {
625 626
	header, err := b.resolveHeader(ctx)
	if err != nil {
627
		return 0, err
628
	}
629
	return hexutil.Uint64(header.Time), nil
630 631 632 633 634 635 636
}

func (b *Block) Nonce(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
637
	return header.Nonce[:], nil
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
}

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
}

func (b *Block) OmmerCount(ctx context.Context) (*int32, error) {
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
	count := int32(len(block.Uncles()))
	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() {
696
		blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
697
		ret = append(ret, &Block{
698 699 700
			backend:      b.backend,
			numberOrHash: &blockNumberOrHash,
			header:       uncle,
701 702 703 704 705 706 707 708 709 710
		})
	}
	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
	}
711
	return header.Extra, nil
712 713 714 715 716 717 718
}

func (b *Block) LogsBloom(ctx context.Context) (hexutil.Bytes, error) {
	header, err := b.resolveHeader(ctx)
	if err != nil {
		return hexutil.Bytes{}, err
	}
719
	return header.Bloom.Bytes(), nil
720 721 722 723 724 725 726 727 728 729 730
}

func (b *Block) TotalDifficulty(ctx context.Context) (hexutil.Big, error) {
	h := b.hash
	if h == (common.Hash{}) {
		header, err := b.resolveHeader(ctx)
		if err != nil {
			return hexutil.Big{}, err
		}
		h = header.Hash()
	}
731 732 733 734 735
	td := b.backend.GetTd(ctx, h)
	if td == nil {
		return hexutil.Big{}, fmt.Errorf("total difficulty not found %x", b.hash)
	}
	return hexutil.Big(*td), nil
736 737 738 739
}

// BlockNumberArgs encapsulates arguments to accessors that specify a block number.
type BlockNumberArgs struct {
740 741 742
	// 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
743 744 745
	Block *hexutil.Uint64
}

746
// NumberOr returns the provided block number argument, or the "current" block number or hash if none
747
// was provided.
748
func (a BlockNumberArgs) NumberOr(current rpc.BlockNumberOrHash) rpc.BlockNumberOrHash {
749
	if a.Block != nil {
750 751
		blockNr := rpc.BlockNumber(*a.Block)
		return rpc.BlockNumberOrHashWithNumber(blockNr)
752
	}
753 754 755 756 757 758 759
	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))
760 761 762
}

func (b *Block) Miner(ctx context.Context, args BlockNumberArgs) (*Account, error) {
763
	header, err := b.resolveHeader(ctx)
764 765 766 767
	if err != nil {
		return nil, err
	}
	return &Account{
768 769 770
		backend:       b.backend,
		address:       header.Coinbase,
		blockNrOrHash: args.NumberOrLatest(),
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
	}, nil
}

func (b *Block) TransactionCount(ctx context.Context) (*int32, error) {
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
	count := int32(len(block.Transactions()))
	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{
			backend: b.backend,
			hash:    tx.Hash(),
			tx:      tx,
			block:   b,
			index:   uint64(i),
		})
	}
	return &ret, nil
}

func (b *Block) TransactionAt(ctx context.Context, args struct{ Index int32 }) (*Transaction, error) {
	block, err := b.resolve(ctx)
	if err != nil || block == nil {
		return nil, err
	}
806 807
	txs := block.Transactions()
	if args.Index < 0 || int(args.Index) >= len(txs) {
808 809
		return nil, nil
	}
810
	tx := txs[args.Index]
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
	return &Transaction{
		backend: b.backend,
		hash:    tx.Hash(),
		tx:      tx,
		block:   b,
		index:   uint64(args.Index),
	}, nil
}

func (b *Block) OmmerAt(ctx context.Context, args struct{ Index int32 }) (*Block, error) {
	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]
830
	blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
831
	return &Block{
832 833 834
		backend:      b.backend,
		numberOrHash: &blockNumberOrHash,
		header:       uncle,
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
	}, 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.
859
func runFilter(ctx context.Context, be ethapi.Backend, filter *filters.Filter) ([]*Log, error) {
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
	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{
			backend:     be,
			transaction: &Transaction{backend: be, hash: log.TxHash},
			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
	}
	hash := b.hash
	if hash == (common.Hash{}) {
886
		header, err := b.resolveHeader(ctx)
887 888 889
		if err != nil {
			return nil, err
		}
890
		hash = header.Hash()
891 892 893 894 895 896 897 898
	}
	// Construct the range filter
	filter := filters.NewBlockFilter(b.backend, hash, addresses, topics)

	// Run the filter and return all the logs
	return runFilter(ctx, b.backend, filter)
}

899 900 901
func (b *Block) Account(ctx context.Context, args struct {
	Address common.Address
}) (*Account, error) {
902
	if b.numberOrHash == nil {
903 904 905 906 907 908
		_, err := b.resolveHeader(ctx)
		if err != nil {
			return nil, err
		}
	}
	return &Account{
909 910 911
		backend:       b.backend,
		address:       args.Address,
		blockNrOrHash: *b.numberOrHash,
912 913 914 915 916 917
	}, nil
}

// CallData encapsulates arguments to `call` or `estimateGas`.
// All arguments are optional.
type CallData struct {
918 919 920 921 922 923 924 925
	From                 *common.Address // The Ethereum address the call is from.
	To                   *common.Address // The Ethereum address the call is to.
	Gas                  *hexutil.Uint64 // The amount of gas provided for the call.
	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.
926 927 928 929
}

// CallResult encapsulates the result of an invocation of the `call` accessor.
type CallResult struct {
930 931 932
	data    hexutil.Bytes // The return data from the call
	gasUsed Long          // The amount of gas used
	status  Long          // The return status of the call - 0 for failure or 1 for success.
933 934 935 936 937 938
}

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

939
func (c *CallResult) GasUsed() Long {
940 941 942
	return c.gasUsed
}

943
func (c *CallResult) Status() Long {
944 945 946 947
	return c.status
}

func (b *Block) Call(ctx context.Context, args struct {
948
	Data ethapi.TransactionArgs
949
}) (*CallResult, error) {
950 951
	if b.numberOrHash == nil {
		_, err := b.resolve(ctx)
952 953 954 955
		if err != nil {
			return nil, err
		}
	}
956
	result, err := ethapi.DoCall(ctx, b.backend, args.Data, *b.numberOrHash, nil, b.backend.RPCEVMTimeout(), b.backend.RPCGasCap())
957 958 959
	if err != nil {
		return nil, err
	}
960
	status := Long(1)
961
	if result.Failed() {
962 963
		status = 0
	}
964

965
	return &CallResult{
966
		data:    result.ReturnData,
967
		gasUsed: Long(result.UsedGas),
968
		status:  status,
969
	}, nil
970 971 972
}

func (b *Block) EstimateGas(ctx context.Context, args struct {
973
	Data ethapi.TransactionArgs
974
}) (Long, error) {
975
	if b.numberOrHash == nil {
976 977
		_, err := b.resolveHeader(ctx)
		if err != nil {
978
			return 0, err
979 980
		}
	}
981
	gas, err := ethapi.DoEstimateGas(ctx, b.backend, args.Data, *b.numberOrHash, b.backend.RPCGasCap())
982
	return Long(gas), err
983 984 985
}

type Pending struct {
986
	backend ethapi.Backend
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 1012 1013
}

func (p *Pending) TransactionCount(ctx context.Context) (int32, error) {
	txs, err := p.backend.GetPoolTransactions()
	return int32(len(txs)), err
}

func (p *Pending) Transactions(ctx context.Context) (*[]*Transaction, error) {
	txs, err := p.backend.GetPoolTransactions()
	if err != nil {
		return nil, err
	}
	ret := make([]*Transaction, 0, len(txs))
	for i, tx := range txs {
		ret = append(ret, &Transaction{
			backend: p.backend,
			hash:    tx.Hash(),
			tx:      tx,
			index:   uint64(i),
		})
	}
	return &ret, nil
}

func (p *Pending) Account(ctx context.Context, args struct {
	Address common.Address
}) *Account {
1014
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1015
	return &Account{
1016 1017 1018
		backend:       p.backend,
		address:       args.Address,
		blockNrOrHash: pendingBlockNr,
1019 1020 1021 1022
	}
}

func (p *Pending) Call(ctx context.Context, args struct {
1023
	Data ethapi.TransactionArgs
1024
}) (*CallResult, error) {
1025
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1026
	result, err := ethapi.DoCall(ctx, p.backend, args.Data, pendingBlockNr, nil, p.backend.RPCEVMTimeout(), p.backend.RPCGasCap())
1027 1028 1029
	if err != nil {
		return nil, err
	}
1030
	status := Long(1)
1031
	if result.Failed() {
1032 1033
		status = 0
	}
1034

1035
	return &CallResult{
1036
		data:    result.ReturnData,
1037
		gasUsed: Long(result.UsedGas),
1038
		status:  status,
1039
	}, nil
1040 1041 1042
}

func (p *Pending) EstimateGas(ctx context.Context, args struct {
1043
	Data ethapi.TransactionArgs
1044
}) (Long, error) {
1045
	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
1046 1047
	gas, err := ethapi.DoEstimateGas(ctx, p.backend, args.Data, pendingBlockNr, p.backend.RPCGasCap())
	return Long(gas), err
1048 1049
}

1050 1051
// Resolver is the top-level object in the GraphQL hierarchy.
type Resolver struct {
1052
	backend ethapi.Backend
1053 1054 1055
}

func (r *Resolver) Block(ctx context.Context, args struct {
1056
	Number *Long
1057 1058 1059 1060
	Hash   *common.Hash
}) (*Block, error) {
	var block *Block
	if args.Number != nil {
1061 1062 1063
		if *args.Number < 0 {
			return nil, nil
		}
1064
		number := rpc.BlockNumber(*args.Number)
1065
		numberOrHash := rpc.BlockNumberOrHashWithNumber(number)
1066
		block = &Block{
1067 1068
			backend:      r.backend,
			numberOrHash: &numberOrHash,
1069 1070
		}
	} else if args.Hash != nil {
1071
		numberOrHash := rpc.BlockNumberOrHashWithHash(*args.Hash, false)
1072
		block = &Block{
1073 1074
			backend:      r.backend,
			numberOrHash: &numberOrHash,
1075 1076
		}
	} else {
1077
		numberOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
1078
		block = &Block{
1079 1080
			backend:      r.backend,
			numberOrHash: &numberOrHash,
1081 1082
		}
	}
1083 1084 1085 1086
	// 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)
1087 1088
	if err != nil {
		return nil, err
1089
	} else if h == nil {
1090 1091 1092 1093 1094 1095
		return nil, nil
	}
	return block, nil
}

func (r *Resolver) Blocks(ctx context.Context, args struct {
1096 1097
	From *Long
	To   *Long
1098
}) ([]*Block, error) {
1099
	from := rpc.BlockNumber(*args.From)
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

	var to rpc.BlockNumber
	if args.To != nil {
		to = rpc.BlockNumber(*args.To)
	} else {
		to = rpc.BlockNumber(r.backend.CurrentBlock().Number().Int64())
	}
	if to < from {
		return []*Block{}, nil
	}
	ret := make([]*Block, 0, to-from+1)
	for i := from; i <= to; i++ {
1112
		numberOrHash := rpc.BlockNumberOrHashWithNumber(i)
1113
		ret = append(ret, &Block{
1114 1115
			backend:      r.backend,
			numberOrHash: &numberOrHash,
1116 1117 1118 1119 1120
		})
	}
	return ret, nil
}

1121 1122
func (r *Resolver) Pending(ctx context.Context) *Pending {
	return &Pending{r.backend}
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
}

func (r *Resolver) Transaction(ctx context.Context, args struct{ Hash common.Hash }) (*Transaction, error) {
	tx := &Transaction{
		backend: r.backend,
		hash:    args.Hash,
	}
	// Resolve the transaction; if it doesn't exist, return nil.
	t, err := tx.resolve(ctx)
	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)
1142
	if err := tx.UnmarshalBinary(args.Data); err != nil {
1143 1144 1145 1146 1147 1148
		return common.Hash{}, err
	}
	hash, err := ethapi.SubmitTransaction(ctx, r.backend, tx)
	return hash, err
}

1149
// FilterCriteria encapsulates the arguments to `logs` on the root resolver object.
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
type FilterCriteria struct {
	FromBlock *hexutil.Uint64   // beginning of the queried range, nil means genesis block
	ToBlock   *hexutil.Uint64   // end of the range, nil means latest block
	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
	filter := filters.NewRangeFilter(filters.Backend(r.backend), begin, end, addresses, topics)
	return runFilter(ctx, r.backend, filter)
}

func (r *Resolver) GasPrice(ctx context.Context) (hexutil.Big, error) {
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	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
1209 1210
}

1211 1212 1213 1214
func (r *Resolver) ChainID(ctx context.Context) (hexutil.Big, error) {
	return hexutil.Big(*r.backend.ChainConfig().ChainID), nil
}

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
// 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)
}

func (s *SyncState) PulledStates() *hexutil.Uint64 {
	ret := hexutil.Uint64(s.progress.PulledStates)
	return &ret
}

func (s *SyncState) KnownStates() *hexutil.Uint64 {
	ret := hexutil.Uint64(s.progress.KnownStates)
	return &ret
}

// 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:
// - 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
// - pulledStates:  number of state entries processed until now
// - knownStates:   number of known state entries that still need to be pulled
func (r *Resolver) Syncing() (*SyncState, error) {
1250
	progress := r.backend.SyncProgress()
1251 1252 1253 1254 1255 1256 1257 1258

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