simulated.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Copyright 2016 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. package backends
  17. import (
  18. "fmt"
  19. "math/big"
  20. "github.com/ethereum/go-ethereum"
  21. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/state"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/core/vm"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/event"
  29. "golang.org/x/net/context"
  30. )
  31. // Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)
  32. var chainConfig = &core.ChainConfig{HomesteadBlock: big.NewInt(0)}
  33. // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
  34. var _ bind.ContractBackend = (*SimulatedBackend)(nil)
  35. // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
  36. // the background. Its main purpose is to allow easily testing contract bindings.
  37. type SimulatedBackend struct {
  38. database ethdb.Database // In memory database to store our testing data
  39. blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
  40. pendingBlock *types.Block // Currently pending block that will be imported on request
  41. pendingState *state.StateDB // Currently pending state that will be the active on on request
  42. }
  43. // NewSimulatedBackend creates a new binding backend using a simulated blockchain
  44. // for testing purposes.
  45. func NewSimulatedBackend(accounts ...core.GenesisAccount) *SimulatedBackend {
  46. database, _ := ethdb.NewMemDatabase()
  47. core.WriteGenesisBlockForTesting(database, accounts...)
  48. blockchain, _ := core.NewBlockChain(database, chainConfig, new(core.FakePow), new(event.TypeMux))
  49. backend := &SimulatedBackend{
  50. database: database,
  51. blockchain: blockchain,
  52. }
  53. backend.Rollback()
  54. return backend
  55. }
  56. // Commit imports all the pending transactions as a single block and starts a
  57. // fresh new state.
  58. func (b *SimulatedBackend) Commit() {
  59. if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
  60. panic(err) // This cannot happen unless the simulator is wrong, fail in that case
  61. }
  62. b.Rollback()
  63. }
  64. // Rollback aborts all pending transactions, reverting to the last committed state.
  65. func (b *SimulatedBackend) Rollback() {
  66. blocks, _ := core.GenerateChain(nil, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {})
  67. b.pendingBlock = blocks[0]
  68. b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
  69. }
  70. // CodeAt implements ChainStateReader.CodeAt, returning the code associated with
  71. // a certain account at a given block number in the blockchain.
  72. func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
  73. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  74. return nil, fmt.Errorf("SimulatedBackend cannot access blocks other than the latest block")
  75. }
  76. statedb, _ := b.blockchain.State()
  77. return statedb.GetCode(contract), nil
  78. }
  79. // PendingCodeAt implements PendingStateReader.PendingCodeAt, returning the
  80. // code associated with a certain account in the pending state of the blockchain.
  81. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  82. return b.pendingState.GetCode(contract), nil
  83. }
  84. // CallContract executes a contract call.
  85. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  86. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  87. return nil, fmt.Errorf("SimulatedBackend cannot access blocks other than the latest block")
  88. }
  89. state, err := b.blockchain.State()
  90. if err != nil {
  91. return nil, err
  92. }
  93. rval, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  94. return rval, err
  95. }
  96. // PendingCallContract executes a contract call on the pending state.
  97. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  98. rval, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState.Copy())
  99. return rval, err
  100. }
  101. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  102. // the nonce currently pending for the account.
  103. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  104. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  105. }
  106. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  107. // chain doens't have miners, we just return a gas price of 1 for any call.
  108. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  109. return big.NewInt(1), nil
  110. }
  111. // EstimateGas executes the requested code against the currently pending block/state and
  112. // returns the used amount of gas.
  113. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) {
  114. _, gas, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState.Copy())
  115. return gas, err
  116. }
  117. // callContract implemens common code between normal and pending contract calls.
  118. // state is modified during execution, make sure to copy it if necessary.
  119. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, error) {
  120. // Ensure message is initialized properly.
  121. if call.GasPrice == nil {
  122. call.GasPrice = big.NewInt(1)
  123. }
  124. if call.Gas == nil || call.Gas.BitLen() == 0 {
  125. call.Gas = big.NewInt(50000000)
  126. }
  127. if call.Value == nil {
  128. call.Value = new(big.Int)
  129. }
  130. // Set infinite balance to the fake caller account.
  131. from := statedb.GetOrNewStateObject(call.From)
  132. from.SetBalance(common.MaxBig)
  133. // Execute the call.
  134. msg := callmsg{call}
  135. vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
  136. gaspool := new(core.GasPool).AddGas(common.MaxBig)
  137. ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  138. return ret, gasUsed, err
  139. }
  140. // SendTransaction updates the pending block to include the given transaction.
  141. // It panics if the transaction is invalid.
  142. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  143. sender, err := tx.From()
  144. if err != nil {
  145. panic(fmt.Errorf("invalid transaction: %v", err))
  146. }
  147. nonce := b.pendingState.GetNonce(sender)
  148. if tx.Nonce() != nonce {
  149. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  150. }
  151. blocks, _ := core.GenerateChain(nil, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
  152. for _, tx := range b.pendingBlock.Transactions() {
  153. block.AddTx(tx)
  154. }
  155. block.AddTx(tx)
  156. })
  157. b.pendingBlock = blocks[0]
  158. b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
  159. return nil
  160. }
  161. // callmsg implements core.Message to allow passing it as a transaction simulator.
  162. type callmsg struct {
  163. ethereum.CallMsg
  164. }
  165. func (m callmsg) From() (common.Address, error) { return m.CallMsg.From, nil }
  166. func (m callmsg) FromFrontier() (common.Address, error) { return m.CallMsg.From, nil }
  167. func (m callmsg) Nonce() uint64 { return 0 }
  168. func (m callmsg) CheckNonce() bool { return false }
  169. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  170. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  171. func (m callmsg) Gas() *big.Int { return m.CallMsg.Gas }
  172. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  173. func (m callmsg) Data() []byte { return m.CallMsg.Data }