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