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