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