simulated.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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/bind"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/math"
  28. "github.com/ethereum/go-ethereum/consensus/ethash"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/bloombits"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/eth/filters"
  36. "github.com/ethereum/go-ethereum/ethdb"
  37. "github.com/ethereum/go-ethereum/event"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/rpc"
  40. )
  41. // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
  42. var _ bind.ContractBackend = (*SimulatedBackend)(nil)
  43. var (
  44. errBlockNumberUnsupported = errors.New("simulatedBackend cannot access blocks other than the latest block")
  45. errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction")
  46. )
  47. // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
  48. // the background. Its main purpose is to allow easily testing contract bindings.
  49. type SimulatedBackend struct {
  50. database ethdb.Database // In memory database to store our testing data
  51. blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
  52. mu sync.Mutex
  53. pendingBlock *types.Block // Currently pending block that will be imported on request
  54. pendingState *state.StateDB // Currently pending state that will be the active on on request
  55. events *filters.EventSystem // Event system for filtering log events live
  56. config *params.ChainConfig
  57. }
  58. // NewSimulatedBackendWithDatabase creates a new binding backend based on the given database
  59. // and uses a simulated blockchain for testing purposes.
  60. func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
  61. genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc}
  62. genesis.MustCommit(database)
  63. blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil)
  64. backend := &SimulatedBackend{
  65. database: database,
  66. blockchain: blockchain,
  67. config: genesis.Config,
  68. events: filters.NewEventSystem(&filterBackend{database, blockchain}, false),
  69. }
  70. backend.rollback()
  71. return backend
  72. }
  73. // NewSimulatedBackend creates a new binding backend using a simulated blockchain
  74. // for testing purposes.
  75. func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
  76. return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit)
  77. }
  78. // Close terminates the underlying blockchain's update loop.
  79. func (b *SimulatedBackend) Close() error {
  80. b.blockchain.Stop()
  81. return nil
  82. }
  83. // Commit imports all the pending transactions as a single block and starts a
  84. // fresh new state.
  85. func (b *SimulatedBackend) Commit() {
  86. b.mu.Lock()
  87. defer b.mu.Unlock()
  88. if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
  89. panic(err) // This cannot happen unless the simulator is wrong, fail in that case
  90. }
  91. b.rollback()
  92. }
  93. // Rollback aborts all pending transactions, reverting to the last committed state.
  94. func (b *SimulatedBackend) Rollback() {
  95. b.mu.Lock()
  96. defer b.mu.Unlock()
  97. b.rollback()
  98. }
  99. func (b *SimulatedBackend) rollback() {
  100. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {})
  101. statedb, _ := b.blockchain.State()
  102. b.pendingBlock = blocks[0]
  103. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  104. }
  105. // CodeAt returns the code associated with a certain account in the blockchain.
  106. func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
  107. b.mu.Lock()
  108. defer b.mu.Unlock()
  109. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  110. return nil, errBlockNumberUnsupported
  111. }
  112. statedb, _ := b.blockchain.State()
  113. return statedb.GetCode(contract), nil
  114. }
  115. // BalanceAt returns the wei balance of a certain account in the blockchain.
  116. func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
  117. b.mu.Lock()
  118. defer b.mu.Unlock()
  119. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  120. return nil, errBlockNumberUnsupported
  121. }
  122. statedb, _ := b.blockchain.State()
  123. return statedb.GetBalance(contract), nil
  124. }
  125. // NonceAt returns the nonce of a certain account in the blockchain.
  126. func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
  127. b.mu.Lock()
  128. defer b.mu.Unlock()
  129. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  130. return 0, errBlockNumberUnsupported
  131. }
  132. statedb, _ := b.blockchain.State()
  133. return statedb.GetNonce(contract), nil
  134. }
  135. // StorageAt returns the value of key in the storage of an account in the blockchain.
  136. func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
  137. b.mu.Lock()
  138. defer b.mu.Unlock()
  139. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  140. return nil, errBlockNumberUnsupported
  141. }
  142. statedb, _ := b.blockchain.State()
  143. val := statedb.GetState(contract, key)
  144. return val[:], nil
  145. }
  146. // TransactionReceipt returns the receipt of a transaction.
  147. func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  148. receipt, _, _, _ := rawdb.ReadReceipt(b.database, txHash, b.config)
  149. return receipt, nil
  150. }
  151. // TransactionByHash checks the pool of pending transactions in addition to the
  152. // blockchain. The isPending return value indicates whether the transaction has been
  153. // mined yet. Note that the transaction may not be part of the canonical chain even if
  154. // it's not pending.
  155. func (b *SimulatedBackend) TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
  156. b.mu.Lock()
  157. defer b.mu.Unlock()
  158. tx := b.pendingBlock.Transaction(txHash)
  159. if tx != nil {
  160. return tx, true, nil
  161. }
  162. tx, _, _, _ = rawdb.ReadTransaction(b.database, txHash)
  163. if tx != nil {
  164. return tx, false, nil
  165. }
  166. return nil, false, ethereum.NotFound
  167. }
  168. // PendingCodeAt returns the code associated with an account in the pending state.
  169. func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
  170. b.mu.Lock()
  171. defer b.mu.Unlock()
  172. return b.pendingState.GetCode(contract), nil
  173. }
  174. // CallContract executes a contract call.
  175. func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  176. b.mu.Lock()
  177. defer b.mu.Unlock()
  178. if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
  179. return nil, errBlockNumberUnsupported
  180. }
  181. state, err := b.blockchain.State()
  182. if err != nil {
  183. return nil, err
  184. }
  185. rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
  186. return rval, err
  187. }
  188. // PendingCallContract executes a contract call on the pending state.
  189. func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
  190. b.mu.Lock()
  191. defer b.mu.Unlock()
  192. defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
  193. rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  194. return rval, err
  195. }
  196. // PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
  197. // the nonce currently pending for the account.
  198. func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  199. b.mu.Lock()
  200. defer b.mu.Unlock()
  201. return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
  202. }
  203. // SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
  204. // chain doesn't have miners, we just return a gas price of 1 for any call.
  205. func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  206. return big.NewInt(1), nil
  207. }
  208. // EstimateGas executes the requested code against the currently pending block/state and
  209. // returns the used amount of gas.
  210. func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
  211. b.mu.Lock()
  212. defer b.mu.Unlock()
  213. // Determine the lowest and highest possible gas limits to binary search in between
  214. var (
  215. lo uint64 = params.TxGas - 1
  216. hi uint64
  217. cap uint64
  218. )
  219. if call.Gas >= params.TxGas {
  220. hi = call.Gas
  221. } else {
  222. hi = b.pendingBlock.GasLimit()
  223. }
  224. cap = hi
  225. // Create a helper to check if a gas allowance results in an executable transaction
  226. executable := func(gas uint64) bool {
  227. call.Gas = gas
  228. snapshot := b.pendingState.Snapshot()
  229. _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
  230. b.pendingState.RevertToSnapshot(snapshot)
  231. if err != nil || failed {
  232. return false
  233. }
  234. return true
  235. }
  236. // Execute the binary search and hone in on an executable gas limit
  237. for lo+1 < hi {
  238. mid := (hi + lo) / 2
  239. if !executable(mid) {
  240. lo = mid
  241. } else {
  242. hi = mid
  243. }
  244. }
  245. // Reject the transaction as invalid if it still fails at the highest allowance
  246. if hi == cap {
  247. if !executable(hi) {
  248. return 0, errGasEstimationFailed
  249. }
  250. }
  251. return hi, nil
  252. }
  253. // callContract implements common code between normal and pending contract calls.
  254. // state is modified during execution, make sure to copy it if necessary.
  255. func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
  256. // Ensure message is initialized properly.
  257. if call.GasPrice == nil {
  258. call.GasPrice = big.NewInt(1)
  259. }
  260. if call.Gas == 0 {
  261. call.Gas = 50000000
  262. }
  263. if call.Value == nil {
  264. call.Value = new(big.Int)
  265. }
  266. // Set infinite balance to the fake caller account.
  267. from := statedb.GetOrNewStateObject(call.From)
  268. from.SetBalance(math.MaxBig256)
  269. // Execute the call.
  270. msg := callmsg{call}
  271. evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain, nil)
  272. // Create a new environment which holds all relevant information
  273. // about the transaction and calling mechanisms.
  274. vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
  275. gaspool := new(core.GasPool).AddGas(math.MaxUint64)
  276. return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
  277. }
  278. // SendTransaction updates the pending block to include the given transaction.
  279. // It panics if the transaction is invalid.
  280. func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  281. b.mu.Lock()
  282. defer b.mu.Unlock()
  283. sender, err := types.Sender(types.NewEIP155Signer(b.config.ChainID), tx)
  284. if err != nil {
  285. panic(fmt.Errorf("invalid transaction: %v", err))
  286. }
  287. nonce := b.pendingState.GetNonce(sender)
  288. if tx.Nonce() != nonce {
  289. panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
  290. }
  291. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  292. for _, tx := range b.pendingBlock.Transactions() {
  293. block.AddTxWithChain(b.blockchain, tx)
  294. }
  295. block.AddTxWithChain(b.blockchain, tx)
  296. })
  297. statedb, _ := b.blockchain.State()
  298. b.pendingBlock = blocks[0]
  299. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  300. return nil
  301. }
  302. // FilterLogs executes a log filter operation, blocking during execution and
  303. // returning all the results in one batch.
  304. //
  305. // TODO(karalabe): Deprecate when the subscription one can return past data too.
  306. func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
  307. var filter *filters.Filter
  308. if query.BlockHash != nil {
  309. // Block filter requested, construct a single-shot filter
  310. filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
  311. } else {
  312. // Initialize unset filter boundaried to run from genesis to chain head
  313. from := int64(0)
  314. if query.FromBlock != nil {
  315. from = query.FromBlock.Int64()
  316. }
  317. to := int64(-1)
  318. if query.ToBlock != nil {
  319. to = query.ToBlock.Int64()
  320. }
  321. // Construct the range filter
  322. filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
  323. }
  324. // Run the filter and return all the logs
  325. logs, err := filter.Logs(ctx)
  326. if err != nil {
  327. return nil, err
  328. }
  329. res := make([]types.Log, len(logs))
  330. for i, log := range logs {
  331. res[i] = *log
  332. }
  333. return res, nil
  334. }
  335. // SubscribeFilterLogs creates a background log filtering operation, returning a
  336. // subscription immediately, which can be used to stream the found events.
  337. func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
  338. // Subscribe to contract events
  339. sink := make(chan []*types.Log)
  340. sub, err := b.events.SubscribeLogs(query, sink)
  341. if err != nil {
  342. return nil, err
  343. }
  344. // Since we're getting logs in batches, we need to flatten them into a plain stream
  345. return event.NewSubscription(func(quit <-chan struct{}) error {
  346. defer sub.Unsubscribe()
  347. for {
  348. select {
  349. case logs := <-sink:
  350. for _, log := range logs {
  351. select {
  352. case ch <- *log:
  353. case err := <-sub.Err():
  354. return err
  355. case <-quit:
  356. return nil
  357. }
  358. }
  359. case err := <-sub.Err():
  360. return err
  361. case <-quit:
  362. return nil
  363. }
  364. }
  365. }), nil
  366. }
  367. // AdjustTime adds a time shift to the simulated clock.
  368. func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
  369. b.mu.Lock()
  370. defer b.mu.Unlock()
  371. blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
  372. for _, tx := range b.pendingBlock.Transactions() {
  373. block.AddTx(tx)
  374. }
  375. block.OffsetTime(int64(adjustment.Seconds()))
  376. })
  377. statedb, _ := b.blockchain.State()
  378. b.pendingBlock = blocks[0]
  379. b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
  380. return nil
  381. }
  382. // Blockchain returns the underlying blockchain.
  383. func (b *SimulatedBackend) Blockchain() *core.BlockChain {
  384. return b.blockchain
  385. }
  386. // callmsg implements core.Message to allow passing it as a transaction simulator.
  387. type callmsg struct {
  388. ethereum.CallMsg
  389. }
  390. func (m callmsg) From() common.Address { return m.CallMsg.From }
  391. func (m callmsg) Nonce() uint64 { return 0 }
  392. func (m callmsg) CheckNonce() bool { return false }
  393. func (m callmsg) To() *common.Address { return m.CallMsg.To }
  394. func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
  395. func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
  396. func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
  397. func (m callmsg) Data() []byte { return m.CallMsg.Data }
  398. // filterBackend implements filters.Backend to support filtering for logs without
  399. // taking bloom-bits acceleration structures into account.
  400. type filterBackend struct {
  401. db ethdb.Database
  402. bc *core.BlockChain
  403. }
  404. func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
  405. func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
  406. func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
  407. if block == rpc.LatestBlockNumber {
  408. return fb.bc.CurrentHeader(), nil
  409. }
  410. return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
  411. }
  412. func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  413. return fb.bc.GetHeaderByHash(hash), nil
  414. }
  415. func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
  416. number := rawdb.ReadHeaderNumber(fb.db, hash)
  417. if number == nil {
  418. return nil, nil
  419. }
  420. return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
  421. }
  422. func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
  423. number := rawdb.ReadHeaderNumber(fb.db, hash)
  424. if number == nil {
  425. return nil, nil
  426. }
  427. receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
  428. if receipts == nil {
  429. return nil, nil
  430. }
  431. logs := make([][]*types.Log, len(receipts))
  432. for i, receipt := range receipts {
  433. logs[i] = receipt.Logs
  434. }
  435. return logs, nil
  436. }
  437. func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  438. return nullSubscription()
  439. }
  440. func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
  441. return fb.bc.SubscribeChainEvent(ch)
  442. }
  443. func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
  444. return fb.bc.SubscribeRemovedLogsEvent(ch)
  445. }
  446. func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  447. return fb.bc.SubscribeLogsEvent(ch)
  448. }
  449. func (fb *filterBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription {
  450. return nullSubscription()
  451. }
  452. func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
  453. func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
  454. panic("not supported")
  455. }
  456. func nullSubscription() event.Subscription {
  457. return event.NewSubscription(func(quit <-chan struct{}) error {
  458. <-quit
  459. return nil
  460. })
  461. }