simulated.go 11 KB

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