simulated.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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, gasLimit uint64) *SimulatedBackend {
  59. database := rawdb.NewMemoryDatabase()
  60. genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc}
  61. genesis.MustCommit(database)
  62. blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil)
  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, b.config)
  138. return receipt, nil
  139. }
  140. // TransactionByHash checks the pool of pending transactions in addition to the
  141. // blockchain. The isPending return value indicates whether the transaction has been
  142. // mined yet. Note that the transaction may not be part of the canonical chain even if
  143. // it's not pending.
  144. func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
  145. b.mu.Lock()
  146. defer b.mu.Unlock()
  147. tx := b.pendingBlock.Transaction(txHash)
  148. if tx != nil {
  149. return tx, true, nil
  150. }
  151. tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash)
  152. if tx != nil {
  153. return tx, false, nil
  154. }
  155. return nil, false, ethereum.NotFound
  156. }
  157. // PendingCodeAt returns the code associated with an account in the pending state.
  158. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  159. b.mu.Lock()
  160. defer b.mu.Unlock()
  161. return b.pendingState.GetCode(contract), nil
  162. }
  163. // CallContract executes a contract call.
  164. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  165. b.mu.Lock()
  166. defer b.mu.Unlock()
  167. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  168. return nil, errBlockNumberUnsupported
  169. }
  170. state, err := b.blockchain.State()
  171. if err != nil {
  172. return nil, err
  173. }
  174. rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  175. return rval, err
  176. }
  177. // PendingCallContract executes a contract call on the pending state.
  178. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  179. b.mu.Lock()
  180. defer b.mu.Unlock()
  181. defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
  182. rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  183. return rval, err
  184. }
  185. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  186. // the nonce currently pending for the account.
  187. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  188. b.mu.Lock()
  189. defer b.mu.Unlock()
  190. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  191. }
  192. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  193. // chain doesn't have miners, we just return a gas price of 1 for any call.
  194. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  195. return big.NewInt(1), nil
  196. }
  197. // EstimateGas executes the requested code against the currently pending block/state and
  198. // returns the used amount of gas.
  199. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
  200. b.mu.Lock()
  201. defer b.mu.Unlock()
  202. // Determine the lowest and highest possible gas limits to binary search in between
  203. var (
  204. lo uint64 = params.TxGas - 1
  205. hi uint64
  206. cap uint64
  207. )
  208. if call.Gas >= params.TxGas {
  209. hi = call.Gas
  210. } else {
  211. hi = b.pendingBlock.GasLimit()
  212. }
  213. cap = hi
  214. // Create a helper to check if a gas allowance results in an executable transaction
  215. executable := func(gas uint64) bool {
  216. call.Gas = gas
  217. snapshot := b.pendingState.Snapshot()
  218. _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  219. b.pendingState.RevertToSnapshot(snapshot)
  220. if err != nil || failed {
  221. return false
  222. }
  223. return true
  224. }
  225. // Execute the binary search and hone in on an executable gas limit
  226. for lo+1 < hi {
  227. mid := (hi + lo) / 2
  228. if !executable(mid) {
  229. lo = mid
  230. } else {
  231. hi = mid
  232. }
  233. }
  234. // Reject the transaction as invalid if it still fails at the highest allowance
  235. if hi == cap {
  236. if !executable(hi) {
  237. return 0, errGasEstimationFailed
  238. }
  239. }
  240. return hi, nil
  241. }
  242. // callContract implements common code between normal and pending contract calls.
  243. // state is modified during execution, make sure to copy it if necessary.
  244. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
  245. // Ensure message is initialized properly.
  246. if call.GasPrice == nil {
  247. call.GasPrice = big.NewInt(1)
  248. }
  249. if call.Gas == 0 {
  250. call.Gas = 50000000
  251. }
  252. if call.Value == nil {
  253. call.Value = new(big.Int)
  254. }
  255. // Set infinite balance to the fake caller account.
  256. from := statedb.GetOrNewStateObject(call.From)
  257. from.SetBalance(math.MaxBig256)
  258. // Execute the call.
  259. msg := callmsg{call}
  260. evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
  261. // Create a new environment which holds all relevant information
  262. // about the transaction and calling mechanisms.
  263. vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
  264. gaspool := new(core.GasPool).AddGas(math.MaxUint64)
  265. return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  266. }
  267. // SendTransaction updates the pending block to include the given transaction.
  268. // It panics if the transaction is invalid.
  269. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  270. b.mu.Lock()
  271. defer b.mu.Unlock()
  272. sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx)
  273. if err != nil {
  274. panic(fmt.Errorf("invalid transaction: %v", err))
  275. }
  276. nonce := b.pendingState.GetNonce(sender)
  277. if tx.Nonce() != nonce {
  278. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  279. }
  280. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  281. for _, tx := range b.pendingBlock.Transactions() {
  282. block.AddTxWithChain(b.blockchain, tx)
  283. }
  284. block.AddTxWithChain(b.blockchain, tx)
  285. })
  286. statedb, _ := b.blockchain.State()
  287. b.pendingBlock = blocks[0]
  288. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  289. return nil
  290. }
  291. // FilterLogs executes a log filter operation, blocking during execution and
  292. // returning all the results in one batch.
  293. //
  294. // TODO(karalabe): Deprecate when the subscription one can return past data too.
  295. func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
  296. var filter *filters.Filter
  297. if query.BlockHash != nil {
  298. // Block filter requested, construct a single-shot filter
  299. filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
  300. } else {
  301. // Initialize unset filter boundaried to run from genesis to chain head
  302. from := int64(0)
  303. if query.FromBlock != nil {
  304. from = query.FromBlock.Int64()
  305. }
  306. to := int64(-1)
  307. if query.ToBlock != nil {
  308. to = query.ToBlock.Int64()
  309. }
  310. // Construct the range filter
  311. filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
  312. }
  313. // Run the filter and return all the logs
  314. logs, err := filter.Logs(ctx)
  315. if err != nil {
  316. return nil, err
  317. }
  318. res := make([]types.Log, len(logs))
  319. for i, log := range logs {
  320. res[i] = *log
  321. }
  322. return res, nil
  323. }
  324. // SubscribeFilterLogs creates a background log filtering operation, returning a
  325. // subscription immediately, which can be used to stream the found events.
  326. func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
  327. // Subscribe to contract events
  328. sink := make(chan []*types.Log)
  329. sub, err := b.events.SubscribeLogs(query, sink)
  330. if err != nil {
  331. return nil, err
  332. }
  333. // Since we're getting logs in batches, we need to flatten them into a plain stream
  334. return event.NewSubscription(func(quit <-chan struct{}) error {
  335. defer sub.Unsubscribe()
  336. for {
  337. select {
  338. case logs := <-sink:
  339. for _, log := range logs {
  340. select {
  341. case ch <- *log:
  342. case err := <-sub.Err():
  343. return err
  344. case <-quit:
  345. return nil
  346. }
  347. }
  348. case err := <-sub.Err():
  349. return err
  350. case <-quit:
  351. return nil
  352. }
  353. }
  354. }), nil
  355. }
  356. // AdjustTime adds a time shift to the simulated clock.
  357. func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
  358. b.mu.Lock()
  359. defer b.mu.Unlock()
  360. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  361. for _, tx := range b.pendingBlock.Transactions() {
  362. block.AddTx(tx)
  363. }
  364. block.OffsetTime(int64(adjustment.Seconds()))
  365. })
  366. statedb, _ := b.blockchain.State()
  367. b.pendingBlock = blocks[0]
  368. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  369. return nil
  370. }
  371. // callmsg implements core.Message to allow passing it as a transaction simulator.
  372. type callmsg struct {
  373. ethereum.CallMsg
  374. }
  375. func (m callmsg) From() common.Address { return m.CallMsg.From }
  376. func (m callmsg) Nonce() uint64 { return 0 }
  377. func (m callmsg) CheckNonce() bool { return false }
  378. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  379. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  380. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  381. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  382. func (m callmsg) Data() []byte { return m.CallMsg.Data }
  383. // filterBackend implements filters.Backend to support filtering for logs without
  384. // taking bloom-bits acceleration structures into account.
  385. type filterBackend struct {
  386. db ethdb.Database
  387. bc *core.BlockChain
  388. }
  389. func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
  390. func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
  391. func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
  392. if block == rpc.LatestBlockNumber {
  393. return fb.bc.CurrentHeader(), nil
  394. }
  395. return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
  396. }
  397. func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  398. return fb.bc.GetHeaderByHash(hash), nil
  399. }
  400. func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
  401. number := rawdb.ReadHeaderNumber(fb.db, hash)
  402. if number == nil {
  403. return nil, nil
  404. }
  405. return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
  406. }
  407. func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
  408. number := rawdb.ReadHeaderNumber(fb.db, hash)
  409. if number == nil {
  410. return nil, nil
  411. }
  412. receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
  413. if receipts == nil {
  414. return nil, nil
  415. }
  416. logs := make([][]*types.Log, len(receipts))
  417. for i, receipt := range receipts {
  418. logs[i] = receipt.Logs
  419. }
  420. return logs, nil
  421. }
  422. func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  423. return event.NewSubscription(func(quit <-chan struct{}) error {
  424. <-quit
  425. return nil
  426. })
  427. }
  428. func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  429. return fb.bc.SubscribeChainEvent(ch)
  430. }
  431. func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  432. return fb.bc.SubscribeRemovedLogsEvent(ch)
  433. }
  434. func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  435. return fb.bc.SubscribeLogsEvent(ch)
  436. }
  437. func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
  438. func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
  439. panic("not supported")
  440. }