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