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