github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/accounts/abi/bind/backends/simulated.go (about)

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