github.com/AlohaMobile/go-ethereum@v1.9.7/graphql/graphql.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package graphql provides a GraphQL interface to Ethereum node data.
    18  package graphql
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum"
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/core/rawdb"
    29  	"github.com/ethereum/go-ethereum/core/state"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/core/vm"
    32  	"github.com/ethereum/go-ethereum/eth/filters"
    33  	"github.com/ethereum/go-ethereum/internal/ethapi"
    34  	"github.com/ethereum/go-ethereum/rlp"
    35  	"github.com/ethereum/go-ethereum/rpc"
    36  )
    37  
    38  var (
    39  	errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash")
    40  )
    41  
    42  // Account represents an Ethereum account at a particular block.
    43  type Account struct {
    44  	backend       ethapi.Backend
    45  	address       common.Address
    46  	blockNrOrHash rpc.BlockNumberOrHash
    47  }
    48  
    49  // getState fetches the StateDB object for an account.
    50  func (a *Account) getState(ctx context.Context) (*state.StateDB, error) {
    51  	state, _, err := a.backend.StateAndHeaderByNumberOrHash(ctx, a.blockNrOrHash)
    52  	return state, err
    53  }
    54  
    55  func (a *Account) Address(ctx context.Context) (common.Address, error) {
    56  	return a.address, nil
    57  }
    58  
    59  func (a *Account) Balance(ctx context.Context) (hexutil.Big, error) {
    60  	state, err := a.getState(ctx)
    61  	if err != nil {
    62  		return hexutil.Big{}, err
    63  	}
    64  	return hexutil.Big(*state.GetBalance(a.address)), nil
    65  }
    66  
    67  func (a *Account) TransactionCount(ctx context.Context) (hexutil.Uint64, error) {
    68  	state, err := a.getState(ctx)
    69  	if err != nil {
    70  		return 0, err
    71  	}
    72  	return hexutil.Uint64(state.GetNonce(a.address)), nil
    73  }
    74  
    75  func (a *Account) Code(ctx context.Context) (hexutil.Bytes, error) {
    76  	state, err := a.getState(ctx)
    77  	if err != nil {
    78  		return hexutil.Bytes{}, err
    79  	}
    80  	return hexutil.Bytes(state.GetCode(a.address)), nil
    81  }
    82  
    83  func (a *Account) Storage(ctx context.Context, args struct{ Slot common.Hash }) (common.Hash, error) {
    84  	state, err := a.getState(ctx)
    85  	if err != nil {
    86  		return common.Hash{}, err
    87  	}
    88  	return state.GetState(a.address, args.Slot), nil
    89  }
    90  
    91  // Log represents an individual log message. All arguments are mandatory.
    92  type Log struct {
    93  	backend     ethapi.Backend
    94  	transaction *Transaction
    95  	log         *types.Log
    96  }
    97  
    98  func (l *Log) Transaction(ctx context.Context) *Transaction {
    99  	return l.transaction
   100  }
   101  
   102  func (l *Log) Account(ctx context.Context, args BlockNumberArgs) *Account {
   103  	return &Account{
   104  		backend:       l.backend,
   105  		address:       l.log.Address,
   106  		blockNrOrHash: args.NumberOrLatest(),
   107  	}
   108  }
   109  
   110  func (l *Log) Index(ctx context.Context) int32 {
   111  	return int32(l.log.Index)
   112  }
   113  
   114  func (l *Log) Topics(ctx context.Context) []common.Hash {
   115  	return l.log.Topics
   116  }
   117  
   118  func (l *Log) Data(ctx context.Context) hexutil.Bytes {
   119  	return hexutil.Bytes(l.log.Data)
   120  }
   121  
   122  // Transaction represents an Ethereum transaction.
   123  // backend and hash are mandatory; all others will be fetched when required.
   124  type Transaction struct {
   125  	backend ethapi.Backend
   126  	hash    common.Hash
   127  	tx      *types.Transaction
   128  	block   *Block
   129  	index   uint64
   130  }
   131  
   132  // resolve returns the internal transaction object, fetching it if needed.
   133  func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, error) {
   134  	if t.tx == nil {
   135  		tx, blockHash, _, index := rawdb.ReadTransaction(t.backend.ChainDb(), t.hash)
   136  		if tx != nil {
   137  			t.tx = tx
   138  			blockNrOrHash := rpc.BlockNumberOrHashWithHash(blockHash, false)
   139  			t.block = &Block{
   140  				backend:      t.backend,
   141  				numberOrHash: &blockNrOrHash,
   142  			}
   143  			t.index = index
   144  		} else {
   145  			t.tx = t.backend.GetPoolTransaction(t.hash)
   146  		}
   147  	}
   148  	return t.tx, nil
   149  }
   150  
   151  func (t *Transaction) Hash(ctx context.Context) common.Hash {
   152  	return t.hash
   153  }
   154  
   155  func (t *Transaction) InputData(ctx context.Context) (hexutil.Bytes, error) {
   156  	tx, err := t.resolve(ctx)
   157  	if err != nil || tx == nil {
   158  		return hexutil.Bytes{}, err
   159  	}
   160  	return hexutil.Bytes(tx.Data()), nil
   161  }
   162  
   163  func (t *Transaction) Gas(ctx context.Context) (hexutil.Uint64, error) {
   164  	tx, err := t.resolve(ctx)
   165  	if err != nil || tx == nil {
   166  		return 0, err
   167  	}
   168  	return hexutil.Uint64(tx.Gas()), nil
   169  }
   170  
   171  func (t *Transaction) GasPrice(ctx context.Context) (hexutil.Big, error) {
   172  	tx, err := t.resolve(ctx)
   173  	if err != nil || tx == nil {
   174  		return hexutil.Big{}, err
   175  	}
   176  	return hexutil.Big(*tx.GasPrice()), nil
   177  }
   178  
   179  func (t *Transaction) Value(ctx context.Context) (hexutil.Big, error) {
   180  	tx, err := t.resolve(ctx)
   181  	if err != nil || tx == nil {
   182  		return hexutil.Big{}, err
   183  	}
   184  	return hexutil.Big(*tx.Value()), nil
   185  }
   186  
   187  func (t *Transaction) Nonce(ctx context.Context) (hexutil.Uint64, error) {
   188  	tx, err := t.resolve(ctx)
   189  	if err != nil || tx == nil {
   190  		return 0, err
   191  	}
   192  	return hexutil.Uint64(tx.Nonce()), nil
   193  }
   194  
   195  func (t *Transaction) To(ctx context.Context, args BlockNumberArgs) (*Account, error) {
   196  	tx, err := t.resolve(ctx)
   197  	if err != nil || tx == nil {
   198  		return nil, err
   199  	}
   200  	to := tx.To()
   201  	if to == nil {
   202  		return nil, nil
   203  	}
   204  	return &Account{
   205  		backend:       t.backend,
   206  		address:       *to,
   207  		blockNrOrHash: args.NumberOrLatest(),
   208  	}, nil
   209  }
   210  
   211  func (t *Transaction) From(ctx context.Context, args BlockNumberArgs) (*Account, error) {
   212  	tx, err := t.resolve(ctx)
   213  	if err != nil || tx == nil {
   214  		return nil, err
   215  	}
   216  	var signer types.Signer = types.HomesteadSigner{}
   217  	if tx.Protected() {
   218  		signer = types.NewEIP155Signer(tx.ChainId())
   219  	}
   220  	from, _ := types.Sender(signer, tx)
   221  
   222  	return &Account{
   223  		backend:       t.backend,
   224  		address:       from,
   225  		blockNrOrHash: args.NumberOrLatest(),
   226  	}, nil
   227  }
   228  
   229  func (t *Transaction) Block(ctx context.Context) (*Block, error) {
   230  	if _, err := t.resolve(ctx); err != nil {
   231  		return nil, err
   232  	}
   233  	return t.block, nil
   234  }
   235  
   236  func (t *Transaction) Index(ctx context.Context) (*int32, error) {
   237  	if _, err := t.resolve(ctx); err != nil {
   238  		return nil, err
   239  	}
   240  	if t.block == nil {
   241  		return nil, nil
   242  	}
   243  	index := int32(t.index)
   244  	return &index, nil
   245  }
   246  
   247  // getReceipt returns the receipt associated with this transaction, if any.
   248  func (t *Transaction) getReceipt(ctx context.Context) (*types.Receipt, error) {
   249  	if _, err := t.resolve(ctx); err != nil {
   250  		return nil, err
   251  	}
   252  	if t.block == nil {
   253  		return nil, nil
   254  	}
   255  	receipts, err := t.block.resolveReceipts(ctx)
   256  	if err != nil {
   257  		return nil, err
   258  	}
   259  	return receipts[t.index], nil
   260  }
   261  
   262  func (t *Transaction) Status(ctx context.Context) (*hexutil.Uint64, error) {
   263  	receipt, err := t.getReceipt(ctx)
   264  	if err != nil || receipt == nil {
   265  		return nil, err
   266  	}
   267  	ret := hexutil.Uint64(receipt.Status)
   268  	return &ret, nil
   269  }
   270  
   271  func (t *Transaction) GasUsed(ctx context.Context) (*hexutil.Uint64, error) {
   272  	receipt, err := t.getReceipt(ctx)
   273  	if err != nil || receipt == nil {
   274  		return nil, err
   275  	}
   276  	ret := hexutil.Uint64(receipt.GasUsed)
   277  	return &ret, nil
   278  }
   279  
   280  func (t *Transaction) CumulativeGasUsed(ctx context.Context) (*hexutil.Uint64, error) {
   281  	receipt, err := t.getReceipt(ctx)
   282  	if err != nil || receipt == nil {
   283  		return nil, err
   284  	}
   285  	ret := hexutil.Uint64(receipt.CumulativeGasUsed)
   286  	return &ret, nil
   287  }
   288  
   289  func (t *Transaction) CreatedContract(ctx context.Context, args BlockNumberArgs) (*Account, error) {
   290  	receipt, err := t.getReceipt(ctx)
   291  	if err != nil || receipt == nil || receipt.ContractAddress == (common.Address{}) {
   292  		return nil, err
   293  	}
   294  	return &Account{
   295  		backend:       t.backend,
   296  		address:       receipt.ContractAddress,
   297  		blockNrOrHash: args.NumberOrLatest(),
   298  	}, nil
   299  }
   300  
   301  func (t *Transaction) Logs(ctx context.Context) (*[]*Log, error) {
   302  	receipt, err := t.getReceipt(ctx)
   303  	if err != nil || receipt == nil {
   304  		return nil, err
   305  	}
   306  	ret := make([]*Log, 0, len(receipt.Logs))
   307  	for _, log := range receipt.Logs {
   308  		ret = append(ret, &Log{
   309  			backend:     t.backend,
   310  			transaction: t,
   311  			log:         log,
   312  		})
   313  	}
   314  	return &ret, nil
   315  }
   316  
   317  type BlockType int
   318  
   319  // Block represents an Ethereum block.
   320  // backend, and numberOrHash are mandatory. All other fields are lazily fetched
   321  // when required.
   322  type Block struct {
   323  	backend      ethapi.Backend
   324  	numberOrHash *rpc.BlockNumberOrHash
   325  	hash         common.Hash
   326  	header       *types.Header
   327  	block        *types.Block
   328  	receipts     []*types.Receipt
   329  }
   330  
   331  // resolve returns the internal Block object representing this block, fetching
   332  // it if necessary.
   333  func (b *Block) resolve(ctx context.Context) (*types.Block, error) {
   334  	if b.block != nil {
   335  		return b.block, nil
   336  	}
   337  	if b.numberOrHash == nil {
   338  		latest := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
   339  		b.numberOrHash = &latest
   340  	}
   341  	var err error
   342  	b.block, err = b.backend.BlockByNumberOrHash(ctx, *b.numberOrHash)
   343  	if b.block != nil && b.header == nil {
   344  		b.header = b.block.Header()
   345  		if hash, ok := b.numberOrHash.Hash(); ok {
   346  			b.hash = hash
   347  		}
   348  	}
   349  	return b.block, err
   350  }
   351  
   352  // resolveHeader returns the internal Header object for this block, fetching it
   353  // if necessary. Call this function instead of `resolve` unless you need the
   354  // additional data (transactions and uncles).
   355  func (b *Block) resolveHeader(ctx context.Context) (*types.Header, error) {
   356  	if b.numberOrHash == nil && b.hash == (common.Hash{}) {
   357  		return nil, errBlockInvariant
   358  	}
   359  	var err error
   360  	if b.header == nil {
   361  		if b.hash != (common.Hash{}) {
   362  			b.header, err = b.backend.HeaderByHash(ctx, b.hash)
   363  		} else {
   364  			b.header, err = b.backend.HeaderByNumberOrHash(ctx, *b.numberOrHash)
   365  		}
   366  	}
   367  	return b.header, err
   368  }
   369  
   370  // resolveReceipts returns the list of receipts for this block, fetching them
   371  // if necessary.
   372  func (b *Block) resolveReceipts(ctx context.Context) ([]*types.Receipt, error) {
   373  	if b.receipts == nil {
   374  		hash := b.hash
   375  		if hash == (common.Hash{}) {
   376  			header, err := b.resolveHeader(ctx)
   377  			if err != nil {
   378  				return nil, err
   379  			}
   380  			hash = header.Hash()
   381  		}
   382  		receipts, err := b.backend.GetReceipts(ctx, hash)
   383  		if err != nil {
   384  			return nil, err
   385  		}
   386  		b.receipts = []*types.Receipt(receipts)
   387  	}
   388  	return b.receipts, nil
   389  }
   390  
   391  func (b *Block) Number(ctx context.Context) (hexutil.Uint64, error) {
   392  	header, err := b.resolveHeader(ctx)
   393  	if err != nil {
   394  		return 0, err
   395  	}
   396  
   397  	return hexutil.Uint64(header.Number.Uint64()), nil
   398  }
   399  
   400  func (b *Block) Hash(ctx context.Context) (common.Hash, error) {
   401  	if b.hash == (common.Hash{}) {
   402  		header, err := b.resolveHeader(ctx)
   403  		if err != nil {
   404  			return common.Hash{}, err
   405  		}
   406  		b.hash = header.Hash()
   407  	}
   408  	return b.hash, nil
   409  }
   410  
   411  func (b *Block) GasLimit(ctx context.Context) (hexutil.Uint64, error) {
   412  	header, err := b.resolveHeader(ctx)
   413  	if err != nil {
   414  		return 0, err
   415  	}
   416  	return hexutil.Uint64(header.GasLimit), nil
   417  }
   418  
   419  func (b *Block) GasUsed(ctx context.Context) (hexutil.Uint64, error) {
   420  	header, err := b.resolveHeader(ctx)
   421  	if err != nil {
   422  		return 0, err
   423  	}
   424  	return hexutil.Uint64(header.GasUsed), nil
   425  }
   426  
   427  func (b *Block) Parent(ctx context.Context) (*Block, error) {
   428  	// If the block header hasn't been fetched, and we'll need it, fetch it.
   429  	if b.numberOrHash == nil && b.header == nil {
   430  		if _, err := b.resolveHeader(ctx); err != nil {
   431  			return nil, err
   432  		}
   433  	}
   434  	if b.header != nil && b.header.Number.Uint64() > 0 {
   435  		num := rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(b.header.Number.Uint64() - 1))
   436  		return &Block{
   437  			backend:      b.backend,
   438  			numberOrHash: &num,
   439  			hash:         b.header.ParentHash,
   440  		}, nil
   441  	}
   442  	return nil, nil
   443  }
   444  
   445  func (b *Block) Difficulty(ctx context.Context) (hexutil.Big, error) {
   446  	header, err := b.resolveHeader(ctx)
   447  	if err != nil {
   448  		return hexutil.Big{}, err
   449  	}
   450  	return hexutil.Big(*header.Difficulty), nil
   451  }
   452  
   453  func (b *Block) Timestamp(ctx context.Context) (hexutil.Uint64, error) {
   454  	header, err := b.resolveHeader(ctx)
   455  	if err != nil {
   456  		return 0, err
   457  	}
   458  	return hexutil.Uint64(header.Time), nil
   459  }
   460  
   461  func (b *Block) Nonce(ctx context.Context) (hexutil.Bytes, error) {
   462  	header, err := b.resolveHeader(ctx)
   463  	if err != nil {
   464  		return hexutil.Bytes{}, err
   465  	}
   466  	return hexutil.Bytes(header.Nonce[:]), nil
   467  }
   468  
   469  func (b *Block) MixHash(ctx context.Context) (common.Hash, error) {
   470  	header, err := b.resolveHeader(ctx)
   471  	if err != nil {
   472  		return common.Hash{}, err
   473  	}
   474  	return header.MixDigest, nil
   475  }
   476  
   477  func (b *Block) TransactionsRoot(ctx context.Context) (common.Hash, error) {
   478  	header, err := b.resolveHeader(ctx)
   479  	if err != nil {
   480  		return common.Hash{}, err
   481  	}
   482  	return header.TxHash, nil
   483  }
   484  
   485  func (b *Block) StateRoot(ctx context.Context) (common.Hash, error) {
   486  	header, err := b.resolveHeader(ctx)
   487  	if err != nil {
   488  		return common.Hash{}, err
   489  	}
   490  	return header.Root, nil
   491  }
   492  
   493  func (b *Block) ReceiptsRoot(ctx context.Context) (common.Hash, error) {
   494  	header, err := b.resolveHeader(ctx)
   495  	if err != nil {
   496  		return common.Hash{}, err
   497  	}
   498  	return header.ReceiptHash, nil
   499  }
   500  
   501  func (b *Block) OmmerHash(ctx context.Context) (common.Hash, error) {
   502  	header, err := b.resolveHeader(ctx)
   503  	if err != nil {
   504  		return common.Hash{}, err
   505  	}
   506  	return header.UncleHash, nil
   507  }
   508  
   509  func (b *Block) OmmerCount(ctx context.Context) (*int32, error) {
   510  	block, err := b.resolve(ctx)
   511  	if err != nil || block == nil {
   512  		return nil, err
   513  	}
   514  	count := int32(len(block.Uncles()))
   515  	return &count, err
   516  }
   517  
   518  func (b *Block) Ommers(ctx context.Context) (*[]*Block, error) {
   519  	block, err := b.resolve(ctx)
   520  	if err != nil || block == nil {
   521  		return nil, err
   522  	}
   523  	ret := make([]*Block, 0, len(block.Uncles()))
   524  	for _, uncle := range block.Uncles() {
   525  		blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
   526  		ret = append(ret, &Block{
   527  			backend:      b.backend,
   528  			numberOrHash: &blockNumberOrHash,
   529  			header:       uncle,
   530  		})
   531  	}
   532  	return &ret, nil
   533  }
   534  
   535  func (b *Block) ExtraData(ctx context.Context) (hexutil.Bytes, error) {
   536  	header, err := b.resolveHeader(ctx)
   537  	if err != nil {
   538  		return hexutil.Bytes{}, err
   539  	}
   540  	return hexutil.Bytes(header.Extra), nil
   541  }
   542  
   543  func (b *Block) LogsBloom(ctx context.Context) (hexutil.Bytes, error) {
   544  	header, err := b.resolveHeader(ctx)
   545  	if err != nil {
   546  		return hexutil.Bytes{}, err
   547  	}
   548  	return hexutil.Bytes(header.Bloom.Bytes()), nil
   549  }
   550  
   551  func (b *Block) TotalDifficulty(ctx context.Context) (hexutil.Big, error) {
   552  	h := b.hash
   553  	if h == (common.Hash{}) {
   554  		header, err := b.resolveHeader(ctx)
   555  		if err != nil {
   556  			return hexutil.Big{}, err
   557  		}
   558  		h = header.Hash()
   559  	}
   560  	return hexutil.Big(*b.backend.GetTd(h)), nil
   561  }
   562  
   563  // BlockNumberArgs encapsulates arguments to accessors that specify a block number.
   564  type BlockNumberArgs struct {
   565  	// TODO: Ideally we could use input unions to allow the query to specify the
   566  	// block parameter by hash, block number, or tag but input unions aren't part of the
   567  	// standard GraphQL schema SDL yet, see: https://github.com/graphql/graphql-spec/issues/488
   568  	Block *hexutil.Uint64
   569  }
   570  
   571  // NumberOr returns the provided block number argument, or the "current" block number or hash if none
   572  // was provided.
   573  func (a BlockNumberArgs) NumberOr(current rpc.BlockNumberOrHash) rpc.BlockNumberOrHash {
   574  	if a.Block != nil {
   575  		blockNr := rpc.BlockNumber(*a.Block)
   576  		return rpc.BlockNumberOrHashWithNumber(blockNr)
   577  	}
   578  	return current
   579  }
   580  
   581  // NumberOrLatest returns the provided block number argument, or the "latest" block number if none
   582  // was provided.
   583  func (a BlockNumberArgs) NumberOrLatest() rpc.BlockNumberOrHash {
   584  	return a.NumberOr(rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber))
   585  }
   586  
   587  func (b *Block) Miner(ctx context.Context, args BlockNumberArgs) (*Account, error) {
   588  	header, err := b.resolveHeader(ctx)
   589  	if err != nil {
   590  		return nil, err
   591  	}
   592  	return &Account{
   593  		backend:       b.backend,
   594  		address:       header.Coinbase,
   595  		blockNrOrHash: args.NumberOrLatest(),
   596  	}, nil
   597  }
   598  
   599  func (b *Block) TransactionCount(ctx context.Context) (*int32, error) {
   600  	block, err := b.resolve(ctx)
   601  	if err != nil || block == nil {
   602  		return nil, err
   603  	}
   604  	count := int32(len(block.Transactions()))
   605  	return &count, err
   606  }
   607  
   608  func (b *Block) Transactions(ctx context.Context) (*[]*Transaction, error) {
   609  	block, err := b.resolve(ctx)
   610  	if err != nil || block == nil {
   611  		return nil, err
   612  	}
   613  	ret := make([]*Transaction, 0, len(block.Transactions()))
   614  	for i, tx := range block.Transactions() {
   615  		ret = append(ret, &Transaction{
   616  			backend: b.backend,
   617  			hash:    tx.Hash(),
   618  			tx:      tx,
   619  			block:   b,
   620  			index:   uint64(i),
   621  		})
   622  	}
   623  	return &ret, nil
   624  }
   625  
   626  func (b *Block) TransactionAt(ctx context.Context, args struct{ Index int32 }) (*Transaction, error) {
   627  	block, err := b.resolve(ctx)
   628  	if err != nil || block == nil {
   629  		return nil, err
   630  	}
   631  	txs := block.Transactions()
   632  	if args.Index < 0 || int(args.Index) >= len(txs) {
   633  		return nil, nil
   634  	}
   635  	tx := txs[args.Index]
   636  	return &Transaction{
   637  		backend: b.backend,
   638  		hash:    tx.Hash(),
   639  		tx:      tx,
   640  		block:   b,
   641  		index:   uint64(args.Index),
   642  	}, nil
   643  }
   644  
   645  func (b *Block) OmmerAt(ctx context.Context, args struct{ Index int32 }) (*Block, error) {
   646  	block, err := b.resolve(ctx)
   647  	if err != nil || block == nil {
   648  		return nil, err
   649  	}
   650  	uncles := block.Uncles()
   651  	if args.Index < 0 || int(args.Index) >= len(uncles) {
   652  		return nil, nil
   653  	}
   654  	uncle := uncles[args.Index]
   655  	blockNumberOrHash := rpc.BlockNumberOrHashWithHash(uncle.Hash(), false)
   656  	return &Block{
   657  		backend:      b.backend,
   658  		numberOrHash: &blockNumberOrHash,
   659  		header:       uncle,
   660  	}, nil
   661  }
   662  
   663  // BlockFilterCriteria encapsulates criteria passed to a `logs` accessor inside
   664  // a block.
   665  type BlockFilterCriteria struct {
   666  	Addresses *[]common.Address // restricts matches to events created by specific contracts
   667  
   668  	// The Topic list restricts matches to particular event topics. Each event has a list
   669  	// of topics. Topics matches a prefix of that list. An empty element slice matches any
   670  	// topic. Non-empty elements represent an alternative that matches any of the
   671  	// contained topics.
   672  	//
   673  	// Examples:
   674  	// {} or nil          matches any topic list
   675  	// {{A}}              matches topic A in first position
   676  	// {{}, {B}}          matches any topic in first position, B in second position
   677  	// {{A}, {B}}         matches topic A in first position, B in second position
   678  	// {{A, B}}, {C, D}}  matches topic (A OR B) in first position, (C OR D) in second position
   679  	Topics *[][]common.Hash
   680  }
   681  
   682  // runFilter accepts a filter and executes it, returning all its results as
   683  // `Log` objects.
   684  func runFilter(ctx context.Context, be ethapi.Backend, filter *filters.Filter) ([]*Log, error) {
   685  	logs, err := filter.Logs(ctx)
   686  	if err != nil || logs == nil {
   687  		return nil, err
   688  	}
   689  	ret := make([]*Log, 0, len(logs))
   690  	for _, log := range logs {
   691  		ret = append(ret, &Log{
   692  			backend:     be,
   693  			transaction: &Transaction{backend: be, hash: log.TxHash},
   694  			log:         log,
   695  		})
   696  	}
   697  	return ret, nil
   698  }
   699  
   700  func (b *Block) Logs(ctx context.Context, args struct{ Filter BlockFilterCriteria }) ([]*Log, error) {
   701  	var addresses []common.Address
   702  	if args.Filter.Addresses != nil {
   703  		addresses = *args.Filter.Addresses
   704  	}
   705  	var topics [][]common.Hash
   706  	if args.Filter.Topics != nil {
   707  		topics = *args.Filter.Topics
   708  	}
   709  	hash := b.hash
   710  	if hash == (common.Hash{}) {
   711  		header, err := b.resolveHeader(ctx)
   712  		if err != nil {
   713  			return nil, err
   714  		}
   715  		hash = header.Hash()
   716  	}
   717  	// Construct the range filter
   718  	filter := filters.NewBlockFilter(b.backend, hash, addresses, topics)
   719  
   720  	// Run the filter and return all the logs
   721  	return runFilter(ctx, b.backend, filter)
   722  }
   723  
   724  func (b *Block) Account(ctx context.Context, args struct {
   725  	Address common.Address
   726  }) (*Account, error) {
   727  	if b.numberOrHash == nil {
   728  		_, err := b.resolveHeader(ctx)
   729  		if err != nil {
   730  			return nil, err
   731  		}
   732  	}
   733  	return &Account{
   734  		backend:       b.backend,
   735  		address:       args.Address,
   736  		blockNrOrHash: *b.numberOrHash,
   737  	}, nil
   738  }
   739  
   740  // CallData encapsulates arguments to `call` or `estimateGas`.
   741  // All arguments are optional.
   742  type CallData struct {
   743  	From     *common.Address // The Ethereum address the call is from.
   744  	To       *common.Address // The Ethereum address the call is to.
   745  	Gas      *hexutil.Uint64 // The amount of gas provided for the call.
   746  	GasPrice *hexutil.Big    // The price of each unit of gas, in wei.
   747  	Value    *hexutil.Big    // The value sent along with the call.
   748  	Data     *hexutil.Bytes  // Any data sent with the call.
   749  }
   750  
   751  // CallResult encapsulates the result of an invocation of the `call` accessor.
   752  type CallResult struct {
   753  	data    hexutil.Bytes  // The return data from the call
   754  	gasUsed hexutil.Uint64 // The amount of gas used
   755  	status  hexutil.Uint64 // The return status of the call - 0 for failure or 1 for success.
   756  }
   757  
   758  func (c *CallResult) Data() hexutil.Bytes {
   759  	return c.data
   760  }
   761  
   762  func (c *CallResult) GasUsed() hexutil.Uint64 {
   763  	return c.gasUsed
   764  }
   765  
   766  func (c *CallResult) Status() hexutil.Uint64 {
   767  	return c.status
   768  }
   769  
   770  func (b *Block) Call(ctx context.Context, args struct {
   771  	Data ethapi.CallArgs
   772  }) (*CallResult, error) {
   773  	if b.numberOrHash == nil {
   774  		_, err := b.resolve(ctx)
   775  		if err != nil {
   776  			return nil, err
   777  		}
   778  	}
   779  	result, gas, failed, err := ethapi.DoCall(ctx, b.backend, args.Data, *b.numberOrHash, nil, vm.Config{}, 5*time.Second, b.backend.RPCGasCap())
   780  	status := hexutil.Uint64(1)
   781  	if failed {
   782  		status = 0
   783  	}
   784  	return &CallResult{
   785  		data:    hexutil.Bytes(result),
   786  		gasUsed: hexutil.Uint64(gas),
   787  		status:  status,
   788  	}, err
   789  }
   790  
   791  func (b *Block) EstimateGas(ctx context.Context, args struct {
   792  	Data ethapi.CallArgs
   793  }) (hexutil.Uint64, error) {
   794  	if b.numberOrHash == nil {
   795  		_, err := b.resolveHeader(ctx)
   796  		if err != nil {
   797  			return hexutil.Uint64(0), err
   798  		}
   799  	}
   800  	gas, err := ethapi.DoEstimateGas(ctx, b.backend, args.Data, *b.numberOrHash, b.backend.RPCGasCap())
   801  	return gas, err
   802  }
   803  
   804  type Pending struct {
   805  	backend ethapi.Backend
   806  }
   807  
   808  func (p *Pending) TransactionCount(ctx context.Context) (int32, error) {
   809  	txs, err := p.backend.GetPoolTransactions()
   810  	return int32(len(txs)), err
   811  }
   812  
   813  func (p *Pending) Transactions(ctx context.Context) (*[]*Transaction, error) {
   814  	txs, err := p.backend.GetPoolTransactions()
   815  	if err != nil {
   816  		return nil, err
   817  	}
   818  	ret := make([]*Transaction, 0, len(txs))
   819  	for i, tx := range txs {
   820  		ret = append(ret, &Transaction{
   821  			backend: p.backend,
   822  			hash:    tx.Hash(),
   823  			tx:      tx,
   824  			index:   uint64(i),
   825  		})
   826  	}
   827  	return &ret, nil
   828  }
   829  
   830  func (p *Pending) Account(ctx context.Context, args struct {
   831  	Address common.Address
   832  }) *Account {
   833  	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   834  	return &Account{
   835  		backend:       p.backend,
   836  		address:       args.Address,
   837  		blockNrOrHash: pendingBlockNr,
   838  	}
   839  }
   840  
   841  func (p *Pending) Call(ctx context.Context, args struct {
   842  	Data ethapi.CallArgs
   843  }) (*CallResult, error) {
   844  	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   845  	result, gas, failed, err := ethapi.DoCall(ctx, p.backend, args.Data, pendingBlockNr, nil, vm.Config{}, 5*time.Second, p.backend.RPCGasCap())
   846  	status := hexutil.Uint64(1)
   847  	if failed {
   848  		status = 0
   849  	}
   850  	return &CallResult{
   851  		data:    hexutil.Bytes(result),
   852  		gasUsed: hexutil.Uint64(gas),
   853  		status:  status,
   854  	}, err
   855  }
   856  
   857  func (p *Pending) EstimateGas(ctx context.Context, args struct {
   858  	Data ethapi.CallArgs
   859  }) (hexutil.Uint64, error) {
   860  	pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   861  	return ethapi.DoEstimateGas(ctx, p.backend, args.Data, pendingBlockNr, p.backend.RPCGasCap())
   862  }
   863  
   864  // Resolver is the top-level object in the GraphQL hierarchy.
   865  type Resolver struct {
   866  	backend ethapi.Backend
   867  }
   868  
   869  func (r *Resolver) Block(ctx context.Context, args struct {
   870  	Number *hexutil.Uint64
   871  	Hash   *common.Hash
   872  }) (*Block, error) {
   873  	var block *Block
   874  	if args.Number != nil {
   875  		number := rpc.BlockNumber(uint64(*args.Number))
   876  		numberOrHash := rpc.BlockNumberOrHashWithNumber(number)
   877  		block = &Block{
   878  			backend:      r.backend,
   879  			numberOrHash: &numberOrHash,
   880  		}
   881  	} else if args.Hash != nil {
   882  		numberOrHash := rpc.BlockNumberOrHashWithHash(*args.Hash, false)
   883  		block = &Block{
   884  			backend:      r.backend,
   885  			numberOrHash: &numberOrHash,
   886  		}
   887  	} else {
   888  		numberOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
   889  		block = &Block{
   890  			backend:      r.backend,
   891  			numberOrHash: &numberOrHash,
   892  		}
   893  	}
   894  	// Resolve the header, return nil if it doesn't exist.
   895  	// Note we don't resolve block directly here since it will require an
   896  	// additional network request for light client.
   897  	h, err := block.resolveHeader(ctx)
   898  	if err != nil {
   899  		return nil, err
   900  	} else if h == nil {
   901  		return nil, nil
   902  	}
   903  	return block, nil
   904  }
   905  
   906  func (r *Resolver) Blocks(ctx context.Context, args struct {
   907  	From hexutil.Uint64
   908  	To   *hexutil.Uint64
   909  }) ([]*Block, error) {
   910  	from := rpc.BlockNumber(args.From)
   911  
   912  	var to rpc.BlockNumber
   913  	if args.To != nil {
   914  		to = rpc.BlockNumber(*args.To)
   915  	} else {
   916  		to = rpc.BlockNumber(r.backend.CurrentBlock().Number().Int64())
   917  	}
   918  	if to < from {
   919  		return []*Block{}, nil
   920  	}
   921  	ret := make([]*Block, 0, to-from+1)
   922  	for i := from; i <= to; i++ {
   923  		numberOrHash := rpc.BlockNumberOrHashWithNumber(i)
   924  		ret = append(ret, &Block{
   925  			backend:      r.backend,
   926  			numberOrHash: &numberOrHash,
   927  		})
   928  	}
   929  	return ret, nil
   930  }
   931  
   932  func (r *Resolver) Pending(ctx context.Context) *Pending {
   933  	return &Pending{r.backend}
   934  }
   935  
   936  func (r *Resolver) Transaction(ctx context.Context, args struct{ Hash common.Hash }) (*Transaction, error) {
   937  	tx := &Transaction{
   938  		backend: r.backend,
   939  		hash:    args.Hash,
   940  	}
   941  	// Resolve the transaction; if it doesn't exist, return nil.
   942  	t, err := tx.resolve(ctx)
   943  	if err != nil {
   944  		return nil, err
   945  	} else if t == nil {
   946  		return nil, nil
   947  	}
   948  	return tx, nil
   949  }
   950  
   951  func (r *Resolver) SendRawTransaction(ctx context.Context, args struct{ Data hexutil.Bytes }) (common.Hash, error) {
   952  	tx := new(types.Transaction)
   953  	if err := rlp.DecodeBytes(args.Data, tx); err != nil {
   954  		return common.Hash{}, err
   955  	}
   956  	hash, err := ethapi.SubmitTransaction(ctx, r.backend, tx)
   957  	return hash, err
   958  }
   959  
   960  // FilterCriteria encapsulates the arguments to `logs` on the root resolver object.
   961  type FilterCriteria struct {
   962  	FromBlock *hexutil.Uint64   // beginning of the queried range, nil means genesis block
   963  	ToBlock   *hexutil.Uint64   // end of the range, nil means latest block
   964  	Addresses *[]common.Address // restricts matches to events created by specific contracts
   965  
   966  	// The Topic list restricts matches to particular event topics. Each event has a list
   967  	// of topics. Topics matches a prefix of that list. An empty element slice matches any
   968  	// topic. Non-empty elements represent an alternative that matches any of the
   969  	// contained topics.
   970  	//
   971  	// Examples:
   972  	// {} or nil          matches any topic list
   973  	// {{A}}              matches topic A in first position
   974  	// {{}, {B}}          matches any topic in first position, B in second position
   975  	// {{A}, {B}}         matches topic A in first position, B in second position
   976  	// {{A, B}}, {C, D}}  matches topic (A OR B) in first position, (C OR D) in second position
   977  	Topics *[][]common.Hash
   978  }
   979  
   980  func (r *Resolver) Logs(ctx context.Context, args struct{ Filter FilterCriteria }) ([]*Log, error) {
   981  	// Convert the RPC block numbers into internal representations
   982  	begin := rpc.LatestBlockNumber.Int64()
   983  	if args.Filter.FromBlock != nil {
   984  		begin = int64(*args.Filter.FromBlock)
   985  	}
   986  	end := rpc.LatestBlockNumber.Int64()
   987  	if args.Filter.ToBlock != nil {
   988  		end = int64(*args.Filter.ToBlock)
   989  	}
   990  	var addresses []common.Address
   991  	if args.Filter.Addresses != nil {
   992  		addresses = *args.Filter.Addresses
   993  	}
   994  	var topics [][]common.Hash
   995  	if args.Filter.Topics != nil {
   996  		topics = *args.Filter.Topics
   997  	}
   998  	// Construct the range filter
   999  	filter := filters.NewRangeFilter(filters.Backend(r.backend), begin, end, addresses, topics)
  1000  	return runFilter(ctx, r.backend, filter)
  1001  }
  1002  
  1003  func (r *Resolver) GasPrice(ctx context.Context) (hexutil.Big, error) {
  1004  	price, err := r.backend.SuggestPrice(ctx)
  1005  	return hexutil.Big(*price), err
  1006  }
  1007  
  1008  func (r *Resolver) ProtocolVersion(ctx context.Context) (int32, error) {
  1009  	return int32(r.backend.ProtocolVersion()), nil
  1010  }
  1011  
  1012  // SyncState represents the synchronisation status returned from the `syncing` accessor.
  1013  type SyncState struct {
  1014  	progress ethereum.SyncProgress
  1015  }
  1016  
  1017  func (s *SyncState) StartingBlock() hexutil.Uint64 {
  1018  	return hexutil.Uint64(s.progress.StartingBlock)
  1019  }
  1020  
  1021  func (s *SyncState) CurrentBlock() hexutil.Uint64 {
  1022  	return hexutil.Uint64(s.progress.CurrentBlock)
  1023  }
  1024  
  1025  func (s *SyncState) HighestBlock() hexutil.Uint64 {
  1026  	return hexutil.Uint64(s.progress.HighestBlock)
  1027  }
  1028  
  1029  func (s *SyncState) PulledStates() *hexutil.Uint64 {
  1030  	ret := hexutil.Uint64(s.progress.PulledStates)
  1031  	return &ret
  1032  }
  1033  
  1034  func (s *SyncState) KnownStates() *hexutil.Uint64 {
  1035  	ret := hexutil.Uint64(s.progress.KnownStates)
  1036  	return &ret
  1037  }
  1038  
  1039  // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  1040  // yet received the latest block headers from its pears. In case it is synchronizing:
  1041  // - startingBlock: block number this node started to synchronise from
  1042  // - currentBlock:  block number this node is currently importing
  1043  // - highestBlock:  block number of the highest block header this node has received from peers
  1044  // - pulledStates:  number of state entries processed until now
  1045  // - knownStates:   number of known state entries that still need to be pulled
  1046  func (r *Resolver) Syncing() (*SyncState, error) {
  1047  	progress := r.backend.Downloader().Progress()
  1048  
  1049  	// Return not syncing if the synchronisation already completed
  1050  	if progress.CurrentBlock >= progress.HighestBlock {
  1051  		return nil, nil
  1052  	}
  1053  	// Otherwise gather the block sync stats
  1054  	return &SyncState{progress}, nil
  1055  }