github.com/baptiste-b-pegasys/quorum/v22@v22.4.2/accounts/abi/bind/backends/simulated.go (about)

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