github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/accounts/abi/bind/backends/simulated.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 backends
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"sync"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum"
    28  	"github.com/ethereum/go-ethereum/accounts/abi"
    29  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    30  	"github.com/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/common/hexutil"
    32  	"github.com/ethereum/go-ethereum/common/math"
    33  	"github.com/ethereum/go-ethereum/consensus/ethash"
    34  	"github.com/ethereum/go-ethereum/core"
    35  	"github.com/ethereum/go-ethereum/core/bloombits"
    36  	"github.com/ethereum/go-ethereum/core/rawdb"
    37  	"github.com/ethereum/go-ethereum/core/state"
    38  	"github.com/ethereum/go-ethereum/core/types"
    39  	"github.com/ethereum/go-ethereum/core/vm"
    40  	"github.com/ethereum/go-ethereum/eth/filters"
    41  	"github.com/ethereum/go-ethereum/ethdb"
    42  	"github.com/ethereum/go-ethereum/event"
    43  	"github.com/ethereum/go-ethereum/log"
    44  	"github.com/ethereum/go-ethereum/params"
    45  	"github.com/ethereum/go-ethereum/rpc"
    46  )
    47  
    48  // This nil assignment ensures at compile time that SimulatedBackend implements bind.ContractBackend.
    49  var _ bind.ContractBackend = (*SimulatedBackend)(nil)
    50  
    51  var (
    52  	errBlockNumberUnsupported  = errors.New("simulatedBackend cannot access blocks other than the latest block")
    53  	errBlockDoesNotExist       = errors.New("block does not exist in blockchain")
    54  	errTransactionDoesNotExist = errors.New("transaction does not exist")
    55  )
    56  
    57  // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
    58  // the background. Its main purpose is to allow for easy testing of contract bindings.
    59  // Simulated backend implements the following interfaces:
    60  // ChainReader, ChainStateReader, ContractBackend, ContractCaller, ContractFilterer, ContractTransactor,
    61  // DeployBackend, GasEstimator, GasPricer, LogFilterer, PendingContractCaller, TransactionReader, and TransactionSender
    62  type SimulatedBackend struct {
    63  	database   ethdb.Database   // In memory database to store our testing data
    64  	blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
    65  
    66  	mu              sync.Mutex
    67  	pendingBlock    *types.Block   // Currently pending block that will be imported on request
    68  	pendingState    *state.StateDB // Currently pending state that will be the active on request
    69  	pendingReceipts types.Receipts // Currently receipts for the pending block
    70  
    71  	events *filters.EventSystem // Event system for filtering log events live
    72  
    73  	config *params.ChainConfig
    74  }
    75  
    76  // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database
    77  // and uses a simulated blockchain for testing purposes.
    78  // A simulated backend always uses chainID 1337.
    79  func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
    80  	genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc}
    81  	genesis.MustCommit(database)
    82  	blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
    83  
    84  	backend := &SimulatedBackend{
    85  		database:   database,
    86  		blockchain: blockchain,
    87  		config:     genesis.Config,
    88  	}
    89  	backend.events = filters.NewEventSystem(&filterBackend{database, blockchain, backend}, false)
    90  	backend.rollback(blockchain.CurrentBlock())
    91  	return backend
    92  }
    93  
    94  // NewSimulatedBackend creates a new binding backend using a simulated blockchain
    95  // for testing purposes.
    96  // A simulated backend always uses chainID 1337.
    97  func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
    98  	return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit)
    99  }
   100  
   101  // Close terminates the underlying blockchain's update loop.
   102  func (b *SimulatedBackend) Close() error {
   103  	b.blockchain.Stop()
   104  	return nil
   105  }
   106  
   107  // Commit imports all the pending transactions as a single block and starts a
   108  // fresh new state.
   109  func (b *SimulatedBackend) Commit() common.Hash {
   110  	b.mu.Lock()
   111  	defer b.mu.Unlock()
   112  
   113  	if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
   114  		panic(err) // This cannot happen unless the simulator is wrong, fail in that case
   115  	}
   116  	blockHash := b.pendingBlock.Hash()
   117  
   118  	// Using the last inserted block here makes it possible to build on a side
   119  	// chain after a fork.
   120  	b.rollback(b.pendingBlock)
   121  
   122  	return blockHash
   123  }
   124  
   125  // Rollback aborts all pending transactions, reverting to the last committed state.
   126  func (b *SimulatedBackend) Rollback() {
   127  	b.mu.Lock()
   128  	defer b.mu.Unlock()
   129  
   130  	b.rollback(b.blockchain.CurrentBlock())
   131  }
   132  
   133  func (b *SimulatedBackend) rollback(parent *types.Block) {
   134  	blocks, _ := core.GenerateChain(b.config, parent, ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
   135  
   136  	b.pendingBlock = blocks[0]
   137  	b.pendingState, _ = state.New(b.pendingBlock.Root(), b.blockchain.StateCache(), nil)
   138  }
   139  
   140  // Fork creates a side-chain that can be used to simulate reorgs.
   141  //
   142  // This function should be called with the ancestor block where the new side
   143  // chain should be started. Transactions (old and new) can then be applied on
   144  // top and Commit-ed.
   145  //
   146  // Note, the side-chain will only become canonical (and trigger the events) when
   147  // it becomes longer. Until then CallContract will still operate on the current
   148  // canonical chain.
   149  //
   150  // There is a % chance that the side chain becomes canonical at the same length
   151  // to simulate live network behavior.
   152  func (b *SimulatedBackend) Fork(ctx context.Context, parent common.Hash) error {
   153  	b.mu.Lock()
   154  	defer b.mu.Unlock()
   155  
   156  	if len(b.pendingBlock.Transactions()) != 0 {
   157  		return errors.New("pending block dirty")
   158  	}
   159  	block, err := b.blockByHash(ctx, parent)
   160  	if err != nil {
   161  		return err
   162  	}
   163  	b.rollback(block)
   164  	return nil
   165  }
   166  
   167  // stateByBlockNumber retrieves a state by a given blocknumber.
   168  func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) {
   169  	if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
   170  		return b.blockchain.State()
   171  	}
   172  	block, err := b.blockByNumber(ctx, blockNumber)
   173  	if err != nil {
   174  		return nil, err
   175  	}
   176  	return b.blockchain.StateAt(block.Root())
   177  }
   178  
   179  // CodeAt returns the code associated with a certain account in the blockchain.
   180  func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
   181  	b.mu.Lock()
   182  	defer b.mu.Unlock()
   183  
   184  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   185  	if err != nil {
   186  		return nil, err
   187  	}
   188  
   189  	return stateDB.GetCode(contract), nil
   190  }
   191  
   192  // BalanceAt returns the wei balance of a certain account in the blockchain.
   193  func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
   194  	b.mu.Lock()
   195  	defer b.mu.Unlock()
   196  
   197  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   198  	if err != nil {
   199  		return nil, err
   200  	}
   201  
   202  	return stateDB.GetBalance(contract), nil
   203  }
   204  
   205  // NonceAt returns the nonce of a certain account in the blockchain.
   206  func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
   207  	b.mu.Lock()
   208  	defer b.mu.Unlock()
   209  
   210  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   211  	if err != nil {
   212  		return 0, err
   213  	}
   214  
   215  	return stateDB.GetNonce(contract), nil
   216  }
   217  
   218  // StorageAt returns the value of key in the storage of an account in the blockchain.
   219  func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   220  	b.mu.Lock()
   221  	defer b.mu.Unlock()
   222  
   223  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   224  	if err != nil {
   225  		return nil, err
   226  	}
   227  
   228  	val := stateDB.GetState(contract, key)
   229  	return val[:], nil
   230  }
   231  
   232  // TransactionReceipt returns the receipt of a transaction.
   233  func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   234  	b.mu.Lock()
   235  	defer b.mu.Unlock()
   236  
   237  	receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config)
   238  	if receipt == nil {
   239  		return nil, ethereum.NotFound
   240  	}
   241  	return receipt, nil
   242  }
   243  
   244  // TransactionByHash checks the pool of pending transactions in addition to the
   245  // blockchain. The isPending return value indicates whether the transaction has been
   246  // mined yet. Note that the transaction may not be part of the canonical chain even if
   247  // it's not pending.
   248  func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
   249  	b.mu.Lock()
   250  	defer b.mu.Unlock()
   251  
   252  	tx := b.pendingBlock.Transaction(txHash)
   253  	if tx != nil {
   254  		return tx, true, nil
   255  	}
   256  	tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash)
   257  	if tx != nil {
   258  		return tx, false, nil
   259  	}
   260  	return nil, false, ethereum.NotFound
   261  }
   262  
   263  // BlockByHash retrieves a block based on the block hash.
   264  func (b *SimulatedBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   265  	b.mu.Lock()
   266  	defer b.mu.Unlock()
   267  
   268  	return b.blockByHash(ctx, hash)
   269  }
   270  
   271  // blockByHash retrieves a block based on the block hash without Locking.
   272  func (b *SimulatedBackend) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   273  	if hash == b.pendingBlock.Hash() {
   274  		return b.pendingBlock, nil
   275  	}
   276  
   277  	block := b.blockchain.GetBlockByHash(hash)
   278  	if block != nil {
   279  		return block, nil
   280  	}
   281  
   282  	return nil, errBlockDoesNotExist
   283  }
   284  
   285  // BlockByNumber retrieves a block from the database by number, caching it
   286  // (associated with its hash) if found.
   287  func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
   288  	b.mu.Lock()
   289  	defer b.mu.Unlock()
   290  
   291  	return b.blockByNumber(ctx, number)
   292  }
   293  
   294  // blockByNumber retrieves a block from the database by number, caching it
   295  // (associated with its hash) if found without Lock.
   296  func (b *SimulatedBackend) blockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
   297  	if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
   298  		return b.blockchain.CurrentBlock(), nil
   299  	}
   300  
   301  	block := b.blockchain.GetBlockByNumber(uint64(number.Int64()))
   302  	if block == nil {
   303  		return nil, errBlockDoesNotExist
   304  	}
   305  
   306  	return block, nil
   307  }
   308  
   309  // HeaderByHash returns a block header from the current canonical chain.
   310  func (b *SimulatedBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   311  	b.mu.Lock()
   312  	defer b.mu.Unlock()
   313  
   314  	if hash == b.pendingBlock.Hash() {
   315  		return b.pendingBlock.Header(), nil
   316  	}
   317  
   318  	header := b.blockchain.GetHeaderByHash(hash)
   319  	if header == nil {
   320  		return nil, errBlockDoesNotExist
   321  	}
   322  
   323  	return header, nil
   324  }
   325  
   326  // HeaderByNumber returns a block header from the current canonical chain. If number is
   327  // nil, the latest known header is returned.
   328  func (b *SimulatedBackend) HeaderByNumber(ctx context.Context, block *big.Int) (*types.Header, error) {
   329  	b.mu.Lock()
   330  	defer b.mu.Unlock()
   331  
   332  	if block == nil || block.Cmp(b.pendingBlock.Number()) == 0 {
   333  		return b.blockchain.CurrentHeader(), nil
   334  	}
   335  
   336  	return b.blockchain.GetHeaderByNumber(uint64(block.Int64())), nil
   337  }
   338  
   339  // TransactionCount returns the number of transactions in a given block.
   340  func (b *SimulatedBackend) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
   341  	b.mu.Lock()
   342  	defer b.mu.Unlock()
   343  
   344  	if blockHash == b.pendingBlock.Hash() {
   345  		return uint(b.pendingBlock.Transactions().Len()), nil
   346  	}
   347  
   348  	block := b.blockchain.GetBlockByHash(blockHash)
   349  	if block == nil {
   350  		return uint(0), errBlockDoesNotExist
   351  	}
   352  
   353  	return uint(block.Transactions().Len()), nil
   354  }
   355  
   356  // TransactionInBlock returns the transaction for a specific block at a specific index.
   357  func (b *SimulatedBackend) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
   358  	b.mu.Lock()
   359  	defer b.mu.Unlock()
   360  
   361  	if blockHash == b.pendingBlock.Hash() {
   362  		transactions := b.pendingBlock.Transactions()
   363  		if uint(len(transactions)) < index+1 {
   364  			return nil, errTransactionDoesNotExist
   365  		}
   366  
   367  		return transactions[index], nil
   368  	}
   369  
   370  	block := b.blockchain.GetBlockByHash(blockHash)
   371  	if block == nil {
   372  		return nil, errBlockDoesNotExist
   373  	}
   374  
   375  	transactions := block.Transactions()
   376  	if uint(len(transactions)) < index+1 {
   377  		return nil, errTransactionDoesNotExist
   378  	}
   379  
   380  	return transactions[index], nil
   381  }
   382  
   383  // PendingCodeAt returns the code associated with an account in the pending state.
   384  func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
   385  	b.mu.Lock()
   386  	defer b.mu.Unlock()
   387  
   388  	return b.pendingState.GetCode(contract), nil
   389  }
   390  
   391  func newRevertError(result *core.ExecutionResult) *revertError {
   392  	reason, errUnpack := abi.UnpackRevert(result.Revert())
   393  	err := errors.New("execution reverted")
   394  	if errUnpack == nil {
   395  		err = fmt.Errorf("execution reverted: %v", reason)
   396  	}
   397  	return &revertError{
   398  		error:  err,
   399  		reason: hexutil.Encode(result.Revert()),
   400  	}
   401  }
   402  
   403  // revertError is an API error that encompasses an EVM revert with JSON error
   404  // code and a binary data blob.
   405  type revertError struct {
   406  	error
   407  	reason string // revert reason hex encoded
   408  }
   409  
   410  // ErrorCode returns the JSON error code for a revert.
   411  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
   412  func (e *revertError) ErrorCode() int {
   413  	return 3
   414  }
   415  
   416  // ErrorData returns the hex encoded revert reason.
   417  func (e *revertError) ErrorData() interface{} {
   418  	return e.reason
   419  }
   420  
   421  // CallContract executes a contract call.
   422  func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
   423  	b.mu.Lock()
   424  	defer b.mu.Unlock()
   425  
   426  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   427  		return nil, errBlockNumberUnsupported
   428  	}
   429  	stateDB, err := b.blockchain.State()
   430  	if err != nil {
   431  		return nil, err
   432  	}
   433  	res, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), stateDB)
   434  	if err != nil {
   435  		return nil, err
   436  	}
   437  	// If the result contains a revert reason, try to unpack and return it.
   438  	if len(res.Revert()) > 0 {
   439  		return nil, newRevertError(res)
   440  	}
   441  	return res.Return(), res.Err
   442  }
   443  
   444  // PendingCallContract executes a contract call on the pending state.
   445  func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
   446  	b.mu.Lock()
   447  	defer b.mu.Unlock()
   448  	defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
   449  
   450  	res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   451  	if err != nil {
   452  		return nil, err
   453  	}
   454  	// If the result contains a revert reason, try to unpack and return it.
   455  	if len(res.Revert()) > 0 {
   456  		return nil, newRevertError(res)
   457  	}
   458  	return res.Return(), res.Err
   459  }
   460  
   461  // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
   462  // the nonce currently pending for the account.
   463  func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   464  	b.mu.Lock()
   465  	defer b.mu.Unlock()
   466  
   467  	return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
   468  }
   469  
   470  // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
   471  // chain doesn't have miners, we just return a gas price of 1 for any call.
   472  func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
   473  	b.mu.Lock()
   474  	defer b.mu.Unlock()
   475  
   476  	if b.pendingBlock.Header().BaseFee != nil {
   477  		return b.pendingBlock.Header().BaseFee, nil
   478  	}
   479  	return big.NewInt(1), nil
   480  }
   481  
   482  // SuggestGasTipCap implements ContractTransactor.SuggestGasTipCap. Since the simulated
   483  // chain doesn't have miners, we just return a gas tip of 1 for any call.
   484  func (b *SimulatedBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
   485  	return big.NewInt(1), nil
   486  }
   487  
   488  // EstimateGas executes the requested code against the currently pending block/state and
   489  // returns the used amount of gas.
   490  func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
   491  	b.mu.Lock()
   492  	defer b.mu.Unlock()
   493  
   494  	// Determine the lowest and highest possible gas limits to binary search in between
   495  	var (
   496  		lo  uint64 = params.TxGas - 1
   497  		hi  uint64
   498  		cap uint64
   499  	)
   500  	if call.Gas >= params.TxGas {
   501  		hi = call.Gas
   502  	} else {
   503  		hi = b.pendingBlock.GasLimit()
   504  	}
   505  	// Normalize the max fee per gas the call is willing to spend.
   506  	var feeCap *big.Int
   507  	if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
   508  		return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   509  	} else if call.GasPrice != nil {
   510  		feeCap = call.GasPrice
   511  	} else if call.GasFeeCap != nil {
   512  		feeCap = call.GasFeeCap
   513  	} else {
   514  		feeCap = common.Big0
   515  	}
   516  	// Recap the highest gas allowance with account's balance.
   517  	if feeCap.BitLen() != 0 {
   518  		balance := b.pendingState.GetBalance(call.From) // from can't be nil
   519  		available := new(big.Int).Set(balance)
   520  		if call.Value != nil {
   521  			if call.Value.Cmp(available) >= 0 {
   522  				return 0, errors.New("insufficient funds for transfer")
   523  			}
   524  			available.Sub(available, call.Value)
   525  		}
   526  		allowance := new(big.Int).Div(available, feeCap)
   527  		if allowance.IsUint64() && hi > allowance.Uint64() {
   528  			transfer := call.Value
   529  			if transfer == nil {
   530  				transfer = new(big.Int)
   531  			}
   532  			log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
   533  				"sent", transfer, "feecap", feeCap, "fundable", allowance)
   534  			hi = allowance.Uint64()
   535  		}
   536  	}
   537  	cap = hi
   538  
   539  	// Create a helper to check if a gas allowance results in an executable transaction
   540  	executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
   541  		call.Gas = gas
   542  
   543  		snapshot := b.pendingState.Snapshot()
   544  		res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   545  		b.pendingState.RevertToSnapshot(snapshot)
   546  
   547  		if err != nil {
   548  			if errors.Is(err, core.ErrIntrinsicGas) {
   549  				return true, nil, nil // Special case, raise gas limit
   550  			}
   551  			return true, nil, err // Bail out
   552  		}
   553  		return res.Failed(), res, nil
   554  	}
   555  	// Execute the binary search and hone in on an executable gas limit
   556  	for lo+1 < hi {
   557  		mid := (hi + lo) / 2
   558  		failed, _, err := executable(mid)
   559  
   560  		// If the error is not nil(consensus error), it means the provided message
   561  		// call or transaction will never be accepted no matter how much gas it is
   562  		// assigned. Return the error directly, don't struggle any more
   563  		if err != nil {
   564  			return 0, err
   565  		}
   566  		if failed {
   567  			lo = mid
   568  		} else {
   569  			hi = mid
   570  		}
   571  	}
   572  	// Reject the transaction as invalid if it still fails at the highest allowance
   573  	if hi == cap {
   574  		failed, result, err := executable(hi)
   575  		if err != nil {
   576  			return 0, err
   577  		}
   578  		if failed {
   579  			if result != nil && result.Err != vm.ErrOutOfGas {
   580  				if len(result.Revert()) > 0 {
   581  					return 0, newRevertError(result)
   582  				}
   583  				return 0, result.Err
   584  			}
   585  			// Otherwise, the specified gas cap is too low
   586  			return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
   587  		}
   588  	}
   589  	return hi, nil
   590  }
   591  
   592  // callContract implements common code between normal and pending contract calls.
   593  // state is modified during execution, make sure to copy it if necessary.
   594  func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) {
   595  	// Gas prices post 1559 need to be initialized
   596  	if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
   597  		return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   598  	}
   599  	head := b.blockchain.CurrentHeader()
   600  	if !b.blockchain.Config().IsLondon(head.Number) {
   601  		// If there's no basefee, then it must be a non-1559 execution
   602  		if call.GasPrice == nil {
   603  			call.GasPrice = new(big.Int)
   604  		}
   605  		call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice
   606  	} else {
   607  		// A basefee is provided, necessitating 1559-type execution
   608  		if call.GasPrice != nil {
   609  			// User specified the legacy gas field, convert to 1559 gas typing
   610  			call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice
   611  		} else {
   612  			// User specified 1559 gas feilds (or none), use those
   613  			if call.GasFeeCap == nil {
   614  				call.GasFeeCap = new(big.Int)
   615  			}
   616  			if call.GasTipCap == nil {
   617  				call.GasTipCap = new(big.Int)
   618  			}
   619  			// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
   620  			call.GasPrice = new(big.Int)
   621  			if call.GasFeeCap.BitLen() > 0 || call.GasTipCap.BitLen() > 0 {
   622  				call.GasPrice = math.BigMin(new(big.Int).Add(call.GasTipCap, head.BaseFee), call.GasFeeCap)
   623  			}
   624  		}
   625  	}
   626  	// Ensure message is initialized properly.
   627  	if call.Gas == 0 {
   628  		call.Gas = 50000000
   629  	}
   630  	if call.Value == nil {
   631  		call.Value = new(big.Int)
   632  	}
   633  	// Set infinite balance to the fake caller account.
   634  	from := stateDB.GetOrNewStateObject(call.From)
   635  	from.SetBalance(math.MaxBig256)
   636  	// Execute the call.
   637  	msg := callMsg{call}
   638  
   639  	txContext := core.NewEVMTxContext(msg)
   640  	evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil)
   641  	// Create a new environment which holds all relevant information
   642  	// about the transaction and calling mechanisms.
   643  	vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true})
   644  	gasPool := new(core.GasPool).AddGas(math.MaxUint64)
   645  
   646  	return core.NewStateTransition(vmEnv, msg, gasPool).TransitionDb()
   647  }
   648  
   649  // SendTransaction updates the pending block to include the given transaction.
   650  func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   651  	b.mu.Lock()
   652  	defer b.mu.Unlock()
   653  
   654  	// Get the last block
   655  	block, err := b.blockByHash(ctx, b.pendingBlock.ParentHash())
   656  	if err != nil {
   657  		return fmt.Errorf("could not fetch parent")
   658  	}
   659  	// Check transaction validity
   660  	signer := types.MakeSigner(b.blockchain.Config(), block.Number())
   661  	sender, err := types.Sender(signer, tx)
   662  	if err != nil {
   663  		return fmt.Errorf("invalid transaction: %v", err)
   664  	}
   665  	nonce := b.pendingState.GetNonce(sender)
   666  	if tx.Nonce() != nonce {
   667  		return fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce)
   668  	}
   669  	// Include tx in chain
   670  	blocks, receipts := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   671  		for _, tx := range b.pendingBlock.Transactions() {
   672  			block.AddTxWithChain(b.blockchain, tx)
   673  		}
   674  		block.AddTxWithChain(b.blockchain, tx)
   675  	})
   676  	stateDB, _ := b.blockchain.State()
   677  
   678  	b.pendingBlock = blocks[0]
   679  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   680  	b.pendingReceipts = receipts[0]
   681  	return nil
   682  }
   683  
   684  // FilterLogs executes a log filter operation, blocking during execution and
   685  // returning all the results in one batch.
   686  //
   687  // TODO(karalabe): Deprecate when the subscription one can return past data too.
   688  func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
   689  	var filter *filters.Filter
   690  	if query.BlockHash != nil {
   691  		// Block filter requested, construct a single-shot filter
   692  		filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain, b}, *query.BlockHash, query.Addresses, query.Topics)
   693  	} else {
   694  		// Initialize unset filter boundaries to run from genesis to chain head
   695  		from := int64(0)
   696  		if query.FromBlock != nil {
   697  			from = query.FromBlock.Int64()
   698  		}
   699  		to := int64(-1)
   700  		if query.ToBlock != nil {
   701  			to = query.ToBlock.Int64()
   702  		}
   703  		// Construct the range filter
   704  		filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain, b}, from, to, query.Addresses, query.Topics)
   705  	}
   706  	// Run the filter and return all the logs
   707  	logs, err := filter.Logs(ctx)
   708  	if err != nil {
   709  		return nil, err
   710  	}
   711  	res := make([]types.Log, len(logs))
   712  	for i, nLog := range logs {
   713  		res[i] = *nLog
   714  	}
   715  	return res, nil
   716  }
   717  
   718  // SubscribeFilterLogs creates a background log filtering operation, returning a
   719  // subscription immediately, which can be used to stream the found events.
   720  func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
   721  	// Subscribe to contract events
   722  	sink := make(chan []*types.Log)
   723  
   724  	sub, err := b.events.SubscribeLogs(query, sink)
   725  	if err != nil {
   726  		return nil, err
   727  	}
   728  	// Since we're getting logs in batches, we need to flatten them into a plain stream
   729  	return event.NewSubscription(func(quit <-chan struct{}) error {
   730  		defer sub.Unsubscribe()
   731  		for {
   732  			select {
   733  			case logs := <-sink:
   734  				for _, nlog := range logs {
   735  					select {
   736  					case ch <- *nlog:
   737  					case err := <-sub.Err():
   738  						return err
   739  					case <-quit:
   740  						return nil
   741  					}
   742  				}
   743  			case err := <-sub.Err():
   744  				return err
   745  			case <-quit:
   746  				return nil
   747  			}
   748  		}
   749  	}), nil
   750  }
   751  
   752  // SubscribeNewHead returns an event subscription for a new header.
   753  func (b *SimulatedBackend) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
   754  	// subscribe to a new head
   755  	sink := make(chan *types.Header)
   756  	sub := b.events.SubscribeNewHeads(sink)
   757  
   758  	return event.NewSubscription(func(quit <-chan struct{}) error {
   759  		defer sub.Unsubscribe()
   760  		for {
   761  			select {
   762  			case head := <-sink:
   763  				select {
   764  				case ch <- head:
   765  				case err := <-sub.Err():
   766  					return err
   767  				case <-quit:
   768  					return nil
   769  				}
   770  			case err := <-sub.Err():
   771  				return err
   772  			case <-quit:
   773  				return nil
   774  			}
   775  		}
   776  	}), nil
   777  }
   778  
   779  // AdjustTime adds a time shift to the simulated clock.
   780  // It can only be called on empty blocks.
   781  func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
   782  	b.mu.Lock()
   783  	defer b.mu.Unlock()
   784  
   785  	if len(b.pendingBlock.Transactions()) != 0 {
   786  		return errors.New("Could not adjust time on non-empty block")
   787  	}
   788  
   789  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   790  		block.OffsetTime(int64(adjustment.Seconds()))
   791  	})
   792  	stateDB, _ := b.blockchain.State()
   793  
   794  	b.pendingBlock = blocks[0]
   795  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   796  
   797  	return nil
   798  }
   799  
   800  // Blockchain returns the underlying blockchain.
   801  func (b *SimulatedBackend) Blockchain() *core.BlockChain {
   802  	return b.blockchain
   803  }
   804  
   805  // callMsg implements core.Message to allow passing it as a transaction simulator.
   806  type callMsg struct {
   807  	ethereum.CallMsg
   808  }
   809  
   810  func (m callMsg) UnderlyingTransaction() *types.Transaction { return nil }
   811  func (m callMsg) RunMode() types.MessageRunMode             { return types.MessageEthcallMode }
   812  
   813  func (m callMsg) From() common.Address         { return m.CallMsg.From }
   814  func (m callMsg) Nonce() uint64                { return 0 }
   815  func (m callMsg) IsFake() bool                 { return true }
   816  func (m callMsg) To() *common.Address          { return m.CallMsg.To }
   817  func (m callMsg) GasPrice() *big.Int           { return m.CallMsg.GasPrice }
   818  func (m callMsg) GasFeeCap() *big.Int          { return m.CallMsg.GasFeeCap }
   819  func (m callMsg) GasTipCap() *big.Int          { return m.CallMsg.GasTipCap }
   820  func (m callMsg) Gas() uint64                  { return m.CallMsg.Gas }
   821  func (m callMsg) Value() *big.Int              { return m.CallMsg.Value }
   822  func (m callMsg) Data() []byte                 { return m.CallMsg.Data }
   823  func (m callMsg) AccessList() types.AccessList { return m.CallMsg.AccessList }
   824  
   825  // filterBackend implements filters.Backend to support filtering for logs without
   826  // taking bloom-bits acceleration structures into account.
   827  type filterBackend struct {
   828  	db      ethdb.Database
   829  	bc      *core.BlockChain
   830  	backend *SimulatedBackend
   831  }
   832  
   833  func (fb *filterBackend) ChainDb() ethdb.Database  { return fb.db }
   834  func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
   835  
   836  func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
   837  	if block == rpc.LatestBlockNumber {
   838  		return fb.bc.CurrentHeader(), nil
   839  	}
   840  	return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
   841  }
   842  
   843  func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   844  	return fb.bc.GetHeaderByHash(hash), nil
   845  }
   846  
   847  func (fb *filterBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   848  	return fb.backend.pendingBlock, fb.backend.pendingReceipts
   849  }
   850  
   851  func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   852  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   853  	if number == nil {
   854  		return nil, nil
   855  	}
   856  	return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
   857  }
   858  
   859  func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
   860  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   861  	if number == nil {
   862  		return nil, nil
   863  	}
   864  	receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
   865  	if receipts == nil {
   866  		return nil, nil
   867  	}
   868  	logs := make([][]*types.Log, len(receipts))
   869  	for i, receipt := range receipts {
   870  		logs[i] = receipt.Logs
   871  	}
   872  	return logs, nil
   873  }
   874  
   875  func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   876  	return nullSubscription()
   877  }
   878  
   879  func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   880  	return fb.bc.SubscribeChainEvent(ch)
   881  }
   882  
   883  func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   884  	return fb.bc.SubscribeRemovedLogsEvent(ch)
   885  }
   886  
   887  func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   888  	return fb.bc.SubscribeLogsEvent(ch)
   889  }
   890  
   891  func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
   892  	return nullSubscription()
   893  }
   894  
   895  func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
   896  
   897  func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
   898  	panic("not supported")
   899  }
   900  
   901  func nullSubscription() event.Subscription {
   902  	return event.NewSubscription(func(quit <-chan struct{}) error {
   903  		<-quit
   904  		return nil
   905  	})
   906  }