simulated.go 26 KB

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