github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/accounts/abi/bind/backends/simulated.go (about)

     1  // Copyright 2022 Commercium
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package backends
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"sync"
    26  	"time"
    27  
    28  	"github.com/CommerciumBlockchain/go-commercium"
    29  	"github.com/CommerciumBlockchain/go-commercium/accounts/abi"
    30  	"github.com/CommerciumBlockchain/go-commercium/accounts/abi/bind"
    31  	"github.com/CommerciumBlockchain/go-commercium/common"
    32  	"github.com/CommerciumBlockchain/go-commercium/common/hexutil"
    33  	"github.com/CommerciumBlockchain/go-commercium/common/math"
    34  	"github.com/CommerciumBlockchain/go-commercium/consensus/ethash"
    35  	"github.com/CommerciumBlockchain/go-commercium/core"
    36  	"github.com/CommerciumBlockchain/go-commercium/core/bloombits"
    37  	"github.com/CommerciumBlockchain/go-commercium/core/rawdb"
    38  	"github.com/CommerciumBlockchain/go-commercium/core/state"
    39  	"github.com/CommerciumBlockchain/go-commercium/core/types"
    40  	"github.com/CommerciumBlockchain/go-commercium/core/vm"
    41  	"github.com/CommerciumBlockchain/go-commercium/eth/filters"
    42  	"github.com/CommerciumBlockchain/go-commercium/ethdb"
    43  	"github.com/CommerciumBlockchain/go-commercium/event"
    44  	"github.com/CommerciumBlockchain/go-commercium/log"
    45  	"github.com/CommerciumBlockchain/go-commercium/params"
    46  	"github.com/CommerciumBlockchain/go-commercium/rpc"
    47  )
    48  
    49  // This nil assignment ensures at compile time that SimulatedBackend implements bind.ContractBackend.
    50  var _ bind.ContractBackend = (*SimulatedBackend)(nil)
    51  
    52  var (
    53  	errBlockNumberUnsupported  = errors.New("simulatedBackend cannot access blocks other than the latest block")
    54  	errBlockDoesNotExist       = errors.New("block does not exist in blockchain")
    55  	errTransactionDoesNotExist = errors.New("transaction does not exist")
    56  )
    57  
    58  // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
    59  // the background. Its main purpose is to allow for easy testing of contract bindings.
    60  // Simulated backend implements the following interfaces:
    61  // ChainReader, ChainStateReader, ContractBackend, ContractCaller, ContractFilterer, ContractTransactor,
    62  // DeployBackend, LogFilterer, PendingContractCaller, TransactionReader, and TransactionSender
    63  type SimulatedBackend struct {
    64  	database   ethdb.Database   // In memory database to store our testing data
    65  	blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
    66  
    67  	mu           sync.Mutex
    68  	pendingBlock *types.Block   // Currently pending block that will be imported on request
    69  	pendingState *state.StateDB // Currently pending state that will be the active on request
    70  
    71  	events *filters.EventSystem // Event system for filtering log events live
    72  
    73  	config *params.ChainConfig
    74  }
    75  
    76  // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database
    77  // and uses a simulated blockchain for testing purposes.
    78  // A simulated backend always uses chainID 1337.
    79  func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc) *SimulatedBackend {
    80  	genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc}
    81  	genesis.MustCommit(database)
    82  	blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
    83  
    84  	backend := &SimulatedBackend{
    85  		database:   database,
    86  		blockchain: blockchain,
    87  		config:     genesis.Config,
    88  		events:     filters.NewEventSystem(&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) *SimulatedBackend {
    98  	return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc)
    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  	stateDB, _ := b.blockchain.State()
   130  
   131  	b.pendingBlock = blocks[0]
   132  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   133  }
   134  
   135  // stateByBlockNumber retrieves a state by a given blocknumber.
   136  func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) {
   137  	if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
   138  		return b.blockchain.State()
   139  	}
   140  	block, err := b.blockByNumberNoLock(ctx, blockNumber)
   141  	if err != nil {
   142  		return nil, err
   143  	}
   144  	return b.blockchain.StateAt(block.Root())
   145  }
   146  
   147  // CodeAt returns the code associated with a certain account in the blockchain.
   148  func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
   149  	b.mu.Lock()
   150  	defer b.mu.Unlock()
   151  
   152  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   153  	if err != nil {
   154  		return nil, err
   155  	}
   156  
   157  	return stateDB.GetCode(contract), nil
   158  }
   159  
   160  // BalanceAt returns the wei balance of a certain account in the blockchain.
   161  func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
   162  	b.mu.Lock()
   163  	defer b.mu.Unlock()
   164  
   165  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   166  	if err != nil {
   167  		return nil, err
   168  	}
   169  
   170  	return stateDB.GetBalance(contract), nil
   171  }
   172  
   173  // NonceAt returns the nonce of a certain account in the blockchain.
   174  func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
   175  	b.mu.Lock()
   176  	defer b.mu.Unlock()
   177  
   178  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   179  	if err != nil {
   180  		return 0, err
   181  	}
   182  
   183  	return stateDB.GetNonce(contract), nil
   184  }
   185  
   186  // StorageAt returns the value of key in the storage of an account in the blockchain.
   187  func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   188  	b.mu.Lock()
   189  	defer b.mu.Unlock()
   190  
   191  	stateDB, err := b.stateByBlockNumber(ctx, blockNumber)
   192  	if err != nil {
   193  		return nil, err
   194  	}
   195  
   196  	val := stateDB.GetState(contract, key)
   197  	return val[:], nil
   198  }
   199  
   200  // TransactionReceipt returns the receipt of a transaction.
   201  func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   202  	b.mu.Lock()
   203  	defer b.mu.Unlock()
   204  
   205  	receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config)
   206  	return receipt, nil
   207  }
   208  
   209  // TransactionByHash checks the pool of pending transactions in addition to the
   210  // blockchain. The isPending return value indicates whether the transaction has been
   211  // mined yet. Note that the transaction may not be part of the canonical chain even if
   212  // it's not pending.
   213  func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
   214  	b.mu.Lock()
   215  	defer b.mu.Unlock()
   216  
   217  	tx := b.pendingBlock.Transaction(txHash)
   218  	if tx != nil {
   219  		return tx, true, nil
   220  	}
   221  	tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash)
   222  	if tx != nil {
   223  		return tx, false, nil
   224  	}
   225  	return nil, false, ethereum.NotFound
   226  }
   227  
   228  // BlockByHash retrieves a block based on the block hash.
   229  func (b *SimulatedBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   230  	b.mu.Lock()
   231  	defer b.mu.Unlock()
   232  
   233  	if hash == b.pendingBlock.Hash() {
   234  		return b.pendingBlock, nil
   235  	}
   236  
   237  	block := b.blockchain.GetBlockByHash(hash)
   238  	if block != nil {
   239  		return block, nil
   240  	}
   241  
   242  	return nil, errBlockDoesNotExist
   243  }
   244  
   245  // BlockByNumber retrieves a block from the database by number, caching it
   246  // (associated with its hash) if found.
   247  func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
   248  	b.mu.Lock()
   249  	defer b.mu.Unlock()
   250  
   251  	return b.blockByNumberNoLock(ctx, number)
   252  }
   253  
   254  // blockByNumberNoLock retrieves a block from the database by number, caching it
   255  // (associated with its hash) if found without Lock.
   256  func (b *SimulatedBackend) blockByNumberNoLock(ctx context.Context, number *big.Int) (*types.Block, error) {
   257  	if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
   258  		return b.blockchain.CurrentBlock(), nil
   259  	}
   260  
   261  	block := b.blockchain.GetBlockByNumber(uint64(number.Int64()))
   262  	if block == nil {
   263  		return nil, errBlockDoesNotExist
   264  	}
   265  
   266  	return block, nil
   267  }
   268  
   269  // HeaderByHash returns a block header from the current canonical chain.
   270  func (b *SimulatedBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   271  	b.mu.Lock()
   272  	defer b.mu.Unlock()
   273  
   274  	if hash == b.pendingBlock.Hash() {
   275  		return b.pendingBlock.Header(), nil
   276  	}
   277  
   278  	header := b.blockchain.GetHeaderByHash(hash)
   279  	if header == nil {
   280  		return nil, errBlockDoesNotExist
   281  	}
   282  
   283  	return header, nil
   284  }
   285  
   286  // HeaderByNumber returns a block header from the current canonical chain. If number is
   287  // nil, the latest known header is returned.
   288  func (b *SimulatedBackend) HeaderByNumber(ctx context.Context, block *big.Int) (*types.Header, error) {
   289  	b.mu.Lock()
   290  	defer b.mu.Unlock()
   291  
   292  	if block == nil || block.Cmp(b.pendingBlock.Number()) == 0 {
   293  		return b.blockchain.CurrentHeader(), nil
   294  	}
   295  
   296  	return b.blockchain.GetHeaderByNumber(uint64(block.Int64())), nil
   297  }
   298  
   299  // TransactionCount returns the number of transactions in a given block.
   300  func (b *SimulatedBackend) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
   301  	b.mu.Lock()
   302  	defer b.mu.Unlock()
   303  
   304  	if blockHash == b.pendingBlock.Hash() {
   305  		return uint(b.pendingBlock.Transactions().Len()), nil
   306  	}
   307  
   308  	block := b.blockchain.GetBlockByHash(blockHash)
   309  	if block == nil {
   310  		return uint(0), errBlockDoesNotExist
   311  	}
   312  
   313  	return uint(block.Transactions().Len()), nil
   314  }
   315  
   316  // TransactionInBlock returns the transaction for a specific block at a specific index.
   317  func (b *SimulatedBackend) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
   318  	b.mu.Lock()
   319  	defer b.mu.Unlock()
   320  
   321  	if blockHash == b.pendingBlock.Hash() {
   322  		transactions := b.pendingBlock.Transactions()
   323  		if uint(len(transactions)) < index+1 {
   324  			return nil, errTransactionDoesNotExist
   325  		}
   326  
   327  		return transactions[index], nil
   328  	}
   329  
   330  	block := b.blockchain.GetBlockByHash(blockHash)
   331  	if block == nil {
   332  		return nil, errBlockDoesNotExist
   333  	}
   334  
   335  	transactions := block.Transactions()
   336  	if uint(len(transactions)) < index+1 {
   337  		return nil, errTransactionDoesNotExist
   338  	}
   339  
   340  	return transactions[index], nil
   341  }
   342  
   343  // PendingCodeAt returns the code associated with an account in the pending state.
   344  func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
   345  	b.mu.Lock()
   346  	defer b.mu.Unlock()
   347  
   348  	return b.pendingState.GetCode(contract), nil
   349  }
   350  
   351  func newRevertError(result *core.ExecutionResult) *revertError {
   352  	reason, errUnpack := abi.UnpackRevert(result.Revert())
   353  	err := errors.New("execution reverted")
   354  	if errUnpack == nil {
   355  		err = fmt.Errorf("execution reverted: %v", reason)
   356  	}
   357  	return &revertError{
   358  		error:  err,
   359  		reason: hexutil.Encode(result.Revert()),
   360  	}
   361  }
   362  
   363  // revertError is an API error that encompasses an EVM revert with JSON error
   364  // code and a binary data blob.
   365  type revertError struct {
   366  	error
   367  	reason string // revert reason hex encoded
   368  }
   369  
   370  // ErrorCode returns the JSON error code for a revert.
   371  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
   372  func (e *revertError) ErrorCode() int {
   373  	return 3
   374  }
   375  
   376  // ErrorData returns the hex encoded revert reason.
   377  func (e *revertError) ErrorData() interface{} {
   378  	return e.reason
   379  }
   380  
   381  // CallContract executes a contract call.
   382  func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
   383  	b.mu.Lock()
   384  	defer b.mu.Unlock()
   385  
   386  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   387  		return nil, errBlockNumberUnsupported
   388  	}
   389  	stateDB, err := b.blockchain.State()
   390  	if err != nil {
   391  		return nil, err
   392  	}
   393  	res, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), stateDB)
   394  	if err != nil {
   395  		return nil, err
   396  	}
   397  	// If the result contains a revert reason, try to unpack and return it.
   398  	if len(res.Revert()) > 0 {
   399  		return nil, newRevertError(res)
   400  	}
   401  	return res.Return(), res.Err
   402  }
   403  
   404  // PendingCallContract executes a contract call on the pending state.
   405  func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
   406  	b.mu.Lock()
   407  	defer b.mu.Unlock()
   408  	defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
   409  
   410  	res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   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  // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
   422  // the nonce currently pending for the account.
   423  func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   424  	b.mu.Lock()
   425  	defer b.mu.Unlock()
   426  
   427  	return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
   428  }
   429  
   430  // callContract implements common code between normal and pending contract calls.
   431  // state is modified during execution, make sure to copy it if necessary.
   432  func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, stateDB *state.StateDB) (*core.ExecutionResult, error) {
   433  	if call.Value == nil {
   434  		call.Value = new(big.Int)
   435  	}
   436  	// Set infinite balance to the fake caller account.
   437  	from := stateDB.GetOrNewStateObject(call.From)
   438  	from.SetBalance(math.MaxBig256)
   439  	// Execute the call.
   440  	msg := callMsg{call}
   441  
   442  	txContext := core.NewEVMTxContext(msg)
   443  	evmContext := core.NewEVMBlockContext(block.Header(), b.blockchain, nil)
   444  	// Create a new environment which holds all relevant information
   445  	// about the transaction and calling mechanisms.
   446  	vmEnv := vm.NewEVM(evmContext, txContext, stateDB, b.config, vm.Config{})
   447  
   448  	return core.NewStateTransition(vmEnv, msg).TransitionDb()
   449  }
   450  
   451  // SendTransaction updates the pending block to include the given transaction.
   452  // It panics if the transaction is invalid.
   453  func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   454  	b.mu.Lock()
   455  	defer b.mu.Unlock()
   456  
   457  	sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx)
   458  	if err != nil {
   459  		panic(fmt.Errorf("invalid transaction: %v", err))
   460  	}
   461  	nonce := b.pendingState.GetNonce(sender)
   462  	if tx.Nonce() != nonce {
   463  		panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
   464  	}
   465  
   466  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   467  		for _, tx := range b.pendingBlock.Transactions() {
   468  			block.AddTxWithChain(b.blockchain, tx)
   469  		}
   470  		block.AddTxWithChain(b.blockchain, tx)
   471  	})
   472  	stateDB, _ := b.blockchain.State()
   473  
   474  	b.pendingBlock = blocks[0]
   475  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   476  	return nil
   477  }
   478  
   479  // FilterLogs executes a log filter operation, blocking during execution and
   480  // returning all the results in one batch.
   481  //
   482  // TODO(karalabe): Deprecate when the subscription one can return past data too.
   483  func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
   484  	var filter *filters.Filter
   485  	if query.BlockHash != nil {
   486  		// Block filter requested, construct a single-shot filter
   487  		filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
   488  	} else {
   489  		// Initialize unset filter boundaries to run from genesis to chain head
   490  		from := int64(0)
   491  		if query.FromBlock != nil {
   492  			from = query.FromBlock.Int64()
   493  		}
   494  		to := int64(-1)
   495  		if query.ToBlock != nil {
   496  			to = query.ToBlock.Int64()
   497  		}
   498  		// Construct the range filter
   499  		filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
   500  	}
   501  	// Run the filter and return all the logs
   502  	logs, err := filter.Logs(ctx)
   503  	if err != nil {
   504  		return nil, err
   505  	}
   506  	res := make([]types.Log, len(logs))
   507  	for i, nLog := range logs {
   508  		res[i] = *nLog
   509  	}
   510  	return res, nil
   511  }
   512  
   513  // SubscribeFilterLogs creates a background log filtering operation, returning a
   514  // subscription immediately, which can be used to stream the found events.
   515  func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
   516  	// Subscribe to contract events
   517  	sink := make(chan []*types.Log)
   518  
   519  	sub, err := b.events.SubscribeLogs(query, sink)
   520  	if err != nil {
   521  		return nil, err
   522  	}
   523  	// Since we're getting logs in batches, we need to flatten them into a plain stream
   524  	return event.NewSubscription(func(quit <-chan struct{}) error {
   525  		defer sub.Unsubscribe()
   526  		for {
   527  			select {
   528  			case logs := <-sink:
   529  				for _, nlog := range logs {
   530  					select {
   531  					case ch <- *nlog:
   532  					case err := <-sub.Err():
   533  						return err
   534  					case <-quit:
   535  						return nil
   536  					}
   537  				}
   538  			case err := <-sub.Err():
   539  				return err
   540  			case <-quit:
   541  				return nil
   542  			}
   543  		}
   544  	}), nil
   545  }
   546  
   547  // SubscribeNewHead returns an event subscription for a new header.
   548  func (b *SimulatedBackend) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
   549  	// subscribe to a new head
   550  	sink := make(chan *types.Header)
   551  	sub := b.events.SubscribeNewHeads(sink)
   552  
   553  	return event.NewSubscription(func(quit <-chan struct{}) error {
   554  		defer sub.Unsubscribe()
   555  		for {
   556  			select {
   557  			case head := <-sink:
   558  				select {
   559  				case ch <- head:
   560  				case err := <-sub.Err():
   561  					return err
   562  				case <-quit:
   563  					return nil
   564  				}
   565  			case err := <-sub.Err():
   566  				return err
   567  			case <-quit:
   568  				return nil
   569  			}
   570  		}
   571  	}), nil
   572  }
   573  
   574  // AdjustTime adds a time shift to the simulated clock.
   575  // It can only be called on empty blocks.
   576  func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
   577  	b.mu.Lock()
   578  	defer b.mu.Unlock()
   579  
   580  	if len(b.pendingBlock.Transactions()) != 0 {
   581  		return errors.New("Could not adjust time on non-empty block")
   582  	}
   583  
   584  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   585  		block.OffsetTime(int64(adjustment.Seconds()))
   586  	})
   587  	stateDB, _ := b.blockchain.State()
   588  
   589  	b.pendingBlock = blocks[0]
   590  	b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
   591  
   592  	return nil
   593  }
   594  
   595  // Blockchain returns the underlying blockchain.
   596  func (b *SimulatedBackend) Blockchain() *core.BlockChain {
   597  	return b.blockchain
   598  }
   599  
   600  // callMsg implements core.Message to allow passing it as a transaction simulator.
   601  type callMsg struct {
   602  	ethereum.CallMsg
   603  }
   604  
   605  func (m callMsg) From() common.Address { return m.CallMsg.From }
   606  func (m callMsg) Nonce() uint64        { return 0 }
   607  func (m callMsg) CheckNonce() bool     { return false }
   608  func (m callMsg) To() *common.Address  { return m.CallMsg.To }
   609  func (m callMsg) Value() *big.Int      { return m.CallMsg.Value }
   610  func (m callMsg) Data() []byte         { return m.CallMsg.Data }
   611  
   612  // filterBackend implements filters.Backend to support filtering for logs without
   613  // taking bloom-bits acceleration structures into account.
   614  type filterBackend struct {
   615  	db ethdb.Database
   616  	bc *core.BlockChain
   617  }
   618  
   619  func (fb *filterBackend) ChainDb() ethdb.Database  { return fb.db }
   620  func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
   621  
   622  func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
   623  	if block == rpc.LatestBlockNumber {
   624  		return fb.bc.CurrentHeader(), nil
   625  	}
   626  	return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
   627  }
   628  
   629  func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   630  	return fb.bc.GetHeaderByHash(hash), nil
   631  }
   632  
   633  func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   634  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   635  	if number == nil {
   636  		return nil, nil
   637  	}
   638  	return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
   639  }
   640  
   641  func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
   642  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   643  	if number == nil {
   644  		return nil, nil
   645  	}
   646  	receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
   647  	if receipts == nil {
   648  		return nil, nil
   649  	}
   650  	logs := make([][]*types.Log, len(receipts))
   651  	for i, receipt := range receipts {
   652  		logs[i] = receipt.Logs
   653  	}
   654  	return logs, nil
   655  }
   656  
   657  func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   658  	return nullSubscription()
   659  }
   660  
   661  func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   662  	return fb.bc.SubscribeChainEvent(ch)
   663  }
   664  
   665  func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   666  	return fb.bc.SubscribeRemovedLogsEvent(ch)
   667  }
   668  
   669  func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   670  	return fb.bc.SubscribeLogsEvent(ch)
   671  }
   672  
   673  func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
   674  	return nullSubscription()
   675  }
   676  
   677  func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
   678  
   679  func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
   680  	panic("not supported")
   681  }
   682  
   683  func nullSubscription() event.Subscription {
   684  	return event.NewSubscription(func(quit <-chan struct{}) error {
   685  		<-quit
   686  		return nil
   687  	})
   688  }