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