state_accessor.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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
  31. // are attempted to be reexecuted to generate the desired state. The optional
  32. // base layer statedb can be passed then it's regarded as the statedb of the
  33. // parent block.
  34. func (eth *Ethereum) stateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool) (statedb *state.StateDB, err error) {
  35. var (
  36. current *types.Block
  37. database state.Database
  38. report = true
  39. origin = block.NumberU64()
  40. )
  41. // Check the live database first if we have the state fully available, use that.
  42. if checkLive {
  43. statedb, err = eth.blockchain.StateAt(block.Root())
  44. if err == nil {
  45. return statedb, nil
  46. }
  47. }
  48. if base != nil {
  49. // The optional base statedb is given, mark the start point as parent block
  50. statedb, database, report = base, base.Database(), false
  51. current = eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  52. } else {
  53. // Otherwise try to reexec blocks until we find a state or reach our limit
  54. current = block
  55. // Create an ephemeral trie.Database for isolating the live one. Otherwise
  56. // the internal junks created by tracing will be persisted into the disk.
  57. database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16})
  58. // If we didn't check the dirty database, do check the clean one, otherwise
  59. // we would rewind past a persisted block (specific corner case is chain
  60. // tracing from the genesis).
  61. if !checkLive {
  62. statedb, err = state.New(current.Root(), database, nil)
  63. if err == nil {
  64. return statedb, nil
  65. }
  66. }
  67. // Database does not have the state for the given block, try to regenerate
  68. for i := uint64(0); i < reexec; i++ {
  69. if current.NumberU64() == 0 {
  70. return nil, errors.New("genesis state is missing")
  71. }
  72. parent := eth.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1)
  73. if parent == nil {
  74. return nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1)
  75. }
  76. current = parent
  77. statedb, err = state.New(current.Root(), database, nil)
  78. if err == nil {
  79. break
  80. }
  81. }
  82. if err != nil {
  83. switch err.(type) {
  84. case *trie.MissingNodeError:
  85. return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
  86. default:
  87. return nil, err
  88. }
  89. }
  90. }
  91. // State was available at historical point, regenerate
  92. var (
  93. start = time.Now()
  94. logged time.Time
  95. parent common.Hash
  96. )
  97. for current.NumberU64() < origin {
  98. // Print progress logs if long enough time elapsed
  99. if time.Since(logged) > 8*time.Second && report {
  100. log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start))
  101. logged = time.Now()
  102. }
  103. // Retrieve the next block to regenerate and process it
  104. next := current.NumberU64() + 1
  105. if current = eth.blockchain.GetBlockByNumber(next); current == nil {
  106. return nil, fmt.Errorf("block #%d not found", next)
  107. }
  108. _, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{})
  109. if err != nil {
  110. return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
  111. }
  112. // Finalize the state so any modifications are written to the trie
  113. root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number()))
  114. if err != nil {
  115. return nil, err
  116. }
  117. statedb, err = state.New(root, database, nil)
  118. if err != nil {
  119. return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err)
  120. }
  121. database.TrieDB().Reference(root, common.Hash{})
  122. if parent != (common.Hash{}) {
  123. database.TrieDB().Dereference(parent)
  124. }
  125. parent = root
  126. }
  127. if report {
  128. nodes, imgs := database.TrieDB().Size()
  129. log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
  130. }
  131. return statedb, nil
  132. }
  133. // stateAtTransaction returns the execution environment of a certain transaction.
  134. func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
  135. // Short circuit if it's genesis block.
  136. if block.NumberU64() == 0 {
  137. return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis")
  138. }
  139. // Create the parent state database
  140. parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  141. if parent == nil {
  142. return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
  143. }
  144. // Lookup the statedb of parent block from the live database,
  145. // otherwise regenerate it on the flight.
  146. statedb, err := eth.stateAtBlock(parent, reexec, nil, true)
  147. if err != nil {
  148. return nil, vm.BlockContext{}, nil, err
  149. }
  150. if txIndex == 0 && len(block.Transactions()) == 0 {
  151. return nil, vm.BlockContext{}, statedb, nil
  152. }
  153. // Recompute transactions up to the target index.
  154. signer := types.MakeSigner(eth.blockchain.Config(), block.Number())
  155. for idx, tx := range block.Transactions() {
  156. // Assemble the transaction call message and return if the requested offset
  157. msg, _ := tx.AsMessage(signer)
  158. txContext := core.NewEVMTxContext(msg)
  159. context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
  160. if idx == txIndex {
  161. return msg, context, statedb, nil
  162. }
  163. // Not yet the searched for transaction, execute on top of the current state
  164. vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{})
  165. statedb.Prepare(tx.Hash(), block.Hash(), idx)
  166. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  167. return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  168. }
  169. // Ensure any modifications are committed to the state
  170. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  171. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  172. }
  173. return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
  174. }