simulated.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. "math/big"
  19. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core"
  22. "github.com/ethereum/go-ethereum/core/state"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/core/vm"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/event"
  27. "golang.org/x/net/context"
  28. )
  29. // Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)
  30. var chainConfig = &core.ChainConfig{HomesteadBlock: big.NewInt(0)}
  31. // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
  32. var _ bind.ContractBackend = (*SimulatedBackend)(nil)
  33. // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
  34. // the background. Its main purpose is to allow easily testing contract bindings.
  35. type SimulatedBackend struct {
  36. database ethdb.Database // In memory database to store our testing data
  37. blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
  38. pendingBlock *types.Block // Currently pending block that will be imported on request
  39. pendingState *state.StateDB // Currently pending state that will be the active on on request
  40. }
  41. // NewSimulatedBackend creates a new binding backend using a simulated blockchain
  42. // for testing purposes.
  43. func NewSimulatedBackend(accounts ...core.GenesisAccount) *SimulatedBackend {
  44. database, _ := ethdb.NewMemDatabase()
  45. core.WriteGenesisBlockForTesting(database, accounts...)
  46. blockchain, _ := core.NewBlockChain(database, chainConfig, new(core.FakePow), new(event.TypeMux))
  47. backend := &SimulatedBackend{
  48. database: database,
  49. blockchain: blockchain,
  50. }
  51. backend.Rollback()
  52. return backend
  53. }
  54. // Commit imports all the pending transactions as a single block and starts a
  55. // fresh new state.
  56. func (b *SimulatedBackend) Commit() {
  57. if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
  58. panic(err) // This cannot happen unless the simulator is wrong, fail in that case
  59. }
  60. b.Rollback()
  61. }
  62. // Rollback aborts all pending transactions, reverting to the last committed state.
  63. func (b *SimulatedBackend) Rollback() {
  64. blocks, _ := core.GenerateChain(b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {})
  65. b.pendingBlock = blocks[0]
  66. b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
  67. }
  68. // HasCode implements ContractVerifier.HasCode, checking whether there is any
  69. // code associated with a certain account in the blockchain.
  70. func (b *SimulatedBackend) HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error) {
  71. if pending {
  72. return len(b.pendingState.GetCode(contract)) > 0, nil
  73. }
  74. statedb, _ := b.blockchain.State()
  75. return len(statedb.GetCode(contract)) > 0, nil
  76. }
  77. // ContractCall implements ContractCaller.ContractCall, executing the specified
  78. // contract with the given input data.
  79. func (b *SimulatedBackend) ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error) {
  80. // Create a copy of the current state db to screw around with
  81. var (
  82. block *types.Block
  83. statedb *state.StateDB
  84. )
  85. if pending {
  86. block, statedb = b.pendingBlock, b.pendingState.Copy()
  87. } else {
  88. block = b.blockchain.CurrentBlock()
  89. statedb, _ = b.blockchain.State()
  90. }
  91. // If there's no code to interact with, respond with an appropriate error
  92. if code := statedb.GetCode(contract); len(code) == 0 {
  93. return nil, bind.ErrNoCode
  94. }
  95. // Set infinite balance to the a fake caller account
  96. from := statedb.GetOrNewStateObject(common.Address{})
  97. from.SetBalance(common.MaxBig)
  98. // Assemble the call invocation to measure the gas usage
  99. msg := callmsg{
  100. from: from,
  101. to: &contract,
  102. gasPrice: new(big.Int),
  103. gasLimit: common.MaxBig,
  104. value: new(big.Int),
  105. data: data,
  106. }
  107. // Execute the call and return
  108. vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
  109. gaspool := new(core.GasPool).AddGas(common.MaxBig)
  110. out, _, err := core.ApplyMessage(vmenv, msg, gaspool)
  111. return out, err
  112. }
  113. // PendingAccountNonce implements ContractTransactor.PendingAccountNonce, retrieving
  114. // the nonce currently pending for the account.
  115. func (b *SimulatedBackend) PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error) {
  116. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  117. }
  118. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  119. // chain doens't have miners, we just return a gas price of 1 for any call.
  120. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  121. return big.NewInt(1), nil
  122. }
  123. // EstimateGasLimit implements ContractTransactor.EstimateGasLimit, executing the
  124. // requested code against the currently pending block/state and returning the used
  125. // gas.
  126. func (b *SimulatedBackend) EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
  127. // Create a copy of the currently pending state db to screw around with
  128. var (
  129. block = b.pendingBlock
  130. statedb = b.pendingState.Copy()
  131. )
  132. // If there's no code to interact with, respond with an appropriate error
  133. if contract != nil {
  134. if code := statedb.GetCode(*contract); len(code) == 0 {
  135. return nil, bind.ErrNoCode
  136. }
  137. }
  138. // Set infinite balance to the a fake caller account
  139. from := statedb.GetOrNewStateObject(sender)
  140. from.SetBalance(common.MaxBig)
  141. // Assemble the call invocation to measure the gas usage
  142. msg := callmsg{
  143. from: from,
  144. to: contract,
  145. gasPrice: new(big.Int),
  146. gasLimit: common.MaxBig,
  147. value: value,
  148. data: data,
  149. }
  150. // Execute the call and return
  151. vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
  152. gaspool := new(core.GasPool).AddGas(common.MaxBig)
  153. _, gas, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  154. return gas, err
  155. }
  156. // SendTransaction implements ContractTransactor.SendTransaction, delegating the raw
  157. // transaction injection to the remote node.
  158. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  159. blocks, _ := core.GenerateChain(b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
  160. for _, tx := range b.pendingBlock.Transactions() {
  161. block.AddTx(tx)
  162. }
  163. block.AddTx(tx)
  164. })
  165. b.pendingBlock = blocks[0]
  166. b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
  167. return nil
  168. }
  169. // callmsg implements core.Message to allow passing it as a transaction simulator.
  170. type callmsg struct {
  171. from *state.StateObject
  172. to *common.Address
  173. gasLimit *big.Int
  174. gasPrice *big.Int
  175. value *big.Int
  176. data []byte
  177. }
  178. func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
  179. func (m callmsg) FromFrontier() (common.Address, error) { return m.from.Address(), nil }
  180. func (m callmsg) Nonce() uint64 { return 0 }
  181. func (m callmsg) CheckNonce() bool { return false }
  182. func (m callmsg) To() *common.Address { return m.to }
  183. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  184. func (m callmsg) Gas() *big.Int { return m.gasLimit }
  185. func (m callmsg) Value() *big.Int { return m.value }
  186. func (m callmsg) Data() []byte { return m.data }