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