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