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