simulated.go 29 KB

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