simulated.go 24 KB

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