state_accessor.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. for i := uint64(0); i < reexec; i++ {
  59. if current.NumberU64() == 0 {
  60. return nil, errors.New("genesis state is missing")
  61. }
  62. parent := eth.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1)
  63. if parent == nil {
  64. return nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1)
  65. }
  66. current = parent
  67. statedb, err = state.New(current.Root(), database, nil)
  68. if err == nil {
  69. break
  70. }
  71. }
  72. if err != nil {
  73. switch err.(type) {
  74. case *trie.MissingNodeError:
  75. return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
  76. default:
  77. return nil, err
  78. }
  79. }
  80. }
  81. // State was available at historical point, regenerate
  82. var (
  83. start = time.Now()
  84. logged time.Time
  85. parent common.Hash
  86. )
  87. for current.NumberU64() < origin {
  88. // Print progress logs if long enough time elapsed
  89. if time.Since(logged) > 8*time.Second && report {
  90. log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start))
  91. logged = time.Now()
  92. }
  93. // Retrieve the next block to regenerate and process it
  94. next := current.NumberU64() + 1
  95. if current = eth.blockchain.GetBlockByNumber(next); current == nil {
  96. return nil, fmt.Errorf("block #%d not found", next)
  97. }
  98. _, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{})
  99. if err != nil {
  100. return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
  101. }
  102. // Finalize the state so any modifications are written to the trie
  103. root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number()))
  104. if err != nil {
  105. return nil, err
  106. }
  107. statedb, err = state.New(root, database, nil)
  108. if err != nil {
  109. return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err)
  110. }
  111. database.TrieDB().Reference(root, common.Hash{})
  112. if parent != (common.Hash{}) {
  113. database.TrieDB().Dereference(parent)
  114. }
  115. parent = root
  116. }
  117. if report {
  118. nodes, imgs := database.TrieDB().Size()
  119. log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
  120. }
  121. return statedb, nil
  122. }
  123. // stateAtTransaction returns the execution environment of a certain transaction.
  124. func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
  125. // Short circuit if it's genesis block.
  126. if block.NumberU64() == 0 {
  127. return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis")
  128. }
  129. // Create the parent state database
  130. parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  131. if parent == nil {
  132. return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
  133. }
  134. // Lookup the statedb of parent block from the live database,
  135. // otherwise regenerate it on the flight.
  136. statedb, err := eth.stateAtBlock(parent, reexec, nil, true)
  137. if err != nil {
  138. return nil, vm.BlockContext{}, nil, err
  139. }
  140. if txIndex == 0 && len(block.Transactions()) == 0 {
  141. return nil, vm.BlockContext{}, statedb, nil
  142. }
  143. // Recompute transactions up to the target index.
  144. signer := types.MakeSigner(eth.blockchain.Config(), block.Number())
  145. for idx, tx := range block.Transactions() {
  146. // Assemble the transaction call message and return if the requested offset
  147. msg, _ := tx.AsMessage(signer)
  148. txContext := core.NewEVMTxContext(msg)
  149. context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
  150. if idx == txIndex {
  151. return msg, context, statedb, nil
  152. }
  153. // Not yet the searched for transaction, execute on top of the current state
  154. vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{})
  155. statedb.Prepare(tx.Hash(), block.Hash(), idx)
  156. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  157. return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  158. }
  159. // Ensure any modifications are committed to the state
  160. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  161. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  162. }
  163. return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
  164. }