github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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/tacshi/go-ethereum"
    26  	"github.com/tacshi/go-ethereum/accounts"
    27  	"github.com/tacshi/go-ethereum/common"
    28  	"github.com/tacshi/go-ethereum/consensus"
    29  	"github.com/tacshi/go-ethereum/core"
    30  	"github.com/tacshi/go-ethereum/core/bloombits"
    31  	"github.com/tacshi/go-ethereum/core/rawdb"
    32  	"github.com/tacshi/go-ethereum/core/state"
    33  	"github.com/tacshi/go-ethereum/core/txpool"
    34  	"github.com/tacshi/go-ethereum/core/types"
    35  	"github.com/tacshi/go-ethereum/core/vm"
    36  	"github.com/tacshi/go-ethereum/eth/gasprice"
    37  	"github.com/tacshi/go-ethereum/eth/tracers"
    38  	"github.com/tacshi/go-ethereum/ethdb"
    39  	"github.com/tacshi/go-ethereum/event"
    40  	"github.com/tacshi/go-ethereum/miner"
    41  	"github.com/tacshi/go-ethereum/params"
    42  	"github.com/tacshi/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.Header {
    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(), nil
    76  	}
    77  	if number == rpc.FinalizedBlockNumber {
    78  		block := b.eth.blockchain.CurrentFinalBlock()
    79  		if block != nil {
    80  			return block, 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, 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  		header := b.eth.blockchain.CurrentBlock()
   124  		return b.eth.blockchain.GetBlock(header.Hash(), header.Number.Uint64()), nil
   125  	}
   126  	if number == rpc.FinalizedBlockNumber {
   127  		header := b.eth.blockchain.CurrentFinalBlock()
   128  		return b.eth.blockchain.GetBlock(header.Hash(), header.Number.Uint64()), nil
   129  	}
   130  	if number == rpc.SafeBlockNumber {
   131  		header := b.eth.blockchain.CurrentSafeBlock()
   132  		return b.eth.blockchain.GetBlock(header.Hash(), header.Number.Uint64()), nil
   133  	}
   134  	return b.eth.blockchain.GetBlockByNumber(uint64(number)), nil
   135  }
   136  
   137  func (b *EthAPIBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   138  	return b.eth.blockchain.GetBlockByHash(hash), nil
   139  }
   140  
   141  // GetBody returns body of a block. It does not resolve special block numbers.
   142  func (b *EthAPIBackend) GetBody(ctx context.Context, hash common.Hash, number rpc.BlockNumber) (*types.Body, error) {
   143  	if number < 0 || hash == (common.Hash{}) {
   144  		return nil, errors.New("invalid arguments; expect hash and no special block numbers")
   145  	}
   146  	if body := b.eth.blockchain.GetBody(hash); body != nil {
   147  		return body, nil
   148  	}
   149  	return nil, errors.New("block body not found")
   150  }
   151  
   152  func (b *EthAPIBackend) BlockByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Block, error) {
   153  	if blockNr, ok := blockNrOrHash.Number(); ok {
   154  		return b.BlockByNumber(ctx, blockNr)
   155  	}
   156  	if hash, ok := blockNrOrHash.Hash(); ok {
   157  		header := b.eth.blockchain.GetHeaderByHash(hash)
   158  		if header == nil {
   159  			return nil, errors.New("header for hash not found")
   160  		}
   161  		if blockNrOrHash.RequireCanonical && b.eth.blockchain.GetCanonicalHash(header.Number.Uint64()) != hash {
   162  			return nil, errors.New("hash is not currently canonical")
   163  		}
   164  		block := b.eth.blockchain.GetBlock(hash, header.Number.Uint64())
   165  		if block == nil {
   166  			return nil, errors.New("header found, but block body is missing")
   167  		}
   168  		return block, nil
   169  	}
   170  	return nil, errors.New("invalid arguments; neither block nor hash specified")
   171  }
   172  
   173  func (b *EthAPIBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   174  	return b.eth.miner.PendingBlockAndReceipts()
   175  }
   176  
   177  func (b *EthAPIBackend) StateAndHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*state.StateDB, *types.Header, error) {
   178  	// Pending state is only known by the miner
   179  	if number == rpc.PendingBlockNumber {
   180  		block, state := b.eth.miner.Pending()
   181  		return state, block.Header(), nil
   182  	}
   183  	// Otherwise resolve the block number and return its state
   184  	header, err := b.HeaderByNumber(ctx, number)
   185  	if err != nil {
   186  		return nil, nil, err
   187  	}
   188  	if header == nil {
   189  		return nil, nil, errors.New("header not found")
   190  	}
   191  	stateDb, err := b.eth.BlockChain().StateAt(header.Root)
   192  	return stateDb, header, err
   193  }
   194  
   195  func (b *EthAPIBackend) StateAndHeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*state.StateDB, *types.Header, error) {
   196  	if blockNr, ok := blockNrOrHash.Number(); ok {
   197  		return b.StateAndHeaderByNumber(ctx, blockNr)
   198  	}
   199  	if hash, ok := blockNrOrHash.Hash(); ok {
   200  		header, err := b.HeaderByHash(ctx, hash)
   201  		if err != nil {
   202  			return nil, nil, err
   203  		}
   204  		if header == nil {
   205  			return nil, nil, errors.New("header for hash not found")
   206  		}
   207  		if blockNrOrHash.RequireCanonical && b.eth.blockchain.GetCanonicalHash(header.Number.Uint64()) != hash {
   208  			return nil, nil, errors.New("hash is not currently canonical")
   209  		}
   210  		stateDb, err := b.eth.BlockChain().StateAt(header.Root)
   211  		return stateDb, header, err
   212  	}
   213  	return nil, nil, errors.New("invalid arguments; neither block nor hash specified")
   214  }
   215  
   216  func (b *EthAPIBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   217  	return b.eth.blockchain.GetReceiptsByHash(hash), nil
   218  }
   219  
   220  func (b *EthAPIBackend) GetLogs(ctx context.Context, hash common.Hash, number uint64) ([][]*types.Log, error) {
   221  	return rawdb.ReadLogs(b.eth.chainDb, hash, number, b.ChainConfig()), nil
   222  }
   223  
   224  func (b *EthAPIBackend) GetTd(ctx context.Context, hash common.Hash) *big.Int {
   225  	if header := b.eth.blockchain.GetHeaderByHash(hash); header != nil {
   226  		return b.eth.blockchain.GetTd(hash, header.Number.Uint64())
   227  	}
   228  	return nil
   229  }
   230  
   231  func (b *EthAPIBackend) GetEVM(ctx context.Context, msg *core.Message, state *state.StateDB, header *types.Header, vmConfig *vm.Config) (*vm.EVM, func() error, error) {
   232  	if vmConfig == nil {
   233  		vmConfig = b.eth.blockchain.GetVMConfig()
   234  	}
   235  	txContext := core.NewEVMTxContext(msg)
   236  	context := core.NewEVMBlockContext(header, b.eth.BlockChain(), nil)
   237  	return vm.NewEVM(context, txContext, state, b.eth.blockchain.Config(), *vmConfig), state.Error, nil
   238  }
   239  
   240  func (b *EthAPIBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   241  	return b.eth.BlockChain().SubscribeRemovedLogsEvent(ch)
   242  }
   243  
   244  func (b *EthAPIBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
   245  	return b.eth.miner.SubscribePendingLogs(ch)
   246  }
   247  
   248  func (b *EthAPIBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   249  	return b.eth.BlockChain().SubscribeChainEvent(ch)
   250  }
   251  
   252  func (b *EthAPIBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   253  	return b.eth.BlockChain().SubscribeChainHeadEvent(ch)
   254  }
   255  
   256  func (b *EthAPIBackend) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
   257  	return b.eth.BlockChain().SubscribeChainSideEvent(ch)
   258  }
   259  
   260  func (b *EthAPIBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   261  	return b.eth.BlockChain().SubscribeLogsEvent(ch)
   262  }
   263  
   264  func (b *EthAPIBackend) SendTx(ctx context.Context, signedTx *types.Transaction) error {
   265  	return b.eth.txPool.AddLocal(signedTx)
   266  }
   267  
   268  func (b *EthAPIBackend) GetPoolTransactions() (types.Transactions, error) {
   269  	pending := b.eth.txPool.Pending(false)
   270  	var txs types.Transactions
   271  	for _, batch := range pending {
   272  		txs = append(txs, batch...)
   273  	}
   274  	return txs, nil
   275  }
   276  
   277  func (b *EthAPIBackend) GetPoolTransaction(hash common.Hash) *types.Transaction {
   278  	return b.eth.txPool.Get(hash)
   279  }
   280  
   281  func (b *EthAPIBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
   282  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(b.eth.ChainDb(), txHash)
   283  	return tx, blockHash, blockNumber, index, nil
   284  }
   285  
   286  func (b *EthAPIBackend) GetPoolNonce(ctx context.Context, addr common.Address) (uint64, error) {
   287  	return b.eth.txPool.Nonce(addr), nil
   288  }
   289  
   290  func (b *EthAPIBackend) Stats() (pending int, queued int) {
   291  	return b.eth.txPool.Stats()
   292  }
   293  
   294  func (b *EthAPIBackend) TxPoolContent() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
   295  	return b.eth.TxPool().Content()
   296  }
   297  
   298  func (b *EthAPIBackend) TxPoolContentFrom(addr common.Address) (types.Transactions, types.Transactions) {
   299  	return b.eth.TxPool().ContentFrom(addr)
   300  }
   301  
   302  func (b *EthAPIBackend) TxPool() *txpool.TxPool {
   303  	return b.eth.TxPool()
   304  }
   305  
   306  func (b *EthAPIBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   307  	return b.eth.TxPool().SubscribeNewTxsEvent(ch)
   308  }
   309  
   310  func (b *EthAPIBackend) SyncProgressMap() map[string]interface{} {
   311  	progress := b.eth.Downloader().Progress()
   312  	return progress.ToMap()
   313  }
   314  
   315  func (b *EthAPIBackend) SyncProgress() ethereum.SyncProgress {
   316  	return b.eth.Downloader().Progress()
   317  }
   318  
   319  func (b *EthAPIBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
   320  	return b.gpo.SuggestTipCap(ctx)
   321  }
   322  
   323  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) {
   324  	return b.gpo.FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles)
   325  }
   326  
   327  func (b *EthAPIBackend) ChainDb() ethdb.Database {
   328  	return b.eth.ChainDb()
   329  }
   330  
   331  func (b *EthAPIBackend) EventMux() *event.TypeMux {
   332  	return b.eth.EventMux()
   333  }
   334  
   335  func (b *EthAPIBackend) AccountManager() *accounts.Manager {
   336  	return b.eth.AccountManager()
   337  }
   338  
   339  func (b *EthAPIBackend) ExtRPCEnabled() bool {
   340  	return b.extRPCEnabled
   341  }
   342  
   343  func (b *EthAPIBackend) UnprotectedAllowed() bool {
   344  	return b.allowUnprotectedTxs
   345  }
   346  
   347  func (b *EthAPIBackend) RPCGasCap() uint64 {
   348  	return b.eth.config.RPCGasCap
   349  }
   350  
   351  func (b *EthAPIBackend) RPCEVMTimeout() time.Duration {
   352  	return b.eth.config.RPCEVMTimeout
   353  }
   354  
   355  func (b *EthAPIBackend) RPCTxFeeCap() float64 {
   356  	return b.eth.config.RPCTxFeeCap
   357  }
   358  
   359  func (b *EthAPIBackend) BloomStatus() (uint64, uint64) {
   360  	sections, _, _ := b.eth.bloomIndexer.Sections()
   361  	return params.BloomBitsBlocks, sections
   362  }
   363  
   364  func (b *EthAPIBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) {
   365  	for i := 0; i < bloomFilterThreads; i++ {
   366  		go session.Multiplex(bloomRetrievalBatch, bloomRetrievalWait, b.eth.bloomRequests)
   367  	}
   368  }
   369  
   370  func (b *EthAPIBackend) Engine() consensus.Engine {
   371  	return b.eth.engine
   372  }
   373  
   374  func (b *EthAPIBackend) CurrentHeader() *types.Header {
   375  	return b.eth.blockchain.CurrentHeader()
   376  }
   377  
   378  func (b *EthAPIBackend) Miner() *miner.Miner {
   379  	return b.eth.Miner()
   380  }
   381  
   382  func (b *EthAPIBackend) StartMining(threads int) error {
   383  	return b.eth.StartMining(threads)
   384  }
   385  
   386  func (b *EthAPIBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, readOnly bool, preferDisk bool) (*state.StateDB, tracers.StateReleaseFunc, error) {
   387  	return b.eth.StateAtBlock(ctx, block, reexec, base, readOnly, preferDisk)
   388  }
   389  
   390  func (b *EthAPIBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (*core.Message, vm.BlockContext, *state.StateDB, tracers.StateReleaseFunc, error) {
   391  	return b.eth.stateAtTransaction(ctx, block, txIndex, reexec)
   392  }
   393  
   394  func (b *EthAPIBackend) FallbackClient() types.FallbackClient {
   395  	return nil
   396  }