github.com/alex403s/heco-chain@v1.2.3-0.20220611014610-f10f4107d8b9/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/types"
    34  	"github.com/ethereum/go-ethereum/core/vm"
    35  	"github.com/ethereum/go-ethereum/eth/gasprice"
    36  	"github.com/ethereum/go-ethereum/ethdb"
    37  	"github.com/ethereum/go-ethereum/event"
    38  	"github.com/ethereum/go-ethereum/miner"
    39  	"github.com/ethereum/go-ethereum/params"
    40  	"github.com/ethereum/go-ethereum/rpc"
    41  )
    42  
    43  // EthAPIBackend implements ethapi.Backend for full nodes
    44  type EthAPIBackend struct {
    45  	extRPCEnabled       bool
    46  	allowUnprotectedTxs bool
    47  	eth                 *Ethereum
    48  	gpo                 *gasprice.Oracle
    49  	gpp                 *gasprice.Prediction
    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, errors.New("failed to get block number from hash")
   190  	}
   191  	logs := rawdb.ReadLogs(db, hash, *number, b.eth.blockchain.Config())
   192  	if logs == nil {
   193  		return nil, errors.New("failed to get logs for block")
   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  	if b.eth.isPoSA {
   213  		// make sure to use parent state to avoid mix up inner cache
   214  		parent := b.eth.blockchain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
   215  		if parent == nil {
   216  			return nil, vmError, errors.New("parent not exist")
   217  		}
   218  		parentState, err := b.eth.blockchain.StateAt(parent.Root)
   219  		if err != nil {
   220  			return nil, vmError, err
   221  		}
   222  		context.ExtraValidator = b.eth.posa.CreateEvmExtraValidator(header, parentState)
   223  	}
   224  	return vm.NewEVM(context, txContext, state, b.eth.blockchain.Config(), *vmConfig), vmError, nil
   225  }
   226  
   227  func (b *EthAPIBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   228  	return b.eth.BlockChain().SubscribeRemovedLogsEvent(ch)
   229  }
   230  
   231  func (b *EthAPIBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
   232  	return b.eth.miner.SubscribePendingLogs(ch)
   233  }
   234  
   235  func (b *EthAPIBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   236  	return b.eth.BlockChain().SubscribeChainEvent(ch)
   237  }
   238  
   239  func (b *EthAPIBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   240  	return b.eth.BlockChain().SubscribeChainHeadEvent(ch)
   241  }
   242  
   243  func (b *EthAPIBackend) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
   244  	return b.eth.BlockChain().SubscribeChainSideEvent(ch)
   245  }
   246  
   247  func (b *EthAPIBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   248  	return b.eth.BlockChain().SubscribeLogsEvent(ch)
   249  }
   250  
   251  func (b *EthAPIBackend) SendTx(ctx context.Context, signedTx *types.Transaction) error {
   252  	return b.eth.txPool.AddLocal(signedTx)
   253  }
   254  
   255  func (b *EthAPIBackend) GetPoolTransactions() (types.Transactions, error) {
   256  	pending := b.eth.txPool.Pending(false)
   257  	var txs types.Transactions
   258  	for _, batch := range pending {
   259  		txs = append(txs, batch...)
   260  	}
   261  	return txs, nil
   262  }
   263  
   264  func (b *EthAPIBackend) GetPoolTransaction(hash common.Hash) *types.Transaction {
   265  	return b.eth.txPool.Get(hash)
   266  }
   267  
   268  func (b *EthAPIBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
   269  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(b.eth.ChainDb(), txHash)
   270  	return tx, blockHash, blockNumber, index, nil
   271  }
   272  
   273  func (b *EthAPIBackend) GetPoolNonce(ctx context.Context, addr common.Address) (uint64, error) {
   274  	return b.eth.txPool.Nonce(addr), nil
   275  }
   276  
   277  func (b *EthAPIBackend) Stats() (pending int, queued int) {
   278  	return b.eth.txPool.Stats()
   279  }
   280  
   281  func (b *EthAPIBackend) TxPoolContent() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
   282  	return b.eth.TxPool().Content()
   283  }
   284  
   285  func (b *EthAPIBackend) TxPoolContentFrom(addr common.Address) (types.Transactions, types.Transactions) {
   286  	return b.eth.TxPool().ContentFrom(addr)
   287  }
   288  
   289  func (b *EthAPIBackend) JamIndex() int {
   290  	return b.eth.TxPool().JamIndex()
   291  }
   292  
   293  func (b *EthAPIBackend) TxPool() *core.TxPool {
   294  	return b.eth.TxPool()
   295  }
   296  
   297  func (b *EthAPIBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   298  	return b.eth.TxPool().SubscribeNewTxsEvent(ch)
   299  }
   300  
   301  func (b *EthAPIBackend) SyncProgress() ethereum.SyncProgress {
   302  	return b.eth.Downloader().Progress()
   303  }
   304  
   305  func (b *EthAPIBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
   306  	return b.gpo.SuggestTipCap(ctx)
   307  }
   308  
   309  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) {
   310  	return b.gpo.FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles)
   311  }
   312  
   313  func (b *EthAPIBackend) PricePrediction(ctx context.Context) ([]uint, error) {
   314  	return b.gpp.CurrentPrices(), nil
   315  }
   316  
   317  func (b *EthAPIBackend) ChainDb() ethdb.Database {
   318  	return b.eth.ChainDb()
   319  }
   320  
   321  func (b *EthAPIBackend) EventMux() *event.TypeMux {
   322  	return b.eth.EventMux()
   323  }
   324  
   325  func (b *EthAPIBackend) AccountManager() *accounts.Manager {
   326  	return b.eth.AccountManager()
   327  }
   328  
   329  func (b *EthAPIBackend) ExtRPCEnabled() bool {
   330  	return b.extRPCEnabled
   331  }
   332  
   333  func (b *EthAPIBackend) UnprotectedAllowed() bool {
   334  	return b.allowUnprotectedTxs
   335  }
   336  
   337  func (b *EthAPIBackend) RPCGasCap() uint64 {
   338  	return b.eth.config.RPCGasCap
   339  }
   340  
   341  func (b *EthAPIBackend) RPCEVMTimeout() time.Duration {
   342  	return b.eth.config.RPCEVMTimeout
   343  }
   344  
   345  func (b *EthAPIBackend) RPCTxFeeCap() float64 {
   346  	return b.eth.config.RPCTxFeeCap
   347  }
   348  
   349  func (b *EthAPIBackend) BloomStatus() (uint64, uint64) {
   350  	sections, _, _ := b.eth.bloomIndexer.Sections()
   351  	return params.BloomBitsBlocks, sections
   352  }
   353  
   354  func (b *EthAPIBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) {
   355  	for i := 0; i < bloomFilterThreads; i++ {
   356  		go session.Multiplex(bloomRetrievalBatch, bloomRetrievalWait, b.eth.bloomRequests)
   357  	}
   358  }
   359  
   360  func (b *EthAPIBackend) Engine() consensus.Engine {
   361  	return b.eth.engine
   362  }
   363  
   364  func (b *EthAPIBackend) CurrentHeader() *types.Header {
   365  	return b.eth.blockchain.CurrentHeader()
   366  }
   367  
   368  func (b *EthAPIBackend) Miner() *miner.Miner {
   369  	return b.eth.Miner()
   370  }
   371  
   372  func (b *EthAPIBackend) StartMining(threads int) error {
   373  	return b.eth.StartMining(threads)
   374  }
   375  
   376  func (b *EthAPIBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, checkLive, preferDisk bool) (*state.StateDB, error) {
   377  	return b.eth.stateAtBlock(block, reexec, base, checkLive, preferDisk)
   378  }
   379  
   380  func (b *EthAPIBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
   381  	return b.eth.stateAtTransaction(block, txIndex, reexec)
   382  }
   383  
   384  func (b *EthAPIBackend) ChainHeaderReader() consensus.ChainHeaderReader {
   385  	return b.eth.blockchain
   386  }