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