github.com/Evanesco-Labs/go-evanesco@v1.0.1/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/Evanesco-Labs/go-evanesco"
    28  	"github.com/Evanesco-Labs/go-evanesco/accounts/abi"
    29  	"github.com/Evanesco-Labs/go-evanesco/accounts/abi/bind"
    30  	"github.com/Evanesco-Labs/go-evanesco/common"
    31  	"github.com/Evanesco-Labs/go-evanesco/common/hexutil"
    32  	"github.com/Evanesco-Labs/go-evanesco/common/math"
    33  	"github.com/Evanesco-Labs/go-evanesco/consensus/ethash"
    34  	"github.com/Evanesco-Labs/go-evanesco/core"
    35  	"github.com/Evanesco-Labs/go-evanesco/core/bloombits"
    36  	"github.com/Evanesco-Labs/go-evanesco/core/rawdb"
    37  	"github.com/Evanesco-Labs/go-evanesco/core/state"
    38  	"github.com/Evanesco-Labs/go-evanesco/core/types"
    39  	"github.com/Evanesco-Labs/go-evanesco/core/vm"
    40  	"github.com/Evanesco-Labs/go-evanesco/eth/filters"
    41  	"github.com/Evanesco-Labs/go-evanesco/ethdb"
    42  	"github.com/Evanesco-Labs/go-evanesco/event"
    43  	"github.com/Evanesco-Labs/go-evanesco/log"
    44  	"github.com/Evanesco-Labs/go-evanesco/params"
    45  	"github.com/Evanesco-Labs/go-evanesco/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, 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  	return big.NewInt(1), nil
   466  }
   467  
   468  // SuggestGasTipCap implements ContractTransactor.SuggestGasTipCap. Since the simulated
   469  // chain doesn't have miners, we just return a gas tip of 1 for any call.
   470  func (b *SimulatedBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
   471  	return big.NewInt(1), nil
   472  }
   473  
   474  // EstimateGas executes the requested code against the currently pending block/state and
   475  // returns the used amount of gas.
   476  func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
   477  	b.mu.Lock()
   478  	defer b.mu.Unlock()
   479  
   480  	// Determine the lowest and highest possible gas limits to binary search in between
   481  	var (
   482  		lo  uint64 = params.TxGas - 1
   483  		hi  uint64
   484  		cap uint64
   485  	)
   486  	if call.Gas >= params.TxGas {
   487  		hi = call.Gas
   488  	} else {
   489  		hi = b.pendingBlock.GasLimit()
   490  	}
   491  	// Recap the highest gas allowance with account's balance.
   492  	if call.GasPrice != nil && call.GasPrice.BitLen() != 0 {
   493  		balance := b.pendingState.GetBalance(call.From) // from can't be nil
   494  		available := new(big.Int).Set(balance)
   495  		if call.Value != nil {
   496  			if call.Value.Cmp(available) >= 0 {
   497  				return 0, errors.New("insufficient funds for transfer")
   498  			}
   499  			available.Sub(available, call.Value)
   500  		}
   501  		allowance := new(big.Int).Div(available, call.GasPrice)
   502  		if allowance.IsUint64() && hi > allowance.Uint64() {
   503  			transfer := call.Value
   504  			if transfer == nil {
   505  				transfer = new(big.Int)
   506  			}
   507  			log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
   508  				"sent", transfer, "gasprice", call.GasPrice, "fundable", allowance)
   509  			hi = allowance.Uint64()
   510  		}
   511  	}
   512  	cap = hi
   513  
   514  	// Create a helper to check if a gas allowance results in an executable transaction
   515  	executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
   516  		call.Gas = gas
   517  
   518  		snapshot := b.pendingState.Snapshot()
   519  		res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   520  		b.pendingState.RevertToSnapshot(snapshot)
   521  
   522  		if err != nil {
   523  			if errors.Is(err, core.ErrIntrinsicGas) {
   524  				return true, nil, nil // Special case, raise gas limit
   525  			}
   526  			return true, nil, err // Bail out
   527  		}
   528  		return res.Failed(), res, nil
   529  	}
   530  	// Execute the binary search and hone in on an executable gas limit
   531  	for lo+1 < hi {
   532  		mid := (hi + lo) / 2
   533  		failed, _, err := executable(mid)
   534  
   535  		// If the error is not nil(consensus error), it means the provided message
   536  		// call or transaction will never be accepted no matter how much gas it is
   537  		// assigned. Return the error directly, don't struggle any more
   538  		if err != nil {
   539  			return 0, err
   540  		}
   541  		if failed {
   542  			lo = mid
   543  		} else {
   544  			hi = mid
   545  		}
   546  	}
   547  	// Reject the transaction as invalid if it still fails at the highest allowance
   548  	if hi == cap {
   549  		failed, result, err := executable(hi)
   550  		if err != nil {
   551  			return 0, err
   552  		}
   553  		if failed {
   554  			if result != nil && result.Err != vm.ErrOutOfGas {
   555  				if len(result.Revert()) > 0 {
   556  					return 0, newRevertError(result)
   557  				}
   558  				return 0, result.Err
   559  			}
   560  			// Otherwise, the specified gas cap is too low
   561  			return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
   562  		}
   563  	}
   564  	return hi, nil
   565  }
   566  
   567  // callContract implements common code between normal and pending contract calls.
   568  // state is modified during execution, make sure to copy it if necessary.
   569  func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) {
   570  	// Gas prices post 1559 need to be initialized
   571  	if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) {
   572  		return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   573  	}
   574  	head := b.blockchain.CurrentHeader()
   575  	if !b.blockchain.Config().IsLondon(head.Number) {
   576  		// If there's no basefee, then it must be a non-1559 execution
   577  		if call.GasPrice == nil {
   578  			call.GasPrice = new(big.Int)
   579  		}
   580  		call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice
   581  	} else {
   582  		// A basefee is provided, necessitating 1559-type execution
   583  		if call.GasPrice != nil {
   584  			// User specified the legacy gas field, convert to 1559 gas typing
   585  			call.GasFeeCap, call.GasTipCap = call.GasPrice, call.GasPrice
   586  		} else {
   587  			// User specified 1559 gas feilds (or none), use those
   588  			if call.GasFeeCap == nil {
   589  				call.GasFeeCap = new(big.Int)
   590  			}
   591  			if call.GasTipCap == nil {
   592  				call.GasTipCap = new(big.Int)
   593  			}
   594  			// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
   595  			call.GasPrice = new(big.Int)
   596  			if call.GasFeeCap.BitLen() > 0 || call.GasTipCap.BitLen() > 0 {
   597  				call.GasPrice = math.BigMin(new(big.Int).Add(call.GasTipCap, head.BaseFee), call.GasFeeCap)
   598  			}
   599  		}
   600  	}
   601  	// Ensure message is initialized properly.
   602  	if call.Gas == 0 {
   603  		call.Gas = 50000000
   604  	}
   605  	if call.Value == nil {
   606  		call.Value = new(big.Int)
   607  	}
   608  	// Set infinite balance to the fake caller account.
   609  	from := stateDB.GetOrNewStateObject(call.From)
   610  	from.SetBalance(math.MaxBig256)
   611  	// Execute the call.
   612  	msg := callMsg{call}
   613  
   614  	txContext := core.NewEVMTxContext(msg)
   615  	evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil)
   616  	// Create a new environment which holds all relevant information
   617  	// about the transaction and calling mechanisms.
   618  	vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{NoBaseFee: true})
   619  	gasPool := new(core.GasPool).AddGas(math.MaxUint64)
   620  
   621  	return core.NewStateTransition(vmEnv, msg, gasPool).TransitionDb()
   622  }
   623  
   624  // SendTransaction updates the pending block to include the given transaction.
   625  // It panics if the transaction is invalid.
   626  func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   627  	b.mu.Lock()
   628  	defer b.mu.Unlock()
   629  
   630  	// Get the last block
   631  	block, err := b.blockByHash(ctx, b.pendingBlock.ParentHash())
   632  	if err != nil {
   633  		panic("could not fetch parent")
   634  	}
   635  	// Check transaction validity
   636  	signer := types.MakeSigner(b.blockchain.Config(), block.Number())
   637  	sender, err := types.Sender(signer, tx)
   638  	if err != nil {
   639  		panic(fmt.Errorf("invalid transaction: %v", err))
   640  	}
   641  	nonce := b.pendingState.GetNonce(sender)
   642  	if tx.Nonce() != nonce {
   643  		panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
   644  	}
   645  	// Include tx in chain
   646  	blocks, _ := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   647  		for _, tx := range b.pendingBlock.Transactions() {
   648  			block.AddTxWithChain(b.blockchain, tx)
   649  		}
   650  		block.AddTxWithChain(b.blockchain, tx)
   651  	})
   652  	stateDB, _ := b.blockchain.State()
   653  
   654  	b.pendingBlock = blocks[0]
   655  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   656  	return nil
   657  }
   658  
   659  // FilterLogs executes a log filter operation, blocking during execution and
   660  // returning all the results in one batch.
   661  //
   662  // TODO(karalabe): Deprecate when the subscription one can return past data too.
   663  func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
   664  	var filter *filters.Filter
   665  	if query.BlockHash != nil {
   666  		// Block filter requested, construct a single-shot filter
   667  		filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
   668  	} else {
   669  		// Initialize unset filter boundaries to run from genesis to chain head
   670  		from := int64(0)
   671  		if query.FromBlock != nil {
   672  			from = query.FromBlock.Int64()
   673  		}
   674  		to := int64(-1)
   675  		if query.ToBlock != nil {
   676  			to = query.ToBlock.Int64()
   677  		}
   678  		// Construct the range filter
   679  		filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
   680  	}
   681  	// Run the filter and return all the logs
   682  	logs, err := filter.Logs(ctx)
   683  	if err != nil {
   684  		return nil, err
   685  	}
   686  	res := make([]types.Log, len(logs))
   687  	for i, nLog := range logs {
   688  		res[i] = *nLog
   689  	}
   690  	return res, nil
   691  }
   692  
   693  // SubscribeFilterLogs creates a background log filtering operation, returning a
   694  // subscription immediately, which can be used to stream the found events.
   695  func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
   696  	// Subscribe to contract events
   697  	sink := make(chan []*types.Log)
   698  
   699  	sub, err := b.events.SubscribeLogs(query, sink)
   700  	if err != nil {
   701  		return nil, err
   702  	}
   703  	// Since we're getting logs in batches, we need to flatten them into a plain stream
   704  	return event.NewSubscription(func(quit <-chan struct{}) error {
   705  		defer sub.Unsubscribe()
   706  		for {
   707  			select {
   708  			case logs := <-sink:
   709  				for _, nlog := range logs {
   710  					select {
   711  					case ch <- *nlog:
   712  					case err := <-sub.Err():
   713  						return err
   714  					case <-quit:
   715  						return nil
   716  					}
   717  				}
   718  			case err := <-sub.Err():
   719  				return err
   720  			case <-quit:
   721  				return nil
   722  			}
   723  		}
   724  	}), nil
   725  }
   726  
   727  // SubscribeNewHead returns an event subscription for a new header.
   728  func (b *SimulatedBackend) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
   729  	// subscribe to a new head
   730  	sink := make(chan *types.Header)
   731  	sub := b.events.SubscribeNewHeads(sink)
   732  
   733  	return event.NewSubscription(func(quit <-chan struct{}) error {
   734  		defer sub.Unsubscribe()
   735  		for {
   736  			select {
   737  			case head := <-sink:
   738  				select {
   739  				case ch <- head:
   740  				case err := <-sub.Err():
   741  					return err
   742  				case <-quit:
   743  					return nil
   744  				}
   745  			case err := <-sub.Err():
   746  				return err
   747  			case <-quit:
   748  				return nil
   749  			}
   750  		}
   751  	}), nil
   752  }
   753  
   754  // AdjustTime adds a time shift to the simulated clock.
   755  // It can only be called on empty blocks.
   756  func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
   757  	b.mu.Lock()
   758  	defer b.mu.Unlock()
   759  
   760  	if len(b.pendingBlock.Transactions()) != 0 {
   761  		return errors.New("Could not adjust time on non-empty block")
   762  	}
   763  
   764  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   765  		block.OffsetTime(int64(adjustment.Seconds()))
   766  	})
   767  	stateDB, _ := b.blockchain.State()
   768  
   769  	b.pendingBlock = blocks[0]
   770  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   771  
   772  	return nil
   773  }
   774  
   775  // Blockchain returns the underlying blockchain.
   776  func (b *SimulatedBackend) Blockchain() *core.BlockChain {
   777  	return b.blockchain
   778  }
   779  
   780  // callMsg implements core.Message to allow passing it as a transaction simulator.
   781  type callMsg struct {
   782  	ethereum.CallMsg
   783  }
   784  
   785  func (m callMsg) From() common.Address         { return m.CallMsg.From }
   786  func (m callMsg) Nonce() uint64                { return 0 }
   787  func (m callMsg) CheckNonce() bool             { return false }
   788  func (m callMsg) To() *common.Address          { return m.CallMsg.To }
   789  func (m callMsg) GasPrice() *big.Int           { return m.CallMsg.GasPrice }
   790  func (m callMsg) GasFeeCap() *big.Int          { return m.CallMsg.GasFeeCap }
   791  func (m callMsg) GasTipCap() *big.Int          { return m.CallMsg.GasTipCap }
   792  func (m callMsg) Gas() uint64                  { return m.CallMsg.Gas }
   793  func (m callMsg) Value() *big.Int              { return m.CallMsg.Value }
   794  func (m callMsg) Data() []byte                 { return m.CallMsg.Data }
   795  func (m callMsg) AccessList() types.AccessList { return m.CallMsg.AccessList }
   796  
   797  // filterBackend implements filters.Backend to support filtering for logs without
   798  // taking bloom-bits acceleration structures into account.
   799  type filterBackend struct {
   800  	db ethdb.Database
   801  	bc *core.BlockChain
   802  }
   803  
   804  func (fb *filterBackend) ChainDb() ethdb.Database  { return fb.db }
   805  func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
   806  
   807  func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
   808  	if block == rpc.LatestBlockNumber {
   809  		return fb.bc.CurrentHeader(), nil
   810  	}
   811  	return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
   812  }
   813  
   814  func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   815  	return fb.bc.GetHeaderByHash(hash), nil
   816  }
   817  
   818  func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   819  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   820  	if number == nil {
   821  		return nil, nil
   822  	}
   823  	return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
   824  }
   825  
   826  func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
   827  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   828  	if number == nil {
   829  		return nil, nil
   830  	}
   831  	receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
   832  	if receipts == nil {
   833  		return nil, nil
   834  	}
   835  	logs := make([][]*types.Log, len(receipts))
   836  	for i, receipt := range receipts {
   837  		logs[i] = receipt.Logs
   838  	}
   839  	return logs, nil
   840  }
   841  
   842  func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   843  	return nullSubscription()
   844  }
   845  
   846  func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   847  	return fb.bc.SubscribeChainEvent(ch)
   848  }
   849  
   850  func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   851  	return fb.bc.SubscribeRemovedLogsEvent(ch)
   852  }
   853  
   854  func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   855  	return fb.bc.SubscribeLogsEvent(ch)
   856  }
   857  
   858  func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
   859  	return nullSubscription()
   860  }
   861  
   862  func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
   863  
   864  func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
   865  	panic("not supported")
   866  }
   867  
   868  func nullSubscription() event.Subscription {
   869  	return event.NewSubscription(func(quit <-chan struct{}) error {
   870  		<-quit
   871  		return nil
   872  	})
   873  }