state_accessor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. "context"
  19. "errors"
  20. "fmt"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/mps"
  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/private"
  30. "github.com/ethereum/go-ethereum/trie"
  31. )
  32. // stateAtBlock retrieves the state database associated with a certain block.
  33. // If no state is locally available for the given block, a number of blocks
  34. // are attempted to be reexecuted to generate the desired state. The optional
  35. // base layer statedb can be passed then it's regarded as the statedb of the
  36. // parent block.
  37. func (eth *Ethereum) stateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool) (statedb *state.StateDB, privateStateDB mps.PrivateStateRepository, err error) {
  38. var (
  39. current *types.Block
  40. database state.Database
  41. report = true
  42. origin = block.NumberU64()
  43. )
  44. // Check the live database first if we have the state fully available, use that.
  45. if checkLive {
  46. statedb, privateStateDB, err = eth.blockchain.StateAt(block.Root())
  47. if err == nil {
  48. return
  49. }
  50. }
  51. if base != nil {
  52. // The optional base statedb is given, mark the start point as parent block
  53. statedb, database, report = base, base.Database(), false
  54. current = eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  55. } else {
  56. // Otherwise try to reexec blocks until we find a state or reach our limit
  57. current = block
  58. // Create an ephemeral trie.Database for isolating the live one. Otherwise
  59. // the internal junks created by tracing will be persisted into the disk.
  60. database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16})
  61. // If we didn't check the dirty database, do check the clean one, otherwise
  62. // we would rewind past a persisted block (specific corner case is chain
  63. // tracing from the genesis).
  64. if !checkLive {
  65. statedb, err = state.New(current.Root(), database, nil)
  66. if err == nil {
  67. // Quorum
  68. _, privateStateDB, err = eth.blockchain.StateAt(current.Root())
  69. if err == nil {
  70. return statedb, privateStateDB, nil
  71. }
  72. // End Quorum
  73. }
  74. }
  75. // Database does not have the state for the given block, try to regenerate
  76. for i := uint64(0); i < reexec; i++ {
  77. if current.NumberU64() == 0 {
  78. return nil, nil, errors.New("genesis state is missing")
  79. }
  80. parent := eth.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1)
  81. if parent == nil {
  82. return nil, nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1)
  83. }
  84. current = parent
  85. statedb, err = state.New(current.Root(), database, nil)
  86. if err == nil {
  87. // Quorum
  88. _, privateStateDB, err = eth.blockchain.StateAt(current.Root())
  89. if err == nil {
  90. break
  91. }
  92. // End Quorum
  93. }
  94. }
  95. if err != nil {
  96. switch err.(type) {
  97. case *trie.MissingNodeError:
  98. return nil, nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
  99. default:
  100. return nil, nil, err
  101. }
  102. }
  103. }
  104. // State was available at historical point, regenerate
  105. var (
  106. start = time.Now()
  107. logged time.Time
  108. parent common.Hash
  109. )
  110. for current.NumberU64() < origin {
  111. // Print progress logs if long enough time elapsed
  112. if time.Since(logged) > 8*time.Second && report {
  113. log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start))
  114. logged = time.Now()
  115. }
  116. // Retrieve the next block to regenerate and process it
  117. next := current.NumberU64() + 1
  118. if current = eth.blockchain.GetBlockByNumber(next); current == nil {
  119. return nil, nil, fmt.Errorf("block #%d not found", next)
  120. }
  121. _, _, _, _, err = eth.blockchain.Processor().Process(current, statedb, privateStateDB, vm.Config{})
  122. if err != nil {
  123. return nil, nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
  124. }
  125. var root common.Hash
  126. // Finalize the state so any modifications are written to the trie
  127. root, err = statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number()))
  128. if err != nil {
  129. return nil, nil, err
  130. }
  131. statedb, err = state.New(root, database, nil)
  132. if err != nil {
  133. return nil, nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err)
  134. }
  135. // Quorum
  136. err = privateStateDB.Commit(eth.blockchain.Config().IsEIP158(block.Number()), block)
  137. if err != nil {
  138. return nil, nil, err
  139. }
  140. if err := privateStateDB.Reset(); err != nil {
  141. return nil, nil, fmt.Errorf("private state reset after block %d failed: %v", block.NumberU64(), err)
  142. }
  143. // End Quorum
  144. database.TrieDB().Reference(root, common.Hash{})
  145. if parent != (common.Hash{}) {
  146. database.TrieDB().Dereference(parent)
  147. }
  148. parent = root
  149. }
  150. if report {
  151. nodes, imgs := database.TrieDB().Size()
  152. log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
  153. }
  154. return statedb, privateStateDB, nil
  155. }
  156. // stateAtTransaction returns the execution environment of a certain transaction.
  157. func (eth *Ethereum) stateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, *state.StateDB, mps.PrivateStateRepository, error) {
  158. // Short circuit if it's genesis block.
  159. if block.NumberU64() == 0 {
  160. return nil, vm.BlockContext{}, nil, nil, nil, errors.New("no transaction in genesis")
  161. }
  162. // Create the parent state database
  163. parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  164. if parent == nil {
  165. return nil, vm.BlockContext{}, nil, nil, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
  166. }
  167. // Quorum
  168. statedb, privateStateRepo, err := eth.stateAtBlock(parent, reexec, nil, true)
  169. if err != nil {
  170. return nil, vm.BlockContext{}, nil, nil, nil, err
  171. }
  172. psm, err := eth.blockchain.PrivateStateManager().ResolveForUserContext(ctx)
  173. if err != nil {
  174. return nil, vm.BlockContext{}, nil, nil, nil, err
  175. }
  176. privateStateDb, err := privateStateRepo.StatePSI(psm.ID)
  177. if err != nil {
  178. return nil, vm.BlockContext{}, nil, nil, nil, err
  179. }
  180. // End Quorum
  181. if txIndex == 0 && len(block.Transactions()) == 0 {
  182. return nil, vm.BlockContext{}, statedb, privateStateDb, privateStateRepo, nil
  183. }
  184. // Recompute transactions up to the target index.
  185. signer := types.MakeSigner(eth.blockchain.Config(), block.Number())
  186. for idx, tx := range block.Transactions() {
  187. // Quorum
  188. privateStateDbToUse := core.PrivateStateDBForTxn(eth.blockchain.Config().IsQuorum, tx, statedb, privateStateDb)
  189. // End Quorum
  190. // Assemble the transaction call message and return if the requested offset
  191. msg, _ := tx.AsMessage(signer)
  192. msg = eth.clearMessageDataIfNonParty(msg, psm) // Quorum
  193. txContext := core.NewEVMTxContext(msg)
  194. context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
  195. if idx == txIndex {
  196. return msg, context, statedb, privateStateDb, privateStateRepo, nil
  197. }
  198. // Not yet the searched for transaction, execute on top of the current state
  199. vmenv := vm.NewEVM(context, txContext, statedb, privateStateDbToUse, eth.blockchain.Config(), vm.Config{})
  200. vmenv.SetCurrentTX(tx)
  201. vmenv.InnerApply = func(innerTx *types.Transaction) error {
  202. return applyInnerTransaction(eth.blockchain, statedb, privateStateDbToUse, block.Header(), tx, vm.Config{}, privateStateRepo.IsMPS(), privateStateRepo, vmenv, innerTx, idx)
  203. }
  204. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  205. return nil, vm.BlockContext{}, nil, nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  206. }
  207. // Ensure any modifications are committed to the state
  208. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  209. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  210. }
  211. return nil, vm.BlockContext{}, nil, nil, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
  212. }
  213. // Quorum
  214. func (eth *Ethereum) GetBlockchain() *core.BlockChain {
  215. return eth.BlockChain()
  216. }
  217. func applyInnerTransaction(bc *core.BlockChain, stateDB *state.StateDB, privateStateDB *state.StateDB, header *types.Header, outerTx *types.Transaction, evmConf vm.Config, forceNonParty bool, privateStateRepo mps.PrivateStateRepository, vmenv *vm.EVM, innerTx *types.Transaction, txIndex int) error {
  218. var (
  219. author *common.Address = nil // ApplyTransaction will determine the author from the header so we won't do it here
  220. gp *core.GasPool = new(core.GasPool).AddGas(outerTx.Gas())
  221. usedGas uint64 = 0
  222. )
  223. return core.ApplyInnerTransaction(bc, author, gp, stateDB, privateStateDB, header, outerTx, &usedGas, evmConf, forceNonParty, privateStateRepo, vmenv, innerTx, txIndex)
  224. }
  225. // clearMessageDataIfNonParty sets the message data to empty hash in case the private state is not party to the
  226. // transaction. The effect is that when the private tx payload is resolved using the privacy manager the private part of
  227. // the transaction is not retrieved and the transaction is being executed as if the node/private state is not party to
  228. // the transaction.
  229. func (eth *Ethereum) clearMessageDataIfNonParty(msg types.Message, psm *mps.PrivateStateMetadata) types.Message {
  230. if msg.IsPrivate() {
  231. _, managedParties, _, _, _ := private.P.Receive(common.BytesToEncryptedPayloadHash(msg.Data()))
  232. if eth.GetBlockchain().PrivateStateManager().NotIncludeAny(psm, managedParties...) {
  233. return msg.WithEmptyPrivateData(true)
  234. }
  235. }
  236. return msg
  237. }