simulated.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. "context"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/math"
  28. "github.com/ethereum/go-ethereum/consensus/ethash"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/core/vm"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/params"
  35. )
  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. var errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction")
  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(alloc core.GenesisAlloc) *SimulatedBackend {
  53. database, _ := ethdb.NewMemDatabase()
  54. genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc}
  55. genesis.MustCommit(database)
  56. blockchain, _ := core.NewBlockChain(database, genesis.Config, ethash.NewFaker(), vm.Config{})
  57. backend := &SimulatedBackend{database: database, blockchain: blockchain, config: genesis.Config}
  58. backend.rollback()
  59. return backend
  60. }
  61. // Commit imports all the pending transactions as a single block and starts a
  62. // fresh new state.
  63. func (b *SimulatedBackend) Commit() {
  64. b.mu.Lock()
  65. defer b.mu.Unlock()
  66. if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
  67. panic(err) // This cannot happen unless the simulator is wrong, fail in that case
  68. }
  69. b.rollback()
  70. }
  71. // Rollback aborts all pending transactions, reverting to the last committed state.
  72. func (b *SimulatedBackend) Rollback() {
  73. b.mu.Lock()
  74. defer b.mu.Unlock()
  75. b.rollback()
  76. }
  77. func (b *SimulatedBackend) rollback() {
  78. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
  79. b.pendingBlock = blocks[0]
  80. b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
  81. }
  82. // CodeAt returns the code associated with a certain account in the blockchain.
  83. func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
  84. b.mu.Lock()
  85. defer b.mu.Unlock()
  86. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  87. return nil, errBlockNumberUnsupported
  88. }
  89. statedb, _ := b.blockchain.State()
  90. return statedb.GetCode(contract), nil
  91. }
  92. // BalanceAt returns the wei balance of a certain account in the blockchain.
  93. func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
  94. b.mu.Lock()
  95. defer b.mu.Unlock()
  96. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  97. return nil, errBlockNumberUnsupported
  98. }
  99. statedb, _ := b.blockchain.State()
  100. return statedb.GetBalance(contract), nil
  101. }
  102. // NonceAt returns the nonce of a certain account in the blockchain.
  103. func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
  104. b.mu.Lock()
  105. defer b.mu.Unlock()
  106. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  107. return 0, errBlockNumberUnsupported
  108. }
  109. statedb, _ := b.blockchain.State()
  110. return statedb.GetNonce(contract), nil
  111. }
  112. // StorageAt returns the value of key in the storage of an account in the blockchain.
  113. func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
  114. b.mu.Lock()
  115. defer b.mu.Unlock()
  116. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  117. return nil, errBlockNumberUnsupported
  118. }
  119. statedb, _ := b.blockchain.State()
  120. val := statedb.GetState(contract, key)
  121. return val[:], nil
  122. }
  123. // TransactionReceipt returns the receipt of a transaction.
  124. func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  125. receipt, _, _, _ := core.GetReceipt(b.database, txHash)
  126. return receipt, nil
  127. }
  128. // PendingCodeAt returns the code associated with an account in the pending state.
  129. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  130. b.mu.Lock()
  131. defer b.mu.Unlock()
  132. return b.pendingState.GetCode(contract), nil
  133. }
  134. // CallContract executes a contract call.
  135. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  136. b.mu.Lock()
  137. defer b.mu.Unlock()
  138. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  139. return nil, errBlockNumberUnsupported
  140. }
  141. state, err := b.blockchain.State()
  142. if err != nil {
  143. return nil, err
  144. }
  145. rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  146. return rval, err
  147. }
  148. // PendingCallContract executes a contract call on the pending state.
  149. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  150. b.mu.Lock()
  151. defer b.mu.Unlock()
  152. defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
  153. rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  154. return rval, err
  155. }
  156. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  157. // the nonce currently pending for the account.
  158. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  159. b.mu.Lock()
  160. defer b.mu.Unlock()
  161. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  162. }
  163. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  164. // chain doens't have miners, we just return a gas price of 1 for any call.
  165. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  166. return big.NewInt(1), nil
  167. }
  168. // EstimateGas executes the requested code against the currently pending block/state and
  169. // returns the used amount of gas.
  170. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
  171. b.mu.Lock()
  172. defer b.mu.Unlock()
  173. // Determine the lowest and highest possible gas limits to binary search in between
  174. var (
  175. lo uint64 = params.TxGas - 1
  176. hi uint64
  177. cap uint64
  178. )
  179. if call.Gas >= params.TxGas {
  180. hi = call.Gas
  181. } else {
  182. hi = b.pendingBlock.GasLimit()
  183. }
  184. cap = hi
  185. // Create a helper to check if a gas allowance results in an executable transaction
  186. executable := func(gas uint64) bool {
  187. call.Gas = gas
  188. snapshot := b.pendingState.Snapshot()
  189. _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  190. b.pendingState.RevertToSnapshot(snapshot)
  191. if err != nil || failed {
  192. return false
  193. }
  194. return true
  195. }
  196. // Execute the binary search and hone in on an executable gas limit
  197. for lo+1 < hi {
  198. mid := (hi + lo) / 2
  199. if !executable(mid) {
  200. lo = mid
  201. } else {
  202. hi = mid
  203. }
  204. }
  205. // Reject the transaction as invalid if it still fails at the highest allowance
  206. if hi == cap {
  207. if !executable(hi) {
  208. return 0, errGasEstimationFailed
  209. }
  210. }
  211. return hi, nil
  212. }
  213. // callContract implemens common code between normal and pending contract calls.
  214. // state is modified during execution, make sure to copy it if necessary.
  215. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
  216. // Ensure message is initialized properly.
  217. if call.GasPrice == nil {
  218. call.GasPrice = big.NewInt(1)
  219. }
  220. if call.Gas == 0 {
  221. call.Gas = 50000000
  222. }
  223. if call.Value == nil {
  224. call.Value = new(big.Int)
  225. }
  226. // Set infinite balance to the fake caller account.
  227. from := statedb.GetOrNewStateObject(call.From)
  228. from.SetBalance(math.MaxBig256)
  229. // Execute the call.
  230. msg := callmsg{call}
  231. evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
  232. // Create a new environment which holds all relevant information
  233. // about the transaction and calling mechanisms.
  234. vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
  235. gaspool := new(core.GasPool).AddGas(math.MaxUint64)
  236. return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  237. }
  238. // SendTransaction updates the pending block to include the given transaction.
  239. // It panics if the transaction is invalid.
  240. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  241. b.mu.Lock()
  242. defer b.mu.Unlock()
  243. sender, err := types.Sender(types.HomesteadSigner{}, tx)
  244. if err != nil {
  245. panic(fmt.Errorf("invalid transaction: %v", err))
  246. }
  247. nonce := b.pendingState.GetNonce(sender)
  248. if tx.Nonce() != nonce {
  249. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  250. }
  251. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  252. for _, tx := range b.pendingBlock.Transactions() {
  253. block.AddTx(tx)
  254. }
  255. block.AddTx(tx)
  256. })
  257. b.pendingBlock = blocks[0]
  258. b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
  259. return nil
  260. }
  261. // JumpTimeInSeconds adds skip seconds to the clock
  262. func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
  263. b.mu.Lock()
  264. defer b.mu.Unlock()
  265. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  266. for _, tx := range b.pendingBlock.Transactions() {
  267. block.AddTx(tx)
  268. }
  269. block.OffsetTime(int64(adjustment.Seconds()))
  270. })
  271. b.pendingBlock = blocks[0]
  272. b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
  273. return nil
  274. }
  275. // callmsg implements core.Message to allow passing it as a transaction simulator.
  276. type callmsg struct {
  277. ethereum.CallMsg
  278. }
  279. func (m callmsg) From() common.Address { return m.CallMsg.From }
  280. func (m callmsg) Nonce() uint64 { return 0 }
  281. func (m callmsg) CheckNonce() bool { return false }
  282. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  283. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  284. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  285. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  286. func (m callmsg) Data() []byte { return m.CallMsg.Data }