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