simulated.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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/bloombits"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/eth/filters"
  36. "github.com/ethereum/go-ethereum/ethdb"
  37. "github.com/ethereum/go-ethereum/event"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/rpc"
  40. )
  41. // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
  42. var _ bind.ContractBackend = (*SimulatedBackend)(nil)
  43. var errBlockNumberUnsupported = errors.New("SimulatedBackend cannot access blocks other than the latest block")
  44. var errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction")
  45. // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
  46. // the background. Its main purpose is to allow easily testing contract bindings.
  47. type SimulatedBackend struct {
  48. database ethdb.Database // In memory database to store our testing data
  49. blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
  50. mu sync.Mutex
  51. pendingBlock *types.Block // Currently pending block that will be imported on request
  52. pendingState *state.StateDB // Currently pending state that will be the active on on request
  53. events *filters.EventSystem // Event system for filtering log events live
  54. config *params.ChainConfig
  55. }
  56. // NewSimulatedBackend creates a new binding backend using a simulated blockchain
  57. // for testing purposes.
  58. func NewSimulatedBackend(alloc core.GenesisAlloc) *SimulatedBackend {
  59. database := ethdb.NewMemDatabase()
  60. genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc}
  61. genesis.MustCommit(database)
  62. blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{})
  63. backend := &SimulatedBackend{
  64. database: database,
  65. blockchain: blockchain,
  66. config: genesis.Config,
  67. events: filters.NewEventSystem(new(event.TypeMux), &filterBackend{database, blockchain}, false),
  68. }
  69. backend.rollback()
  70. return backend
  71. }
  72. // Commit imports all the pending transactions as a single block and starts a
  73. // fresh new state.
  74. func (b *SimulatedBackend) Commit() {
  75. b.mu.Lock()
  76. defer b.mu.Unlock()
  77. if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
  78. panic(err) // This cannot happen unless the simulator is wrong, fail in that case
  79. }
  80. b.rollback()
  81. }
  82. // Rollback aborts all pending transactions, reverting to the last committed state.
  83. func (b *SimulatedBackend) Rollback() {
  84. b.mu.Lock()
  85. defer b.mu.Unlock()
  86. b.rollback()
  87. }
  88. func (b *SimulatedBackend) rollback() {
  89. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
  90. statedb, _ := b.blockchain.State()
  91. b.pendingBlock = blocks[0]
  92. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  93. }
  94. // CodeAt returns the code associated with a certain account in the blockchain.
  95. func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
  96. b.mu.Lock()
  97. defer b.mu.Unlock()
  98. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  99. return nil, errBlockNumberUnsupported
  100. }
  101. statedb, _ := b.blockchain.State()
  102. return statedb.GetCode(contract), nil
  103. }
  104. // BalanceAt returns the wei balance of a certain account in the blockchain.
  105. func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
  106. b.mu.Lock()
  107. defer b.mu.Unlock()
  108. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  109. return nil, errBlockNumberUnsupported
  110. }
  111. statedb, _ := b.blockchain.State()
  112. return statedb.GetBalance(contract), nil
  113. }
  114. // NonceAt returns the nonce of a certain account in the blockchain.
  115. func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
  116. b.mu.Lock()
  117. defer b.mu.Unlock()
  118. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  119. return 0, errBlockNumberUnsupported
  120. }
  121. statedb, _ := b.blockchain.State()
  122. return statedb.GetNonce(contract), nil
  123. }
  124. // StorageAt returns the value of key in the storage of an account in the blockchain.
  125. func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
  126. b.mu.Lock()
  127. defer b.mu.Unlock()
  128. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  129. return nil, errBlockNumberUnsupported
  130. }
  131. statedb, _ := b.blockchain.State()
  132. val := statedb.GetState(contract, key)
  133. return val[:], nil
  134. }
  135. // TransactionReceipt returns the receipt of a transaction.
  136. func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  137. receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash)
  138. return receipt, nil
  139. }
  140. // PendingCodeAt returns the code associated with an account in the pending state.
  141. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  142. b.mu.Lock()
  143. defer b.mu.Unlock()
  144. return b.pendingState.GetCode(contract), nil
  145. }
  146. // CallContract executes a contract call.
  147. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  148. b.mu.Lock()
  149. defer b.mu.Unlock()
  150. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  151. return nil, errBlockNumberUnsupported
  152. }
  153. state, err := b.blockchain.State()
  154. if err != nil {
  155. return nil, err
  156. }
  157. rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  158. return rval, err
  159. }
  160. // PendingCallContract executes a contract call on the pending state.
  161. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  162. b.mu.Lock()
  163. defer b.mu.Unlock()
  164. defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
  165. rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  166. return rval, err
  167. }
  168. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  169. // the nonce currently pending for the account.
  170. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  171. b.mu.Lock()
  172. defer b.mu.Unlock()
  173. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  174. }
  175. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  176. // chain doens't have miners, we just return a gas price of 1 for any call.
  177. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  178. return big.NewInt(1), nil
  179. }
  180. // EstimateGas executes the requested code against the currently pending block/state and
  181. // returns the used amount of gas.
  182. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
  183. b.mu.Lock()
  184. defer b.mu.Unlock()
  185. // Determine the lowest and highest possible gas limits to binary search in between
  186. var (
  187. lo uint64 = params.TxGas - 1
  188. hi uint64
  189. cap uint64
  190. )
  191. if call.Gas >= params.TxGas {
  192. hi = call.Gas
  193. } else {
  194. hi = b.pendingBlock.GasLimit()
  195. }
  196. cap = hi
  197. // Create a helper to check if a gas allowance results in an executable transaction
  198. executable := func(gas uint64) bool {
  199. call.Gas = gas
  200. snapshot := b.pendingState.Snapshot()
  201. _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  202. b.pendingState.RevertToSnapshot(snapshot)
  203. if err != nil || failed {
  204. return false
  205. }
  206. return true
  207. }
  208. // Execute the binary search and hone in on an executable gas limit
  209. for lo+1 < hi {
  210. mid := (hi + lo) / 2
  211. if !executable(mid) {
  212. lo = mid
  213. } else {
  214. hi = mid
  215. }
  216. }
  217. // Reject the transaction as invalid if it still fails at the highest allowance
  218. if hi == cap {
  219. if !executable(hi) {
  220. return 0, errGasEstimationFailed
  221. }
  222. }
  223. return hi, nil
  224. }
  225. // callContract implements common code between normal and pending contract calls.
  226. // state is modified during execution, make sure to copy it if necessary.
  227. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
  228. // Ensure message is initialized properly.
  229. if call.GasPrice == nil {
  230. call.GasPrice = big.NewInt(1)
  231. }
  232. if call.Gas == 0 {
  233. call.Gas = 50000000
  234. }
  235. if call.Value == nil {
  236. call.Value = new(big.Int)
  237. }
  238. // Set infinite balance to the fake caller account.
  239. from := statedb.GetOrNewStateObject(call.From)
  240. from.SetBalance(math.MaxBig256)
  241. // Execute the call.
  242. msg := callmsg{call}
  243. evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
  244. // Create a new environment which holds all relevant information
  245. // about the transaction and calling mechanisms.
  246. vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
  247. gaspool := new(core.GasPool).AddGas(math.MaxUint64)
  248. return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  249. }
  250. // SendTransaction updates the pending block to include the given transaction.
  251. // It panics if the transaction is invalid.
  252. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  253. b.mu.Lock()
  254. defer b.mu.Unlock()
  255. sender, err := types.Sender(types.HomesteadSigner{}, tx)
  256. if err != nil {
  257. panic(fmt.Errorf("invalid transaction: %v", err))
  258. }
  259. nonce := b.pendingState.GetNonce(sender)
  260. if tx.Nonce() != nonce {
  261. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  262. }
  263. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  264. for _, tx := range b.pendingBlock.Transactions() {
  265. block.AddTxWithChain(b.blockchain, tx)
  266. }
  267. block.AddTxWithChain(b.blockchain, tx)
  268. })
  269. statedb, _ := b.blockchain.State()
  270. b.pendingBlock = blocks[0]
  271. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  272. return nil
  273. }
  274. // FilterLogs executes a log filter operation, blocking during execution and
  275. // returning all the results in one batch.
  276. //
  277. // TODO(karalabe): Deprecate when the subscription one can return past data too.
  278. func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
  279. // Initialize unset filter boundaried to run from genesis to chain head
  280. from := int64(0)
  281. if query.FromBlock != nil {
  282. from = query.FromBlock.Int64()
  283. }
  284. to := int64(-1)
  285. if query.ToBlock != nil {
  286. to = query.ToBlock.Int64()
  287. }
  288. // Construct and execute the filter
  289. filter := filters.New(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
  290. logs, err := filter.Logs(ctx)
  291. if err != nil {
  292. return nil, err
  293. }
  294. res := make([]types.Log, len(logs))
  295. for i, log := range logs {
  296. res[i] = *log
  297. }
  298. return res, nil
  299. }
  300. // SubscribeFilterLogs creates a background log filtering operation, returning a
  301. // subscription immediately, which can be used to stream the found events.
  302. func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
  303. // Subscribe to contract events
  304. sink := make(chan []*types.Log)
  305. sub, err := b.events.SubscribeLogs(query, sink)
  306. if err != nil {
  307. return nil, err
  308. }
  309. // Since we're getting logs in batches, we need to flatten them into a plain stream
  310. return event.NewSubscription(func(quit <-chan struct{}) error {
  311. defer sub.Unsubscribe()
  312. for {
  313. select {
  314. case logs := <-sink:
  315. for _, log := range logs {
  316. select {
  317. case ch <- *log:
  318. case err := <-sub.Err():
  319. return err
  320. case <-quit:
  321. return nil
  322. }
  323. }
  324. case err := <-sub.Err():
  325. return err
  326. case <-quit:
  327. return nil
  328. }
  329. }
  330. }), nil
  331. }
  332. // AdjustTime adds a time shift to the simulated clock.
  333. func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
  334. b.mu.Lock()
  335. defer b.mu.Unlock()
  336. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  337. for _, tx := range b.pendingBlock.Transactions() {
  338. block.AddTx(tx)
  339. }
  340. block.OffsetTime(int64(adjustment.Seconds()))
  341. })
  342. statedb, _ := b.blockchain.State()
  343. b.pendingBlock = blocks[0]
  344. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  345. return nil
  346. }
  347. // callmsg implements core.Message to allow passing it as a transaction simulator.
  348. type callmsg struct {
  349. ethereum.CallMsg
  350. }
  351. func (m callmsg) From() common.Address { return m.CallMsg.From }
  352. func (m callmsg) Nonce() uint64 { return 0 }
  353. func (m callmsg) CheckNonce() bool { return false }
  354. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  355. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  356. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  357. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  358. func (m callmsg) Data() []byte { return m.CallMsg.Data }
  359. // filterBackend implements filters.Backend to support filtering for logs without
  360. // taking bloom-bits acceleration structures into account.
  361. type filterBackend struct {
  362. db ethdb.Database
  363. bc *core.BlockChain
  364. }
  365. func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
  366. func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
  367. func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
  368. if block == rpc.LatestBlockNumber {
  369. return fb.bc.CurrentHeader(), nil
  370. }
  371. return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
  372. }
  373. func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
  374. number := rawdb.ReadHeaderNumber(fb.db, hash)
  375. if number == nil {
  376. return nil, nil
  377. }
  378. return rawdb.ReadReceipts(fb.db, hash, *number), nil
  379. }
  380. func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
  381. number := rawdb.ReadHeaderNumber(fb.db, hash)
  382. if number == nil {
  383. return nil, nil
  384. }
  385. receipts := rawdb.ReadReceipts(fb.db, hash, *number)
  386. if receipts == nil {
  387. return nil, nil
  388. }
  389. logs := make([][]*types.Log, len(receipts))
  390. for i, receipt := range receipts {
  391. logs[i] = receipt.Logs
  392. }
  393. return logs, nil
  394. }
  395. func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  396. return event.NewSubscription(func(quit <-chan struct{}) error {
  397. <-quit
  398. return nil
  399. })
  400. }
  401. func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  402. return fb.bc.SubscribeChainEvent(ch)
  403. }
  404. func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  405. return fb.bc.SubscribeRemovedLogsEvent(ch)
  406. }
  407. func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  408. return fb.bc.SubscribeLogsEvent(ch)
  409. }
  410. func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
  411. func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
  412. panic("not supported")
  413. }