simulated.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. "github.com/ethereum/go-ethereum/params"
  28. )
  29. // Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)
  30. var chainConfig = &core.ChainConfig{HomesteadBlock: params.MainNetHomesteadBlock}
  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. // ContractCall implements ContractCaller.ContractCall, executing the specified
  69. // contract with the given input data.
  70. func (b *SimulatedBackend) ContractCall(contract common.Address, data []byte, pending bool) ([]byte, error) {
  71. // Create a copy of the current state db to screw around with
  72. var (
  73. block *types.Block
  74. statedb *state.StateDB
  75. )
  76. if pending {
  77. block, statedb = b.pendingBlock, b.pendingState.Copy()
  78. } else {
  79. block = b.blockchain.CurrentBlock()
  80. statedb, _ = b.blockchain.State()
  81. }
  82. // Set infinite balance to the a fake caller account
  83. from := statedb.GetOrNewStateObject(common.Address{})
  84. from.SetBalance(common.MaxBig)
  85. // Assemble the call invocation to measure the gas usage
  86. msg := callmsg{
  87. from: from,
  88. to: &contract,
  89. gasPrice: new(big.Int),
  90. gasLimit: common.MaxBig,
  91. value: new(big.Int),
  92. data: data,
  93. }
  94. // Execute the call and return
  95. vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
  96. gaspool := new(core.GasPool).AddGas(common.MaxBig)
  97. out, _, err := core.ApplyMessage(vmenv, msg, gaspool)
  98. return out, err
  99. }
  100. // PendingAccountNonce implements ContractTransactor.PendingAccountNonce, retrieving
  101. // the nonce currently pending for the account.
  102. func (b *SimulatedBackend) PendingAccountNonce(account common.Address) (uint64, error) {
  103. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  104. }
  105. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  106. // chain doens't have miners, we just return a gas price of 1 for any call.
  107. func (b *SimulatedBackend) SuggestGasPrice() (*big.Int, error) {
  108. return big.NewInt(1), nil
  109. }
  110. // EstimateGasLimit implements ContractTransactor.EstimateGasLimit, executing the
  111. // requested code against the currently pending block/state and returning the used
  112. // gas.
  113. func (b *SimulatedBackend) EstimateGasLimit(sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
  114. // Create a copy of the currently pending state db to screw around with
  115. var (
  116. block = b.pendingBlock
  117. statedb = b.pendingState.Copy()
  118. )
  119. // Set infinite balance to the a fake caller account
  120. from := statedb.GetOrNewStateObject(sender)
  121. from.SetBalance(common.MaxBig)
  122. // Assemble the call invocation to measure the gas usage
  123. msg := callmsg{
  124. from: from,
  125. to: contract,
  126. gasPrice: new(big.Int),
  127. gasLimit: common.MaxBig,
  128. value: value,
  129. data: data,
  130. }
  131. // Execute the call and return
  132. vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
  133. gaspool := new(core.GasPool).AddGas(common.MaxBig)
  134. _, gas, err := core.ApplyMessage(vmenv, msg, gaspool)
  135. return gas, err
  136. }
  137. // SendTransaction implements ContractTransactor.SendTransaction, delegating the raw
  138. // transaction injection to the remote node.
  139. func (b *SimulatedBackend) SendTransaction(tx *types.Transaction) error {
  140. blocks, _ := core.GenerateChain(b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
  141. for _, tx := range b.pendingBlock.Transactions() {
  142. block.AddTx(tx)
  143. }
  144. block.AddTx(tx)
  145. })
  146. b.pendingBlock = blocks[0]
  147. b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
  148. return nil
  149. }
  150. // callmsg implements core.Message to allow passing it as a transaction simulator.
  151. type callmsg struct {
  152. from *state.StateObject
  153. to *common.Address
  154. gasLimit *big.Int
  155. gasPrice *big.Int
  156. value *big.Int
  157. data []byte
  158. }
  159. func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
  160. func (m callmsg) FromFrontier() (common.Address, error) { return m.from.Address(), nil }
  161. func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
  162. func (m callmsg) To() *common.Address { return m.to }
  163. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  164. func (m callmsg) Gas() *big.Int { return m.gasLimit }
  165. func (m callmsg) Value() *big.Int { return m.value }
  166. func (m callmsg) Data() []byte { return m.data }