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