github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/accounts/abi/bind/backends/simulated.go (about)

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