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