github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/accounts/abi/bind/backends/simulated.go (about)

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