simulated.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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"
  26. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/math"
  29. "github.com/ethereum/go-ethereum/consensus/ethash"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/bloombits"
  32. "github.com/ethereum/go-ethereum/core/rawdb"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/types"
  35. "github.com/ethereum/go-ethereum/core/vm"
  36. "github.com/ethereum/go-ethereum/eth/filters"
  37. "github.com/ethereum/go-ethereum/ethdb"
  38. "github.com/ethereum/go-ethereum/event"
  39. "github.com/ethereum/go-ethereum/params"
  40. "github.com/ethereum/go-ethereum/rpc"
  41. )
  42. // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
  43. var _ bind.ContractBackend = (*SimulatedBackend)(nil)
  44. var (
  45. errBlockNumberUnsupported = errors.New("simulatedBackend cannot access blocks other than the latest block")
  46. errBlockDoesNotExist = errors.New("block does not exist in blockchain")
  47. errTransactionDoesNotExist = errors.New("transaction does not exist")
  48. )
  49. // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
  50. // the background. Its main purpose is to allow easily testing contract bindings.
  51. // Simulated backend implements the following interfaces:
  52. // ChainReader, ChainStateReader, ContractBackend, ContractCaller, ContractFilterer, ContractTransactor,
  53. // DeployBackend, GasEstimator, GasPricer, LogFilterer, PendingContractCaller, TransactionReader, and TransactionSender
  54. type SimulatedBackend struct {
  55. database ethdb.Database // In memory database to store our testing data
  56. blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
  57. mu sync.Mutex
  58. pendingBlock *types.Block // Currently pending block that will be imported on request
  59. pendingState *state.StateDB // Currently pending state that will be the active on on request
  60. events *filters.EventSystem // Event system for filtering log events live
  61. config *params.ChainConfig
  62. }
  63. // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database
  64. // and uses a simulated blockchain for testing purposes.
  65. func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
  66. genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc}
  67. genesis.MustCommit(database)
  68. blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil)
  69. backend := &SimulatedBackend{
  70. database: database,
  71. blockchain: blockchain,
  72. config: genesis.Config,
  73. events: filters.NewEventSystem(&filterBackend{database, blockchain}, false),
  74. }
  75. backend.rollback()
  76. return backend
  77. }
  78. // NewSimulatedBackend creates a new binding backend using a simulated blockchain
  79. // for testing purposes.
  80. func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
  81. return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit)
  82. }
  83. // Close terminates the underlying blockchain's update loop.
  84. func (b *SimulatedBackend) Close() error {
  85. b.blockchain.Stop()
  86. return nil
  87. }
  88. // Commit imports all the pending transactions as a single block and starts a
  89. // fresh new state.
  90. func (b *SimulatedBackend) Commit() {
  91. b.mu.Lock()
  92. defer b.mu.Unlock()
  93. if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
  94. panic(err) // This cannot happen unless the simulator is wrong, fail in that case
  95. }
  96. b.rollback()
  97. }
  98. // Rollback aborts all pending transactions, reverting to the last committed state.
  99. func (b *SimulatedBackend) Rollback() {
  100. b.mu.Lock()
  101. defer b.mu.Unlock()
  102. b.rollback()
  103. }
  104. func (b *SimulatedBackend) rollback() {
  105. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
  106. statedb, _ := b.blockchain.State()
  107. b.pendingBlock = blocks[0]
  108. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database(), nil)
  109. }
  110. // stateByBlockNumber retrieves a state by a given blocknumber.
  111. func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) {
  112. if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
  113. return b.blockchain.State()
  114. }
  115. block, err := b.BlockByNumber(ctx, blockNumber)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return b.blockchain.StateAt(block.Hash())
  120. }
  121. // CodeAt returns the code associated with a certain account in the blockchain.
  122. func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
  123. b.mu.Lock()
  124. defer b.mu.Unlock()
  125. statedb, err := b.stateByBlockNumber(ctx, blockNumber)
  126. if err != nil {
  127. return nil, err
  128. }
  129. return statedb.GetCode(contract), nil
  130. }
  131. // BalanceAt returns the wei balance of a certain account in the blockchain.
  132. func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
  133. b.mu.Lock()
  134. defer b.mu.Unlock()
  135. statedb, err := b.stateByBlockNumber(ctx, blockNumber)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return statedb.GetBalance(contract), nil
  140. }
  141. // NonceAt returns the nonce of a certain account in the blockchain.
  142. func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
  143. b.mu.Lock()
  144. defer b.mu.Unlock()
  145. statedb, err := b.stateByBlockNumber(ctx, blockNumber)
  146. if err != nil {
  147. return 0, err
  148. }
  149. return statedb.GetNonce(contract), nil
  150. }
  151. // StorageAt returns the value of key in the storage of an account in the blockchain.
  152. func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
  153. b.mu.Lock()
  154. defer b.mu.Unlock()
  155. statedb, err := b.stateByBlockNumber(ctx, blockNumber)
  156. if err != nil {
  157. return nil, err
  158. }
  159. val := statedb.GetState(contract, key)
  160. return val[:], nil
  161. }
  162. // TransactionReceipt returns the receipt of a transaction.
  163. func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  164. b.mu.Lock()
  165. defer b.mu.Unlock()
  166. receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config)
  167. return receipt, nil
  168. }
  169. // TransactionByHash checks the pool of pending transactions in addition to the
  170. // blockchain. The isPending return value indicates whether the transaction has been
  171. // mined yet. Note that the transaction may not be part of the canonical chain even if
  172. // it's not pending.
  173. func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
  174. b.mu.Lock()
  175. defer b.mu.Unlock()
  176. tx := b.pendingBlock.Transaction(txHash)
  177. if tx != nil {
  178. return tx, true, nil
  179. }
  180. tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash)
  181. if tx != nil {
  182. return tx, false, nil
  183. }
  184. return nil, false, ethereum.NotFound
  185. }
  186. // BlockByHash retrieves a block based on the block hash
  187. func (b *SimulatedBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  188. b.mu.Lock()
  189. defer b.mu.Unlock()
  190. if hash == b.pendingBlock.Hash() {
  191. return b.pendingBlock, nil
  192. }
  193. block := b.blockchain.GetBlockByHash(hash)
  194. if block != nil {
  195. return block, nil
  196. }
  197. return nil, errBlockDoesNotExist
  198. }
  199. // BlockByNumber retrieves a block from the database by number, caching it
  200. // (associated with its hash) if found.
  201. func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
  202. b.mu.Lock()
  203. defer b.mu.Unlock()
  204. if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
  205. return b.blockchain.CurrentBlock(), nil
  206. }
  207. block := b.blockchain.GetBlockByNumber(uint64(number.Int64()))
  208. if block == nil {
  209. return nil, errBlockDoesNotExist
  210. }
  211. return block, nil
  212. }
  213. // HeaderByHash returns a block header from the current canonical chain.
  214. func (b *SimulatedBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  215. b.mu.Lock()
  216. defer b.mu.Unlock()
  217. if hash == b.pendingBlock.Hash() {
  218. return b.pendingBlock.Header(), nil
  219. }
  220. header := b.blockchain.GetHeaderByHash(hash)
  221. if header == nil {
  222. return nil, errBlockDoesNotExist
  223. }
  224. return header, nil
  225. }
  226. // HeaderByNumber returns a block header from the current canonical chain. If number is
  227. // nil, the latest known header is returned.
  228. func (b *SimulatedBackend) HeaderByNumber(ctx context.Context, block *big.Int) (*types.Header, error) {
  229. b.mu.Lock()
  230. defer b.mu.Unlock()
  231. if block == nil || block.Cmp(b.pendingBlock.Number()) == 0 {
  232. return b.blockchain.CurrentHeader(), nil
  233. }
  234. return b.blockchain.GetHeaderByNumber(uint64(block.Int64())), nil
  235. }
  236. // TransactionCount returns the number of transactions in a given block
  237. func (b *SimulatedBackend) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
  238. b.mu.Lock()
  239. defer b.mu.Unlock()
  240. if blockHash == b.pendingBlock.Hash() {
  241. return uint(b.pendingBlock.Transactions().Len()), nil
  242. }
  243. block := b.blockchain.GetBlockByHash(blockHash)
  244. if block == nil {
  245. return uint(0), errBlockDoesNotExist
  246. }
  247. return uint(block.Transactions().Len()), nil
  248. }
  249. // TransactionInBlock returns the transaction for a specific block at a specific index
  250. func (b *SimulatedBackend) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
  251. b.mu.Lock()
  252. defer b.mu.Unlock()
  253. if blockHash == b.pendingBlock.Hash() {
  254. transactions := b.pendingBlock.Transactions()
  255. if uint(len(transactions)) < index+1 {
  256. return nil, errTransactionDoesNotExist
  257. }
  258. return transactions[index], nil
  259. }
  260. block := b.blockchain.GetBlockByHash(blockHash)
  261. if block == nil {
  262. return nil, errBlockDoesNotExist
  263. }
  264. transactions := block.Transactions()
  265. if uint(len(transactions)) < index+1 {
  266. return nil, errTransactionDoesNotExist
  267. }
  268. return transactions[index], nil
  269. }
  270. // PendingCodeAt returns the code associated with an account in the pending state.
  271. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  272. b.mu.Lock()
  273. defer b.mu.Unlock()
  274. return b.pendingState.GetCode(contract), nil
  275. }
  276. // CallContract executes a contract call.
  277. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  278. b.mu.Lock()
  279. defer b.mu.Unlock()
  280. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  281. return nil, errBlockNumberUnsupported
  282. }
  283. state, err := b.blockchain.State()
  284. if err != nil {
  285. return nil, err
  286. }
  287. res, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  288. if err != nil {
  289. return nil, err
  290. }
  291. return res.Return(), nil
  292. }
  293. // PendingCallContract executes a contract call on the pending state.
  294. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  295. b.mu.Lock()
  296. defer b.mu.Unlock()
  297. defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
  298. res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  299. if err != nil {
  300. return nil, err
  301. }
  302. return res.Return(), nil
  303. }
  304. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  305. // the nonce currently pending for the account.
  306. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  307. b.mu.Lock()
  308. defer b.mu.Unlock()
  309. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  310. }
  311. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  312. // chain doesn't have miners, we just return a gas price of 1 for any call.
  313. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  314. return big.NewInt(1), nil
  315. }
  316. // EstimateGas executes the requested code against the currently pending block/state and
  317. // returns the used amount of gas.
  318. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
  319. b.mu.Lock()
  320. defer b.mu.Unlock()
  321. // Determine the lowest and highest possible gas limits to binary search in between
  322. var (
  323. lo uint64 = params.TxGas - 1
  324. hi uint64
  325. cap uint64
  326. )
  327. if call.Gas >= params.TxGas {
  328. hi = call.Gas
  329. } else {
  330. hi = b.pendingBlock.GasLimit()
  331. }
  332. cap = hi
  333. // Create a helper to check if a gas allowance results in an executable transaction
  334. executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  335. call.Gas = gas
  336. snapshot := b.pendingState.Snapshot()
  337. res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  338. b.pendingState.RevertToSnapshot(snapshot)
  339. if err != nil {
  340. if err == core.ErrIntrinsicGas {
  341. return true, nil, nil // Special case, raise gas limit
  342. }
  343. return true, nil, err // Bail out
  344. }
  345. return res.Failed(), res, nil
  346. }
  347. // Execute the binary search and hone in on an executable gas limit
  348. for lo+1 < hi {
  349. mid := (hi + lo) / 2
  350. failed, _, err := executable(mid)
  351. // If the error is not nil(consensus error), it means the provided message
  352. // call or transaction will never be accepted no matter how much gas it is
  353. // assigned. Return the error directly, don't struggle any more
  354. if err != nil {
  355. return 0, err
  356. }
  357. if failed {
  358. lo = mid
  359. } else {
  360. hi = mid
  361. }
  362. }
  363. // Reject the transaction as invalid if it still fails at the highest allowance
  364. if hi == cap {
  365. failed, result, err := executable(hi)
  366. if err != nil {
  367. return 0, err
  368. }
  369. if failed {
  370. if result != nil && result.Err != vm.ErrOutOfGas {
  371. errMsg := fmt.Sprintf("always failing transaction (%v)", result.Err)
  372. if len(result.Revert()) > 0 {
  373. ret, err := abi.UnpackRevert(result.Revert())
  374. if err != nil {
  375. errMsg += fmt.Sprintf(" (%#x)", result.Revert())
  376. } else {
  377. errMsg += fmt.Sprintf(" (%s)", ret)
  378. }
  379. }
  380. return 0, errors.New(errMsg)
  381. }
  382. // Otherwise, the specified gas cap is too low
  383. return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  384. }
  385. }
  386. return hi, nil
  387. }
  388. // callContract implements common code between normal and pending contract calls.
  389. // state is modified during execution, make sure to copy it if necessary.
  390. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) (*core.ExecutionResult, error) {
  391. // Ensure message is initialized properly.
  392. if call.GasPrice == nil {
  393. call.GasPrice = big.NewInt(1)
  394. }
  395. if call.Gas == 0 {
  396. call.Gas = 50000000
  397. }
  398. if call.Value == nil {
  399. call.Value = new(big.Int)
  400. }
  401. // Set infinite balance to the fake caller account.
  402. from := statedb.GetOrNewStateObject(call.From)
  403. from.SetBalance(math.MaxBig256)
  404. // Execute the call.
  405. msg := callmsg{call}
  406. evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
  407. // Create a new environment which holds all relevant information
  408. // about the transaction and calling mechanisms.
  409. vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
  410. gaspool := new(core.GasPool).AddGas(math.MaxUint64)
  411. return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  412. }
  413. // SendTransaction updates the pending block to include the given transaction.
  414. // It panics if the transaction is invalid.
  415. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  416. b.mu.Lock()
  417. defer b.mu.Unlock()
  418. sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx)
  419. if err != nil {
  420. panic(fmt.Errorf("invalid transaction: %v", err))
  421. }
  422. nonce := b.pendingState.GetNonce(sender)
  423. if tx.Nonce() != nonce {
  424. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  425. }
  426. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  427. for _, tx := range b.pendingBlock.Transactions() {
  428. block.AddTxWithChain(b.blockchain, tx)
  429. }
  430. block.AddTxWithChain(b.blockchain, tx)
  431. })
  432. statedb, _ := b.blockchain.State()
  433. b.pendingBlock = blocks[0]
  434. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database(), nil)
  435. return nil
  436. }
  437. // FilterLogs executes a log filter operation, blocking during execution and
  438. // returning all the results in one batch.
  439. //
  440. // TODO(karalabe): Deprecate when the subscription one can return past data too.
  441. func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
  442. var filter *filters.Filter
  443. if query.BlockHash != nil {
  444. // Block filter requested, construct a single-shot filter
  445. filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
  446. } else {
  447. // Initialize unset filter boundaried to run from genesis to chain head
  448. from := int64(0)
  449. if query.FromBlock != nil {
  450. from = query.FromBlock.Int64()
  451. }
  452. to := int64(-1)
  453. if query.ToBlock != nil {
  454. to = query.ToBlock.Int64()
  455. }
  456. // Construct the range filter
  457. filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
  458. }
  459. // Run the filter and return all the logs
  460. logs, err := filter.Logs(ctx)
  461. if err != nil {
  462. return nil, err
  463. }
  464. res := make([]types.Log, len(logs))
  465. for i, log := range logs {
  466. res[i] = *log
  467. }
  468. return res, nil
  469. }
  470. // SubscribeFilterLogs creates a background log filtering operation, returning a
  471. // subscription immediately, which can be used to stream the found events.
  472. func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
  473. // Subscribe to contract events
  474. sink := make(chan []*types.Log)
  475. sub, err := b.events.SubscribeLogs(query, sink)
  476. if err != nil {
  477. return nil, err
  478. }
  479. // Since we're getting logs in batches, we need to flatten them into a plain stream
  480. return event.NewSubscription(func(quit <-chan struct{}) error {
  481. defer sub.Unsubscribe()
  482. for {
  483. select {
  484. case logs := <-sink:
  485. for _, log := range logs {
  486. select {
  487. case ch <- *log:
  488. case err := <-sub.Err():
  489. return err
  490. case <-quit:
  491. return nil
  492. }
  493. }
  494. case err := <-sub.Err():
  495. return err
  496. case <-quit:
  497. return nil
  498. }
  499. }
  500. }), nil
  501. }
  502. // SubscribeNewHead returns an event subscription for a new header
  503. func (b *SimulatedBackend) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
  504. // subscribe to a new head
  505. sink := make(chan *types.Header)
  506. sub := b.events.SubscribeNewHeads(sink)
  507. return event.NewSubscription(func(quit <-chan struct{}) error {
  508. defer sub.Unsubscribe()
  509. for {
  510. select {
  511. case head := <-sink:
  512. select {
  513. case ch <- head:
  514. case err := <-sub.Err():
  515. return err
  516. case <-quit:
  517. return nil
  518. }
  519. case err := <-sub.Err():
  520. return err
  521. case <-quit:
  522. return nil
  523. }
  524. }
  525. }), nil
  526. }
  527. // AdjustTime adds a time shift to the simulated clock.
  528. func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
  529. b.mu.Lock()
  530. defer b.mu.Unlock()
  531. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  532. for _, tx := range b.pendingBlock.Transactions() {
  533. block.AddTx(tx)
  534. }
  535. block.OffsetTime(int64(adjustment.Seconds()))
  536. })
  537. statedb, _ := b.blockchain.State()
  538. b.pendingBlock = blocks[0]
  539. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database(), nil)
  540. return nil
  541. }
  542. // Blockchain returns the underlying blockchain.
  543. func (b *SimulatedBackend) Blockchain() *core.BlockChain {
  544. return b.blockchain
  545. }
  546. // callmsg implements core.Message to allow passing it as a transaction simulator.
  547. type callmsg struct {
  548. ethereum.CallMsg
  549. }
  550. func (m callmsg) From() common.Address { return m.CallMsg.From }
  551. func (m callmsg) Nonce() uint64 { return 0 }
  552. func (m callmsg) CheckNonce() bool { return false }
  553. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  554. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  555. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  556. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  557. func (m callmsg) Data() []byte { return m.CallMsg.Data }
  558. // filterBackend implements filters.Backend to support filtering for logs without
  559. // taking bloom-bits acceleration structures into account.
  560. type filterBackend struct {
  561. db ethdb.Database
  562. bc *core.BlockChain
  563. }
  564. func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
  565. func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
  566. func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
  567. if block == rpc.LatestBlockNumber {
  568. return fb.bc.CurrentHeader(), nil
  569. }
  570. return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
  571. }
  572. func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  573. return fb.bc.GetHeaderByHash(hash), nil
  574. }
  575. func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
  576. number := rawdb.ReadHeaderNumber(fb.db, hash)
  577. if number == nil {
  578. return nil, nil
  579. }
  580. return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
  581. }
  582. func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
  583. number := rawdb.ReadHeaderNumber(fb.db, hash)
  584. if number == nil {
  585. return nil, nil
  586. }
  587. receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
  588. if receipts == nil {
  589. return nil, nil
  590. }
  591. logs := make([][]*types.Log, len(receipts))
  592. for i, receipt := range receipts {
  593. logs[i] = receipt.Logs
  594. }
  595. return logs, nil
  596. }
  597. func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  598. return nullSubscription()
  599. }
  600. func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  601. return fb.bc.SubscribeChainEvent(ch)
  602. }
  603. func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  604. return fb.bc.SubscribeRemovedLogsEvent(ch)
  605. }
  606. func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  607. return fb.bc.SubscribeLogsEvent(ch)
  608. }
  609. func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
  610. return nullSubscription()
  611. }
  612. func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
  613. func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
  614. panic("not supported")
  615. }
  616. func nullSubscription() event.Subscription {
  617. return event.NewSubscription(func(quit <-chan struct{}) error {
  618. <-quit
  619. return nil
  620. })
  621. }