simulated.go 10 KB

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