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