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