simulated.go 10 KB

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