github.com/avence12/go-ethereum@v1.5.10-0.20170320123548-1dfd65f6d047/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  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  	"sync"
    24  
    25  	"github.com/ethereum/go-ethereum"
    26  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/math"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/state"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/core/vm"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/event"
    35  	"github.com/ethereum/go-ethereum/params"
    36  	"github.com/ethereum/go-ethereum/pow"
    37  	"golang.org/x/net/context"
    38  )
    39  
    40  // Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)
    41  var chainConfig = &params.ChainConfig{HomesteadBlock: big.NewInt(0), EIP150Block: new(big.Int), EIP158Block: new(big.Int)}
    42  
    43  // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
    44  var _ bind.ContractBackend = (*SimulatedBackend)(nil)
    45  
    46  var errBlockNumberUnsupported = errors.New("SimulatedBackend cannot access blocks other than the latest block")
    47  
    48  // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
    49  // the background. Its main purpose is to allow easily testing contract bindings.
    50  type SimulatedBackend struct {
    51  	database   ethdb.Database   // In memory database to store our testing data
    52  	blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
    53  
    54  	mu           sync.Mutex
    55  	pendingBlock *types.Block   // Currently pending block that will be imported on request
    56  	pendingState *state.StateDB // Currently pending state that will be the active on on request
    57  
    58  	config *params.ChainConfig
    59  }
    60  
    61  // NewSimulatedBackend creates a new binding backend using a simulated blockchain
    62  // for testing purposes.
    63  func NewSimulatedBackend(accounts ...core.GenesisAccount) *SimulatedBackend {
    64  	database, _ := ethdb.NewMemDatabase()
    65  	core.WriteGenesisBlockForTesting(database, accounts...)
    66  	blockchain, _ := core.NewBlockChain(database, chainConfig, new(pow.FakePow), new(event.TypeMux), vm.Config{})
    67  	backend := &SimulatedBackend{database: database, blockchain: blockchain}
    68  	backend.rollback()
    69  	return backend
    70  }
    71  
    72  // Commit imports all the pending transactions as a single block and starts a
    73  // fresh new state.
    74  func (b *SimulatedBackend) Commit() {
    75  	b.mu.Lock()
    76  	defer b.mu.Unlock()
    77  
    78  	if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
    79  		panic(err) // This cannot happen unless the simulator is wrong, fail in that case
    80  	}
    81  	b.rollback()
    82  }
    83  
    84  // Rollback aborts all pending transactions, reverting to the last committed state.
    85  func (b *SimulatedBackend) Rollback() {
    86  	b.mu.Lock()
    87  	defer b.mu.Unlock()
    88  
    89  	b.rollback()
    90  }
    91  
    92  func (b *SimulatedBackend) rollback() {
    93  	blocks, _ := core.GenerateChain(chainConfig, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {})
    94  	b.pendingBlock = blocks[0]
    95  	b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
    96  }
    97  
    98  // CodeAt returns the code associated with a certain account in the blockchain.
    99  func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
   100  	b.mu.Lock()
   101  	defer b.mu.Unlock()
   102  
   103  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   104  		return nil, errBlockNumberUnsupported
   105  	}
   106  	statedb, _ := b.blockchain.State()
   107  	return statedb.GetCode(contract), nil
   108  }
   109  
   110  // BalanceAt returns the wei balance of a certain account in the blockchain.
   111  func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
   112  	b.mu.Lock()
   113  	defer b.mu.Unlock()
   114  
   115  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   116  		return nil, errBlockNumberUnsupported
   117  	}
   118  	statedb, _ := b.blockchain.State()
   119  	return statedb.GetBalance(contract), nil
   120  }
   121  
   122  // NonceAt returns the nonce of a certain account in the blockchain.
   123  func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
   124  	b.mu.Lock()
   125  	defer b.mu.Unlock()
   126  
   127  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   128  		return 0, errBlockNumberUnsupported
   129  	}
   130  	statedb, _ := b.blockchain.State()
   131  	return statedb.GetNonce(contract), nil
   132  }
   133  
   134  // StorageAt returns the value of key in the storage of an account in the blockchain.
   135  func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   136  	b.mu.Lock()
   137  	defer b.mu.Unlock()
   138  
   139  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   140  		return nil, errBlockNumberUnsupported
   141  	}
   142  	statedb, _ := b.blockchain.State()
   143  	val := statedb.GetState(contract, key)
   144  	return val[:], nil
   145  }
   146  
   147  // TransactionReceipt returns the receipt of a transaction.
   148  func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   149  	return core.GetReceipt(b.database, txHash), nil
   150  }
   151  
   152  // PendingCodeAt returns the code associated with an account in the pending state.
   153  func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
   154  	b.mu.Lock()
   155  	defer b.mu.Unlock()
   156  
   157  	return b.pendingState.GetCode(contract), nil
   158  }
   159  
   160  // CallContract executes a contract call.
   161  func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
   162  	b.mu.Lock()
   163  	defer b.mu.Unlock()
   164  
   165  	if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
   166  		return nil, errBlockNumberUnsupported
   167  	}
   168  	state, err := b.blockchain.State()
   169  	if err != nil {
   170  		return nil, err
   171  	}
   172  	rval, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
   173  	return rval, err
   174  }
   175  
   176  // PendingCallContract executes a contract call on the pending state.
   177  func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
   178  	b.mu.Lock()
   179  	defer b.mu.Unlock()
   180  	defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
   181  
   182  	rval, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   183  	return rval, err
   184  }
   185  
   186  // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
   187  // the nonce currently pending for the account.
   188  func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   189  	b.mu.Lock()
   190  	defer b.mu.Unlock()
   191  
   192  	return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
   193  }
   194  
   195  // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
   196  // chain doens't have miners, we just return a gas price of 1 for any call.
   197  func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
   198  	return big.NewInt(1), nil
   199  }
   200  
   201  // EstimateGas executes the requested code against the currently pending block/state and
   202  // returns the used amount of gas.
   203  func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) {
   204  	b.mu.Lock()
   205  	defer b.mu.Unlock()
   206  
   207  	// Binary search the gas requirement, as it may be higher than the amount used
   208  	var lo, hi uint64
   209  	if call.Gas != nil {
   210  		hi = call.Gas.Uint64()
   211  	} else {
   212  		hi = b.pendingBlock.GasLimit().Uint64()
   213  	}
   214  	for lo+1 < hi {
   215  		// Take a guess at the gas, and check transaction validity
   216  		mid := (hi + lo) / 2
   217  		call.Gas = new(big.Int).SetUint64(mid)
   218  
   219  		snapshot := b.pendingState.Snapshot()
   220  		_, gas, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
   221  		b.pendingState.RevertToSnapshot(snapshot)
   222  
   223  		// If the transaction became invalid or used all the gas (failed), raise the gas limit
   224  		if err != nil || gas.Cmp(call.Gas) == 0 {
   225  			lo = mid
   226  			continue
   227  		}
   228  		// Otherwise assume the transaction succeeded, lower the gas limit
   229  		hi = mid
   230  	}
   231  	return new(big.Int).SetUint64(hi), nil
   232  }
   233  
   234  // callContract implemens common code between normal and pending contract calls.
   235  // state is modified during execution, make sure to copy it if necessary.
   236  func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, error) {
   237  	// Ensure message is initialized properly.
   238  	if call.GasPrice == nil {
   239  		call.GasPrice = big.NewInt(1)
   240  	}
   241  	if call.Gas == nil || call.Gas.Sign() == 0 {
   242  		call.Gas = big.NewInt(50000000)
   243  	}
   244  	if call.Value == nil {
   245  		call.Value = new(big.Int)
   246  	}
   247  	// Set infinite balance to the fake caller account.
   248  	from := statedb.GetOrNewStateObject(call.From)
   249  	from.SetBalance(math.MaxBig256)
   250  	// Execute the call.
   251  	msg := callmsg{call}
   252  
   253  	evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain)
   254  	// Create a new environment which holds all relevant information
   255  	// about the transaction and calling mechanisms.
   256  	vmenv := vm.NewEVM(evmContext, statedb, chainConfig, vm.Config{})
   257  	gaspool := new(core.GasPool).AddGas(math.MaxBig256)
   258  	ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
   259  	return ret, gasUsed, err
   260  }
   261  
   262  // SendTransaction updates the pending block to include the given transaction.
   263  // It panics if the transaction is invalid.
   264  func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   265  	b.mu.Lock()
   266  	defer b.mu.Unlock()
   267  
   268  	sender, err := types.Sender(types.HomesteadSigner{}, tx)
   269  	if err != nil {
   270  		panic(fmt.Errorf("invalid transaction: %v", err))
   271  	}
   272  	nonce := b.pendingState.GetNonce(sender)
   273  	if tx.Nonce() != nonce {
   274  		panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
   275  	}
   276  
   277  	blocks, _ := core.GenerateChain(chainConfig, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
   278  		for _, tx := range b.pendingBlock.Transactions() {
   279  			block.AddTx(tx)
   280  		}
   281  		block.AddTx(tx)
   282  	})
   283  	b.pendingBlock = blocks[0]
   284  	b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
   285  	return nil
   286  }
   287  
   288  // callmsg implements core.Message to allow passing it as a transaction simulator.
   289  type callmsg struct {
   290  	ethereum.CallMsg
   291  }
   292  
   293  func (m callmsg) From() common.Address { return m.CallMsg.From }
   294  func (m callmsg) Nonce() uint64        { return 0 }
   295  func (m callmsg) CheckNonce() bool     { return false }
   296  func (m callmsg) To() *common.Address  { return m.CallMsg.To }
   297  func (m callmsg) GasPrice() *big.Int   { return m.CallMsg.GasPrice }
   298  func (m callmsg) Gas() *big.Int        { return m.CallMsg.Gas }
   299  func (m callmsg) Value() *big.Int      { return m.CallMsg.Value }
   300  func (m callmsg) Data() []byte         { return m.CallMsg.Data }