github.com/klaytn/klaytn@v1.10.2/accounts/abi/bind/backends/simulated.go (about)

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