state_accessor.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Copyright 2021 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 eth
  17. import (
  18. "errors"
  19. "fmt"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/state"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/core/vm"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/trie"
  28. )
  29. // stateAtBlock retrieves the state database associated with a certain block.
  30. // If no state is locally available for the given block, a number of blocks are
  31. // attempted to be reexecuted to generate the desired state.
  32. func (eth *Ethereum) stateAtBlock(block *types.Block, reexec uint64) (statedb *state.StateDB, release func(), err error) {
  33. // If we have the state fully available, use that
  34. statedb, err = eth.blockchain.StateAt(block.Root())
  35. if err == nil {
  36. return statedb, func() {}, nil
  37. }
  38. // Otherwise try to reexec blocks until we find a state or reach our limit
  39. origin := block.NumberU64()
  40. database := state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16, Preimages: true})
  41. for i := uint64(0); i < reexec; i++ {
  42. if block.NumberU64() == 0 {
  43. return nil, nil, errors.New("genesis state is missing")
  44. }
  45. parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  46. if parent == nil {
  47. return nil, nil, fmt.Errorf("missing block %v %d", block.ParentHash(), block.NumberU64()-1)
  48. }
  49. block = parent
  50. statedb, err = state.New(block.Root(), database, nil)
  51. if err == nil {
  52. break
  53. }
  54. }
  55. if err != nil {
  56. switch err.(type) {
  57. case *trie.MissingNodeError:
  58. return nil, nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
  59. default:
  60. return nil, nil, err
  61. }
  62. }
  63. // State was available at historical point, regenerate
  64. var (
  65. start = time.Now()
  66. logged time.Time
  67. parent common.Hash
  68. )
  69. defer func() {
  70. if err != nil && parent != (common.Hash{}) {
  71. database.TrieDB().Dereference(parent)
  72. }
  73. }()
  74. for block.NumberU64() < origin {
  75. // Print progress logs if long enough time elapsed
  76. if time.Since(logged) > 8*time.Second {
  77. log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "remaining", origin-block.NumberU64()-1, "elapsed", time.Since(start))
  78. logged = time.Now()
  79. }
  80. // Retrieve the next block to regenerate and process it
  81. if block = eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil {
  82. return nil, nil, fmt.Errorf("block #%d not found", block.NumberU64()+1)
  83. }
  84. _, _, _, err := eth.blockchain.Processor().Process(block, statedb, vm.Config{})
  85. if err != nil {
  86. return nil, nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
  87. }
  88. // Finalize the state so any modifications are written to the trie
  89. root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(block.Number()))
  90. if err != nil {
  91. return nil, nil, err
  92. }
  93. statedb, err = state.New(root, database, nil)
  94. if err != nil {
  95. return nil, nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
  96. }
  97. database.TrieDB().Reference(root, common.Hash{})
  98. if parent != (common.Hash{}) {
  99. database.TrieDB().Dereference(parent)
  100. }
  101. parent = root
  102. }
  103. nodes, imgs := database.TrieDB().Size()
  104. log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
  105. return statedb, func() { database.TrieDB().Dereference(parent) }, nil
  106. }
  107. // statesInRange retrieves a batch of state databases associated with the specific
  108. // block ranges. If no state is locally available for the given range, a number of
  109. // blocks are attempted to be reexecuted to generate the ancestor state.
  110. func (eth *Ethereum) statesInRange(fromBlock, toBlock *types.Block, reexec uint64) (states []*state.StateDB, release func(), err error) {
  111. statedb, err := eth.blockchain.StateAt(fromBlock.Root())
  112. if err != nil {
  113. statedb, _, err = eth.stateAtBlock(fromBlock, reexec)
  114. }
  115. if err != nil {
  116. return nil, nil, err
  117. }
  118. states = append(states, statedb.Copy())
  119. var (
  120. logged time.Time
  121. parent common.Hash
  122. start = time.Now()
  123. refs = []common.Hash{fromBlock.Root()}
  124. database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16, Preimages: true})
  125. )
  126. // Release all resources(including the states referenced by `stateAtBlock`)
  127. // if error is returned.
  128. defer func() {
  129. if err != nil {
  130. for _, ref := range refs {
  131. database.TrieDB().Dereference(ref)
  132. }
  133. }
  134. }()
  135. for i := fromBlock.NumberU64() + 1; i <= toBlock.NumberU64(); i++ {
  136. // Print progress logs if long enough time elapsed
  137. if time.Since(logged) > 8*time.Second {
  138. logged = time.Now()
  139. log.Info("Regenerating historical state", "block", i, "target", fromBlock.NumberU64(), "remaining", toBlock.NumberU64()-i, "elapsed", time.Since(start))
  140. }
  141. // Retrieve the next block to regenerate and process it
  142. block := eth.blockchain.GetBlockByNumber(i)
  143. if block == nil {
  144. return nil, nil, fmt.Errorf("block #%d not found", i)
  145. }
  146. _, _, _, err := eth.blockchain.Processor().Process(block, statedb, vm.Config{})
  147. if err != nil {
  148. return nil, nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
  149. }
  150. // Finalize the state so any modifications are written to the trie
  151. root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(block.Number()))
  152. if err != nil {
  153. return nil, nil, err
  154. }
  155. statedb, err := eth.blockchain.StateAt(root)
  156. if err != nil {
  157. return nil, nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
  158. }
  159. states = append(states, statedb.Copy())
  160. // Reference the trie twice, once for us, once for the tracer
  161. database.TrieDB().Reference(root, common.Hash{})
  162. database.TrieDB().Reference(root, common.Hash{})
  163. refs = append(refs, root)
  164. // Dereference all past tries we ourselves are done working with
  165. if parent != (common.Hash{}) {
  166. database.TrieDB().Dereference(parent)
  167. }
  168. parent = root
  169. }
  170. // release is handler to release all states referenced, including
  171. // the one referenced in `stateAtBlock`.
  172. release = func() {
  173. for _, ref := range refs {
  174. database.TrieDB().Dereference(ref)
  175. }
  176. }
  177. return states, release, nil
  178. }
  179. // stateAtTransaction returns the execution environment of a certain transaction.
  180. func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, func(), error) {
  181. // Short circuit if it's genesis block.
  182. if block.NumberU64() == 0 {
  183. return nil, vm.BlockContext{}, nil, nil, errors.New("no transaction in genesis")
  184. }
  185. // Create the parent state database
  186. parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  187. if parent == nil {
  188. return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
  189. }
  190. statedb, release, err := eth.stateAtBlock(parent, reexec)
  191. if err != nil {
  192. return nil, vm.BlockContext{}, nil, nil, err
  193. }
  194. if txIndex == 0 && len(block.Transactions()) == 0 {
  195. return nil, vm.BlockContext{}, statedb, release, nil
  196. }
  197. // Recompute transactions up to the target index.
  198. signer := types.MakeSigner(eth.blockchain.Config(), block.Number())
  199. for idx, tx := range block.Transactions() {
  200. // Assemble the transaction call message and return if the requested offset
  201. msg, _ := tx.AsMessage(signer)
  202. txContext := core.NewEVMTxContext(msg)
  203. context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
  204. if idx == txIndex {
  205. return msg, context, statedb, release, nil
  206. }
  207. // Not yet the searched for transaction, execute on top of the current state
  208. vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{})
  209. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  210. release()
  211. return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  212. }
  213. // Ensure any modifications are committed to the state
  214. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  215. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  216. }
  217. release()
  218. return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
  219. }