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