simulated.go 25 KB

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