simulated.go 27 KB

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