github.com/nonsense/go-ethereum@v1.9.7/accounts/abi/bind/backends/simulated.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package backends
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"sync"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum"
    28  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/math"
    31  	"github.com/ethereum/go-ethereum/consensus/ethash"
    32  	"github.com/ethereum/go-ethereum/core"
    33  	"github.com/ethereum/go-ethereum/core/bloombits"
    34  	"github.com/ethereum/go-ethereum/core/rawdb"
    35  	"github.com/ethereum/go-ethereum/core/state"
    36  	"github.com/ethereum/go-ethereum/core/types"
    37  	"github.com/ethereum/go-ethereum/core/vm"
    38  	"github.com/ethereum/go-ethereum/eth/filters"
    39  	"github.com/ethereum/go-ethereum/ethdb"
    40  	"github.com/ethereum/go-ethereum/event"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/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  	errGasEstimationFailed    = errors.New("gas required exceeds allowance or always failing transaction")
    51  )
    52  
    53  // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
    54  // the background. Its main purpose is to allow easily testing contract bindings.
    55  type SimulatedBackend struct {
    56  	database   ethdb.Database   // In memory database to store our testing data
    57  	blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
    58  
    59  	mu           sync.Mutex
    60  	pendingBlock *types.Block   // Currently pending block that will be imported on request
    61  	pendingState *state.StateDB // Currently pending state that will be the active on on request
    62  
    63  	events *filters.EventSystem // Event system for filtering log events live
    64  
    65  	config *params.ChainConfig
    66  }
    67  
    68  // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database
    69  // and uses a simulated blockchain for testing purposes.
    70  func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
    71  	genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc}
    72  	genesis.MustCommit(database)
    73  	blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil)
    74  
    75  	backend := &SimulatedBackend{
    76  		database:   database,
    77  		blockchain: blockchain,
    78  		config:     genesis.Config,
    79  		events:     filters.NewEventSystem(new(event.TypeMux), &filterBackend{database, blockchain}, false),
    80  	}
    81  	backend.rollback()
    82  	return backend
    83  }
    84  
    85  // NewSimulatedBackend creates a new binding backend using a simulated blockchain
    86  // for testing purposes.
    87  func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
    88  	return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit)
    89  }
    90  
    91  // Close terminates the underlying blockchain's update loop.
    92  func (b *SimulatedBackend) Close() error {
    93  	b.blockchain.Stop()
    94  	return nil
    95  }
    96  
    97  // Commit imports all the pending transactions as a single block and starts a
    98  // fresh new state.
    99  func (b *SimulatedBackend) Commit() {
   100  	b.mu.Lock()
   101  	defer b.mu.Unlock()
   102  
   103  	if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
   104  		panic(err) // This cannot happen unless the simulator is wrong, fail in that case
   105  	}
   106  	b.rollback()
   107  }
   108  
   109  // Rollback aborts all pending transactions, reverting to the last committed state.
   110  func (b *SimulatedBackend) Rollback() {
   111  	b.mu.Lock()
   112  	defer b.mu.Unlock()
   113  
   114  	b.rollback()
   115  }
   116  
   117  func (b *SimulatedBackend) rollback() {
   118  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
   119  	statedb, _ := b.blockchain.State()
   120  
   121  	b.pendingBlock = blocks[0]
   122  	b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
   123  }
   124  
   125  // CodeAt returns the code associated with a certain account in the blockchain.
   126  func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
   127  	b.mu.Lock()
   128  	defer b.mu.Unlock()
   129  
   130  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   131  		return nil, errBlockNumberUnsupported
   132  	}
   133  	statedb, _ := b.blockchain.State()
   134  	return statedb.GetCode(contract), nil
   135  }
   136  
   137  // BalanceAt returns the wei balance of a certain account in the blockchain.
   138  func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
   139  	b.mu.Lock()
   140  	defer b.mu.Unlock()
   141  
   142  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   143  		return nil, errBlockNumberUnsupported
   144  	}
   145  	statedb, _ := b.blockchain.State()
   146  	return statedb.GetBalance(contract), nil
   147  }
   148  
   149  // NonceAt returns the nonce of a certain account in the blockchain.
   150  func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
   151  	b.mu.Lock()
   152  	defer b.mu.Unlock()
   153  
   154  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   155  		return 0, errBlockNumberUnsupported
   156  	}
   157  	statedb, _ := b.blockchain.State()
   158  	return statedb.GetNonce(contract), nil
   159  }
   160  
   161  // StorageAt returns the value of key in the storage of an account in the blockchain.
   162  func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   163  	b.mu.Lock()
   164  	defer b.mu.Unlock()
   165  
   166  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   167  		return nil, errBlockNumberUnsupported
   168  	}
   169  	statedb, _ := b.blockchain.State()
   170  	val := statedb.GetState(contract, key)
   171  	return val[:], nil
   172  }
   173  
   174  // TransactionReceipt returns the receipt of a transaction.
   175  func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   176  	receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config)
   177  	return receipt, nil
   178  }
   179  
   180  // TransactionByHash checks the pool of pending transactions in addition to the
   181  // blockchain. The isPending return value indicates whether the transaction has been
   182  // mined yet. Note that the transaction may not be part of the canonical chain even if
   183  // it's not pending.
   184  func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
   185  	b.mu.Lock()
   186  	defer b.mu.Unlock()
   187  
   188  	tx := b.pendingBlock.Transaction(txHash)
   189  	if tx != nil {
   190  		return tx, true, nil
   191  	}
   192  	tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash)
   193  	if tx != nil {
   194  		return tx, false, nil
   195  	}
   196  	return nil, false, ethereum.NotFound
   197  }
   198  
   199  // PendingCodeAt returns the code associated with an account in the pending state.
   200  func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
   201  	b.mu.Lock()
   202  	defer b.mu.Unlock()
   203  
   204  	return b.pendingState.GetCode(contract), nil
   205  }
   206  
   207  // CallContract executes a contract call.
   208  func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
   209  	b.mu.Lock()
   210  	defer b.mu.Unlock()
   211  
   212  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   213  		return nil, errBlockNumberUnsupported
   214  	}
   215  	state, err := b.blockchain.State()
   216  	if err != nil {
   217  		return nil, err
   218  	}
   219  	rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
   220  	return rval, err
   221  }
   222  
   223  // PendingCallContract executes a contract call on the pending state.
   224  func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
   225  	b.mu.Lock()
   226  	defer b.mu.Unlock()
   227  	defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
   228  
   229  	rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   230  	return rval, err
   231  }
   232  
   233  // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
   234  // the nonce currently pending for the account.
   235  func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   236  	b.mu.Lock()
   237  	defer b.mu.Unlock()
   238  
   239  	return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
   240  }
   241  
   242  // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
   243  // chain doesn't have miners, we just return a gas price of 1 for any call.
   244  func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
   245  	return big.NewInt(1), nil
   246  }
   247  
   248  // EstimateGas executes the requested code against the currently pending block/state and
   249  // returns the used amount of gas.
   250  func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
   251  	b.mu.Lock()
   252  	defer b.mu.Unlock()
   253  
   254  	// Determine the lowest and highest possible gas limits to binary search in between
   255  	var (
   256  		lo  uint64 = params.TxGas - 1
   257  		hi  uint64
   258  		cap uint64
   259  	)
   260  	if call.Gas >= params.TxGas {
   261  		hi = call.Gas
   262  	} else {
   263  		hi = b.pendingBlock.GasLimit()
   264  	}
   265  	cap = hi
   266  
   267  	// Create a helper to check if a gas allowance results in an executable transaction
   268  	executable := func(gas uint64) bool {
   269  		call.Gas = gas
   270  
   271  		snapshot := b.pendingState.Snapshot()
   272  		_, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   273  		b.pendingState.RevertToSnapshot(snapshot)
   274  
   275  		if err != nil || failed {
   276  			return false
   277  		}
   278  		return true
   279  	}
   280  	// Execute the binary search and hone in on an executable gas limit
   281  	for lo+1 < hi {
   282  		mid := (hi + lo) / 2
   283  		if !executable(mid) {
   284  			lo = mid
   285  		} else {
   286  			hi = mid
   287  		}
   288  	}
   289  	// Reject the transaction as invalid if it still fails at the highest allowance
   290  	if hi == cap {
   291  		if !executable(hi) {
   292  			return 0, errGasEstimationFailed
   293  		}
   294  	}
   295  	return hi, nil
   296  }
   297  
   298  // callContract implements common code between normal and pending contract calls.
   299  // state is modified during execution, make sure to copy it if necessary.
   300  func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
   301  	// Ensure message is initialized properly.
   302  	if call.GasPrice == nil {
   303  		call.GasPrice = big.NewInt(1)
   304  	}
   305  	if call.Gas == 0 {
   306  		call.Gas = 50000000
   307  	}
   308  	if call.Value == nil {
   309  		call.Value = new(big.Int)
   310  	}
   311  	// Set infinite balance to the fake caller account.
   312  	from := statedb.GetOrNewStateObject(call.From)
   313  	from.SetBalance(math.MaxBig256)
   314  	// Execute the call.
   315  	msg := callmsg{call}
   316  
   317  	evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
   318  	// Create a new environment which holds all relevant information
   319  	// about the transaction and calling mechanisms.
   320  	vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
   321  	gaspool := new(core.GasPool).AddGas(math.MaxUint64)
   322  
   323  	return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
   324  }
   325  
   326  // SendTransaction updates the pending block to include the given transaction.
   327  // It panics if the transaction is invalid.
   328  func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   329  	b.mu.Lock()
   330  	defer b.mu.Unlock()
   331  
   332  	sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx)
   333  	if err != nil {
   334  		panic(fmt.Errorf("invalid transaction: %v", err))
   335  	}
   336  	nonce := b.pendingState.GetNonce(sender)
   337  	if tx.Nonce() != nonce {
   338  		panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
   339  	}
   340  
   341  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   342  		for _, tx := range b.pendingBlock.Transactions() {
   343  			block.AddTxWithChain(b.blockchain, tx)
   344  		}
   345  		block.AddTxWithChain(b.blockchain, tx)
   346  	})
   347  	statedb, _ := b.blockchain.State()
   348  
   349  	b.pendingBlock = blocks[0]
   350  	b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
   351  	return nil
   352  }
   353  
   354  // FilterLogs executes a log filter operation, blocking during execution and
   355  // returning all the results in one batch.
   356  //
   357  // TODO(karalabe): Deprecate when the subscription one can return past data too.
   358  func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
   359  	var filter *filters.Filter
   360  	if query.BlockHash != nil {
   361  		// Block filter requested, construct a single-shot filter
   362  		filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
   363  	} else {
   364  		// Initialize unset filter boundaried to run from genesis to chain head
   365  		from := int64(0)
   366  		if query.FromBlock != nil {
   367  			from = query.FromBlock.Int64()
   368  		}
   369  		to := int64(-1)
   370  		if query.ToBlock != nil {
   371  			to = query.ToBlock.Int64()
   372  		}
   373  		// Construct the range filter
   374  		filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
   375  	}
   376  	// Run the filter and return all the logs
   377  	logs, err := filter.Logs(ctx)
   378  	if err != nil {
   379  		return nil, err
   380  	}
   381  	res := make([]types.Log, len(logs))
   382  	for i, log := range logs {
   383  		res[i] = *log
   384  	}
   385  	return res, nil
   386  }
   387  
   388  // SubscribeFilterLogs creates a background log filtering operation, returning a
   389  // subscription immediately, which can be used to stream the found events.
   390  func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
   391  	// Subscribe to contract events
   392  	sink := make(chan []*types.Log)
   393  
   394  	sub, err := b.events.SubscribeLogs(query, sink)
   395  	if err != nil {
   396  		return nil, err
   397  	}
   398  	// Since we're getting logs in batches, we need to flatten them into a plain stream
   399  	return event.NewSubscription(func(quit <-chan struct{}) error {
   400  		defer sub.Unsubscribe()
   401  		for {
   402  			select {
   403  			case logs := <-sink:
   404  				for _, log := range logs {
   405  					select {
   406  					case ch <- *log:
   407  					case err := <-sub.Err():
   408  						return err
   409  					case <-quit:
   410  						return nil
   411  					}
   412  				}
   413  			case err := <-sub.Err():
   414  				return err
   415  			case <-quit:
   416  				return nil
   417  			}
   418  		}
   419  	}), nil
   420  }
   421  
   422  // AdjustTime adds a time shift to the simulated clock.
   423  func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
   424  	b.mu.Lock()
   425  	defer b.mu.Unlock()
   426  	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
   427  		for _, tx := range b.pendingBlock.Transactions() {
   428  			block.AddTx(tx)
   429  		}
   430  		block.OffsetTime(int64(adjustment.Seconds()))
   431  	})
   432  	statedb, _ := b.blockchain.State()
   433  
   434  	b.pendingBlock = blocks[0]
   435  	b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
   436  
   437  	return nil
   438  }
   439  
   440  // Blockchain returns the underlying blockchain.
   441  func (b *SimulatedBackend) Blockchain() *core.BlockChain {
   442  	return b.blockchain
   443  }
   444  
   445  // callmsg implements core.Message to allow passing it as a transaction simulator.
   446  type callmsg struct {
   447  	ethereum.CallMsg
   448  }
   449  
   450  func (m callmsg) From() common.Address { return m.CallMsg.From }
   451  func (m callmsg) Nonce() uint64        { return 0 }
   452  func (m callmsg) CheckNonce() bool     { return false }
   453  func (m callmsg) To() *common.Address  { return m.CallMsg.To }
   454  func (m callmsg) GasPrice() *big.Int   { return m.CallMsg.GasPrice }
   455  func (m callmsg) Gas() uint64          { return m.CallMsg.Gas }
   456  func (m callmsg) Value() *big.Int      { return m.CallMsg.Value }
   457  func (m callmsg) Data() []byte         { return m.CallMsg.Data }
   458  
   459  // filterBackend implements filters.Backend to support filtering for logs without
   460  // taking bloom-bits acceleration structures into account.
   461  type filterBackend struct {
   462  	db ethdb.Database
   463  	bc *core.BlockChain
   464  }
   465  
   466  func (fb *filterBackend) ChainDb() ethdb.Database  { return fb.db }
   467  func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
   468  
   469  func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
   470  	if block == rpc.LatestBlockNumber {
   471  		return fb.bc.CurrentHeader(), nil
   472  	}
   473  	return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
   474  }
   475  
   476  func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   477  	return fb.bc.GetHeaderByHash(hash), nil
   478  }
   479  
   480  func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   481  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   482  	if number == nil {
   483  		return nil, nil
   484  	}
   485  	return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
   486  }
   487  
   488  func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
   489  	number := rawdb.ReadHeaderNumber(fb.db, hash)
   490  	if number == nil {
   491  		return nil, nil
   492  	}
   493  	receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
   494  	if receipts == nil {
   495  		return nil, nil
   496  	}
   497  	logs := make([][]*types.Log, len(receipts))
   498  	for i, receipt := range receipts {
   499  		logs[i] = receipt.Logs
   500  	}
   501  	return logs, nil
   502  }
   503  
   504  func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   505  	return event.NewSubscription(func(quit <-chan struct{}) error {
   506  		<-quit
   507  		return nil
   508  	})
   509  }
   510  func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   511  	return fb.bc.SubscribeChainEvent(ch)
   512  }
   513  func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   514  	return fb.bc.SubscribeRemovedLogsEvent(ch)
   515  }
   516  func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   517  	return fb.bc.SubscribeLogsEvent(ch)
   518  }
   519  
   520  func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
   521  func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
   522  	panic("not supported")
   523  }