simulated.go 25 KB

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