state_accessor.go 7.5 KB

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