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