github.com/jimmyx0x/go-ethereum@v1.10.28/eth/api_backend.go (about)

     1  // Copyright 2015 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 eth
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"math/big"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum"
    26  	"github.com/ethereum/go-ethereum/accounts"
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/consensus"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/bloombits"
    31  	"github.com/ethereum/go-ethereum/core/rawdb"
    32  	"github.com/ethereum/go-ethereum/core/state"
    33  	"github.com/ethereum/go-ethereum/core/txpool"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/core/vm"
    36  	"github.com/ethereum/go-ethereum/eth/gasprice"
    37  	"github.com/ethereum/go-ethereum/eth/tracers"
    38  	"github.com/ethereum/go-ethereum/ethdb"
    39  	"github.com/ethereum/go-ethereum/event"
    40  	"github.com/ethereum/go-ethereum/miner"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/rpc"
    43  )
    44  
    45  // EthAPIBackend implements ethapi.Backend for full nodes
    46  type EthAPIBackend struct {
    47  	extRPCEnabled       bool
    48  	allowUnprotectedTxs bool
    49  	eth                 *Ethereum
    50  	gpo                 *gasprice.Oracle
    51  }
    52  
    53  // ChainConfig returns the active chain configuration.
    54  func (b *EthAPIBackend) ChainConfig() *params.ChainConfig {
    55  	return b.eth.blockchain.Config()
    56  }
    57  
    58  func (b *EthAPIBackend) CurrentBlock() *types.Block {
    59  	return b.eth.blockchain.CurrentBlock()
    60  }
    61  
    62  func (b *EthAPIBackend) SetHead(number uint64) {
    63  	b.eth.handler.downloader.Cancel()
    64  	b.eth.blockchain.SetHead(number)
    65  }
    66  
    67  func (b *EthAPIBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
    68  	// Pending block is only known by the miner
    69  	if number == rpc.PendingBlockNumber {
    70  		block := b.eth.miner.PendingBlock()
    71  		return block.Header(), nil
    72  	}
    73  	// Otherwise resolve and return the block
    74  	if number == rpc.LatestBlockNumber {
    75  		return b.eth.blockchain.CurrentBlock().Header(), nil
    76  	}
    77  	if number == rpc.FinalizedBlockNumber {
    78  		block := b.eth.blockchain.CurrentFinalizedBlock()
    79  		if block != nil {
    80  			return block.Header(), nil
    81  		}
    82  		return nil, errors.New("finalized block not found")
    83  	}
    84  	if number == rpc.SafeBlockNumber {
    85  		block := b.eth.blockchain.CurrentSafeBlock()
    86  		if block != nil {
    87  			return block.Header(), nil
    88  		}
    89  		return nil, errors.New("safe block not found")
    90  	}
    91  	return b.eth.blockchain.GetHeaderByNumber(uint64(number)), nil
    92  }
    93  
    94  func (b *EthAPIBackend) HeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Header, error) {
    95  	if blockNr, ok := blockNrOrHash.Number(); ok {
    96  		return b.HeaderByNumber(ctx, blockNr)
    97  	}
    98  	if hash, ok := blockNrOrHash.Hash(); ok {
    99  		header := b.eth.blockchain.GetHeaderByHash(hash)
   100  		if header == nil {
   101  			return nil, errors.New("header for hash not found")
   102  		}
   103  		if blockNrOrHash.RequireCanonical && b.eth.blockchain.GetCanonicalHash(header.Number.Uint64()) != hash {
   104  			return nil, errors.New("hash is not currently canonical")
   105  		}
   106  		return header, nil
   107  	}
   108  	return nil, errors.New("invalid arguments; neither block nor hash specified")
   109  }
   110  
   111  func (b *EthAPIBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   112  	return b.eth.blockchain.GetHeaderByHash(hash), nil
   113  }
   114  
   115  func (b *EthAPIBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
   116  	// Pending block is only known by the miner
   117  	if number == rpc.PendingBlockNumber {
   118  		block := b.eth.miner.PendingBlock()
   119  		return block, nil
   120  	}
   121  	// Otherwise resolve and return the block
   122  	if number == rpc.LatestBlockNumber {
   123  		return b.eth.blockchain.CurrentBlock(), nil
   124  	}
   125  	if number == rpc.FinalizedBlockNumber {
   126  		return b.eth.blockchain.CurrentFinalizedBlock(), nil
   127  	}
   128  	if number == rpc.SafeBlockNumber {
   129  		return b.eth.blockchain.CurrentSafeBlock(), nil
   130  	}
   131  	return b.eth.blockchain.GetBlockByNumber(uint64(number)), nil
   132  }
   133  
   134  func (b *EthAPIBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   135  	return b.eth.blockchain.GetBlockByHash(hash), nil
   136  }
   137  
   138  func (b *EthAPIBackend) BlockByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Block, error) {
   139  	if blockNr, ok := blockNrOrHash.Number(); ok {
   140  		return b.BlockByNumber(ctx, blockNr)
   141  	}
   142  	if hash, ok := blockNrOrHash.Hash(); ok {
   143  		header := b.eth.blockchain.GetHeaderByHash(hash)
   144  		if header == nil {
   145  			return nil, errors.New("header for hash not found")
   146  		}
   147  		if blockNrOrHash.RequireCanonical && b.eth.blockchain.GetCanonicalHash(header.Number.Uint64()) != hash {
   148  			return nil, errors.New("hash is not currently canonical")
   149  		}
   150  		block := b.eth.blockchain.GetBlock(hash, header.Number.Uint64())
   151  		if block == nil {
   152  			return nil, errors.New("header found, but block body is missing")
   153  		}
   154  		return block, nil
   155  	}
   156  	return nil, errors.New("invalid arguments; neither block nor hash specified")
   157  }
   158  
   159  func (b *EthAPIBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   160  	return b.eth.miner.PendingBlockAndReceipts()
   161  }
   162  
   163  func (b *EthAPIBackend) StateAndHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*state.StateDB, *types.Header, error) {
   164  	// Pending state is only known by the miner
   165  	if number == rpc.PendingBlockNumber {
   166  		block, state := b.eth.miner.Pending()
   167  		return state, block.Header(), nil
   168  	}
   169  	// Otherwise resolve the block number and return its state
   170  	header, err := b.HeaderByNumber(ctx, number)
   171  	if err != nil {
   172  		return nil, nil, err
   173  	}
   174  	if header == nil {
   175  		return nil, nil, errors.New("header not found")
   176  	}
   177  	stateDb, err := b.eth.BlockChain().StateAt(header.Root)
   178  	return stateDb, header, err
   179  }
   180  
   181  func (b *EthAPIBackend) StateAndHeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*state.StateDB, *types.Header, error) {
   182  	if blockNr, ok := blockNrOrHash.Number(); ok {
   183  		return b.StateAndHeaderByNumber(ctx, blockNr)
   184  	}
   185  	if hash, ok := blockNrOrHash.Hash(); ok {
   186  		header, err := b.HeaderByHash(ctx, hash)
   187  		if err != nil {
   188  			return nil, nil, err
   189  		}
   190  		if header == nil {
   191  			return nil, nil, errors.New("header for hash not found")
   192  		}
   193  		if blockNrOrHash.RequireCanonical && b.eth.blockchain.GetCanonicalHash(header.Number.Uint64()) != hash {
   194  			return nil, nil, errors.New("hash is not currently canonical")
   195  		}
   196  		stateDb, err := b.eth.BlockChain().StateAt(header.Root)
   197  		return stateDb, header, err
   198  	}
   199  	return nil, nil, errors.New("invalid arguments; neither block nor hash specified")
   200  }
   201  
   202  func (b *EthAPIBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   203  	return b.eth.blockchain.GetReceiptsByHash(hash), nil
   204  }
   205  
   206  func (b *EthAPIBackend) GetLogs(ctx context.Context, hash common.Hash, number uint64) ([][]*types.Log, error) {
   207  	return rawdb.ReadLogs(b.eth.chainDb, hash, number, b.ChainConfig()), nil
   208  }
   209  
   210  func (b *EthAPIBackend) GetTd(ctx context.Context, hash common.Hash) *big.Int {
   211  	if header := b.eth.blockchain.GetHeaderByHash(hash); header != nil {
   212  		return b.eth.blockchain.GetTd(hash, header.Number.Uint64())
   213  	}
   214  	return nil
   215  }
   216  
   217  func (b *EthAPIBackend) GetEVM(ctx context.Context, msg core.Message, state *state.StateDB, header *types.Header, vmConfig *vm.Config) (*vm.EVM, func() error, error) {
   218  	if vmConfig == nil {
   219  		vmConfig = b.eth.blockchain.GetVMConfig()
   220  	}
   221  	txContext := core.NewEVMTxContext(msg)
   222  	context := core.NewEVMBlockContext(header, b.eth.BlockChain(), nil)
   223  	return vm.NewEVM(context, txContext, state, b.eth.blockchain.Config(), *vmConfig), state.Error, nil
   224  }
   225  
   226  func (b *EthAPIBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   227  	return b.eth.BlockChain().SubscribeRemovedLogsEvent(ch)
   228  }
   229  
   230  func (b *EthAPIBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
   231  	return b.eth.miner.SubscribePendingLogs(ch)
   232  }
   233  
   234  func (b *EthAPIBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   235  	return b.eth.BlockChain().SubscribeChainEvent(ch)
   236  }
   237  
   238  func (b *EthAPIBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   239  	return b.eth.BlockChain().SubscribeChainHeadEvent(ch)
   240  }
   241  
   242  func (b *EthAPIBackend) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
   243  	return b.eth.BlockChain().SubscribeChainSideEvent(ch)
   244  }
   245  
   246  func (b *EthAPIBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   247  	return b.eth.BlockChain().SubscribeLogsEvent(ch)
   248  }
   249  
   250  func (b *EthAPIBackend) SendTx(ctx context.Context, signedTx *types.Transaction) error {
   251  	return b.eth.txPool.AddLocal(signedTx)
   252  }
   253  
   254  func (b *EthAPIBackend) GetPoolTransactions() (types.Transactions, error) {
   255  	pending := b.eth.txPool.Pending(false)
   256  	var txs types.Transactions
   257  	for _, batch := range pending {
   258  		txs = append(txs, batch...)
   259  	}
   260  	return txs, nil
   261  }
   262  
   263  func (b *EthAPIBackend) GetPoolTransaction(hash common.Hash) *types.Transaction {
   264  	return b.eth.txPool.Get(hash)
   265  }
   266  
   267  func (b *EthAPIBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
   268  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(b.eth.ChainDb(), txHash)
   269  	return tx, blockHash, blockNumber, index, nil
   270  }
   271  
   272  func (b *EthAPIBackend) GetPoolNonce(ctx context.Context, addr common.Address) (uint64, error) {
   273  	return b.eth.txPool.Nonce(addr), nil
   274  }
   275  
   276  func (b *EthAPIBackend) Stats() (pending int, queued int) {
   277  	return b.eth.txPool.Stats()
   278  }
   279  
   280  func (b *EthAPIBackend) TxPoolContent() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
   281  	return b.eth.TxPool().Content()
   282  }
   283  
   284  func (b *EthAPIBackend) TxPoolContentFrom(addr common.Address) (types.Transactions, types.Transactions) {
   285  	return b.eth.TxPool().ContentFrom(addr)
   286  }
   287  
   288  func (b *EthAPIBackend) TxPool() *txpool.TxPool {
   289  	return b.eth.TxPool()
   290  }
   291  
   292  func (b *EthAPIBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   293  	return b.eth.TxPool().SubscribeNewTxsEvent(ch)
   294  }
   295  
   296  func (b *EthAPIBackend) SyncProgress() ethereum.SyncProgress {
   297  	return b.eth.Downloader().Progress()
   298  }
   299  
   300  func (b *EthAPIBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
   301  	return b.gpo.SuggestTipCap(ctx)
   302  }
   303  
   304  func (b *EthAPIBackend) FeeHistory(ctx context.Context, blockCount int, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (firstBlock *big.Int, reward [][]*big.Int, baseFee []*big.Int, gasUsedRatio []float64, err error) {
   305  	return b.gpo.FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles)
   306  }
   307  
   308  func (b *EthAPIBackend) ChainDb() ethdb.Database {
   309  	return b.eth.ChainDb()
   310  }
   311  
   312  func (b *EthAPIBackend) EventMux() *event.TypeMux {
   313  	return b.eth.EventMux()
   314  }
   315  
   316  func (b *EthAPIBackend) AccountManager() *accounts.Manager {
   317  	return b.eth.AccountManager()
   318  }
   319  
   320  func (b *EthAPIBackend) ExtRPCEnabled() bool {
   321  	return b.extRPCEnabled
   322  }
   323  
   324  func (b *EthAPIBackend) UnprotectedAllowed() bool {
   325  	return b.allowUnprotectedTxs
   326  }
   327  
   328  func (b *EthAPIBackend) RPCGasCap() uint64 {
   329  	return b.eth.config.RPCGasCap
   330  }
   331  
   332  func (b *EthAPIBackend) RPCEVMTimeout() time.Duration {
   333  	return b.eth.config.RPCEVMTimeout
   334  }
   335  
   336  func (b *EthAPIBackend) RPCTxFeeCap() float64 {
   337  	return b.eth.config.RPCTxFeeCap
   338  }
   339  
   340  func (b *EthAPIBackend) BloomStatus() (uint64, uint64) {
   341  	sections, _, _ := b.eth.bloomIndexer.Sections()
   342  	return params.BloomBitsBlocks, sections
   343  }
   344  
   345  func (b *EthAPIBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) {
   346  	for i := 0; i < bloomFilterThreads; i++ {
   347  		go session.Multiplex(bloomRetrievalBatch, bloomRetrievalWait, b.eth.bloomRequests)
   348  	}
   349  }
   350  
   351  func (b *EthAPIBackend) Engine() consensus.Engine {
   352  	return b.eth.engine
   353  }
   354  
   355  func (b *EthAPIBackend) CurrentHeader() *types.Header {
   356  	return b.eth.blockchain.CurrentHeader()
   357  }
   358  
   359  func (b *EthAPIBackend) Miner() *miner.Miner {
   360  	return b.eth.Miner()
   361  }
   362  
   363  func (b *EthAPIBackend) StartMining(threads int) error {
   364  	return b.eth.StartMining(threads)
   365  }
   366  
   367  func (b *EthAPIBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, readOnly bool, preferDisk bool) (*state.StateDB, tracers.StateReleaseFunc, error) {
   368  	return b.eth.StateAtBlock(ctx, block, reexec, base, readOnly, preferDisk)
   369  }
   370  
   371  func (b *EthAPIBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, tracers.StateReleaseFunc, error) {
   372  	return b.eth.stateAtTransaction(ctx, block, txIndex, reexec)
   373  }