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