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