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