simulated.go 15 KB

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