simulated.go 16 KB

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