simulated.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. val := statedb.GetState(contract, key)
  117. return val[:], nil
  118. }
  119. // TransactionReceipt returns the receipt of a transaction.
  120. func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  121. return core.GetReceipt(b.database, txHash), nil
  122. }
  123. // PendingCodeAt returns the code associated with an account in the pending state.
  124. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  125. b.mu.Lock()
  126. defer b.mu.Unlock()
  127. return b.pendingState.GetCode(contract), nil
  128. }
  129. // CallContract executes a contract call.
  130. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  131. b.mu.Lock()
  132. defer b.mu.Unlock()
  133. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  134. return nil, errBlockNumberUnsupported
  135. }
  136. state, err := b.blockchain.State()
  137. if err != nil {
  138. return nil, err
  139. }
  140. rval, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  141. return rval, err
  142. }
  143. // PendingCallContract executes a contract call on the pending state.
  144. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  145. b.mu.Lock()
  146. defer b.mu.Unlock()
  147. rval, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState.Copy())
  148. return rval, err
  149. }
  150. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  151. // the nonce currently pending for the account.
  152. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  153. b.mu.Lock()
  154. defer b.mu.Unlock()
  155. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  156. }
  157. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  158. // chain doens't have miners, we just return a gas price of 1 for any call.
  159. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  160. return big.NewInt(1), nil
  161. }
  162. // EstimateGas executes the requested code against the currently pending block/state and
  163. // returns the used amount of gas.
  164. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) {
  165. b.mu.Lock()
  166. defer b.mu.Unlock()
  167. _, gas, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState.Copy())
  168. return gas, err
  169. }
  170. // callContract implemens common code between normal and pending contract calls.
  171. // state is modified during execution, make sure to copy it if necessary.
  172. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, error) {
  173. // Ensure message is initialized properly.
  174. if call.GasPrice == nil {
  175. call.GasPrice = big.NewInt(1)
  176. }
  177. if call.Gas == nil || call.Gas.BitLen() == 0 {
  178. call.Gas = big.NewInt(50000000)
  179. }
  180. if call.Value == nil {
  181. call.Value = new(big.Int)
  182. }
  183. // Set infinite balance to the fake caller account.
  184. from := statedb.GetOrNewStateObject(call.From)
  185. from.SetBalance(common.MaxBig)
  186. // Execute the call.
  187. msg := callmsg{call}
  188. vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
  189. gaspool := new(core.GasPool).AddGas(common.MaxBig)
  190. ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  191. return ret, gasUsed, err
  192. }
  193. // SendTransaction updates the pending block to include the given transaction.
  194. // It panics if the transaction is invalid.
  195. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  196. b.mu.Lock()
  197. defer b.mu.Unlock()
  198. sender, err := tx.From()
  199. if err != nil {
  200. panic(fmt.Errorf("invalid transaction: %v", err))
  201. }
  202. nonce := b.pendingState.GetNonce(sender)
  203. if tx.Nonce() != nonce {
  204. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  205. }
  206. blocks, _ := core.GenerateChain(nil, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
  207. for _, tx := range b.pendingBlock.Transactions() {
  208. block.AddTx(tx)
  209. }
  210. block.AddTx(tx)
  211. })
  212. b.pendingBlock = blocks[0]
  213. b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
  214. return nil
  215. }
  216. // callmsg implements core.Message to allow passing it as a transaction simulator.
  217. type callmsg struct {
  218. ethereum.CallMsg
  219. }
  220. func (m callmsg) From() (common.Address, error) { return m.CallMsg.From, nil }
  221. func (m callmsg) FromFrontier() (common.Address, error) { return m.CallMsg.From, nil }
  222. func (m callmsg) Nonce() uint64 { return 0 }
  223. func (m callmsg) CheckNonce() bool { return false }
  224. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  225. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  226. func (m callmsg) Gas() *big.Int { return m.CallMsg.Gas }
  227. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  228. func (m callmsg) Data() []byte { return m.CallMsg.Data }