snapshot.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. // Copyright 2020 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "errors"
  20. "time"
  21. "github.com/ethereum/go-ethereum/cmd/utils"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  24. "github.com/ethereum/go-ethereum/core/state"
  25. "github.com/ethereum/go-ethereum/core/state/pruner"
  26. "github.com/ethereum/go-ethereum/core/state/snapshot"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. "github.com/ethereum/go-ethereum/trie"
  31. cli "gopkg.in/urfave/cli.v1"
  32. )
  33. var (
  34. // emptyRoot is the known root hash of an empty trie.
  35. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  36. // emptyCode is the known hash of the empty EVM bytecode.
  37. emptyCode = crypto.Keccak256(nil)
  38. )
  39. var (
  40. snapshotCommand = cli.Command{
  41. Name: "snapshot",
  42. Usage: "A set of commands based on the snapshot",
  43. Category: "MISCELLANEOUS COMMANDS",
  44. Description: "",
  45. Subcommands: []cli.Command{
  46. {
  47. Name: "prune-state",
  48. Usage: "Prune stale ethereum state data based on the snapshot",
  49. ArgsUsage: "<root>",
  50. Action: utils.MigrateFlags(pruneState),
  51. Category: "MISCELLANEOUS COMMANDS",
  52. Flags: []cli.Flag{
  53. utils.DataDirFlag,
  54. utils.RopstenFlag,
  55. utils.RinkebyFlag,
  56. utils.GoerliFlag,
  57. utils.CacheTrieJournalFlag,
  58. utils.BloomFilterSizeFlag,
  59. },
  60. Description: `
  61. geth snapshot prune-state <state-root>
  62. will prune historical state data with the help of the state snapshot.
  63. All trie nodes and contract codes that do not belong to the specified
  64. version state will be deleted from the database. After pruning, only
  65. two version states are available: genesis and the specific one.
  66. The default pruning target is the HEAD-127 state.
  67. WARNING: It's necessary to delete the trie clean cache after the pruning.
  68. If you specify another directory for the trie clean cache via "--cache.trie.journal"
  69. during the use of Geth, please also specify it here for correct deletion. Otherwise
  70. the trie clean cache with default directory will be deleted.
  71. `,
  72. },
  73. {
  74. Name: "verify-state",
  75. Usage: "Recalculate state hash based on the snapshot for verification",
  76. ArgsUsage: "<root>",
  77. Action: utils.MigrateFlags(verifyState),
  78. Category: "MISCELLANEOUS COMMANDS",
  79. Flags: []cli.Flag{
  80. utils.DataDirFlag,
  81. utils.RopstenFlag,
  82. utils.RinkebyFlag,
  83. utils.GoerliFlag,
  84. },
  85. Description: `
  86. geth snapshot verify-state <state-root>
  87. will traverse the whole accounts and storages set based on the specified
  88. snapshot and recalculate the root hash of state for verification.
  89. In other words, this command does the snapshot to trie conversion.
  90. `,
  91. },
  92. {
  93. Name: "traverse-state",
  94. Usage: "Traverse the state with given root hash for verification",
  95. ArgsUsage: "<root>",
  96. Action: utils.MigrateFlags(traverseState),
  97. Category: "MISCELLANEOUS COMMANDS",
  98. Flags: []cli.Flag{
  99. utils.DataDirFlag,
  100. utils.RopstenFlag,
  101. utils.RinkebyFlag,
  102. utils.GoerliFlag,
  103. },
  104. Description: `
  105. geth snapshot traverse-state <state-root>
  106. will traverse the whole state from the given state root and will abort if any
  107. referenced trie node or contract code is missing. This command can be used for
  108. state integrity verification. The default checking target is the HEAD state.
  109. It's also usable without snapshot enabled.
  110. `,
  111. },
  112. {
  113. Name: "traverse-rawstate",
  114. Usage: "Traverse the state with given root hash for verification",
  115. ArgsUsage: "<root>",
  116. Action: utils.MigrateFlags(traverseRawState),
  117. Category: "MISCELLANEOUS COMMANDS",
  118. Flags: []cli.Flag{
  119. utils.DataDirFlag,
  120. utils.RopstenFlag,
  121. utils.RinkebyFlag,
  122. utils.GoerliFlag,
  123. },
  124. Description: `
  125. geth snapshot traverse-rawstate <state-root>
  126. will traverse the whole state from the given root and will abort if any referenced
  127. trie node or contract code is missing. This command can be used for state integrity
  128. verification. The default checking target is the HEAD state. It's basically identical
  129. to traverse-state, but the check granularity is smaller.
  130. It's also usable without snapshot enabled.
  131. `,
  132. },
  133. },
  134. }
  135. )
  136. func pruneState(ctx *cli.Context) error {
  137. stack, config := makeConfigNode(ctx)
  138. defer stack.Close()
  139. chain, chaindb := utils.MakeChain(ctx, stack, true)
  140. defer chaindb.Close()
  141. pruner, err := pruner.NewPruner(chaindb, chain.CurrentBlock().Header(), stack.ResolvePath(""), stack.ResolvePath(config.Eth.TrieCleanCacheJournal), ctx.GlobalUint64(utils.BloomFilterSizeFlag.Name))
  142. if err != nil {
  143. log.Error("Failed to open snapshot tree", "error", err)
  144. return err
  145. }
  146. if ctx.NArg() > 1 {
  147. log.Error("Too many arguments given")
  148. return errors.New("too many arguments")
  149. }
  150. var targetRoot common.Hash
  151. if ctx.NArg() == 1 {
  152. targetRoot, err = parseRoot(ctx.Args()[0])
  153. if err != nil {
  154. log.Error("Failed to resolve state root", "error", err)
  155. return err
  156. }
  157. }
  158. if err = pruner.Prune(targetRoot); err != nil {
  159. log.Error("Failed to prune state", "error", err)
  160. return err
  161. }
  162. return nil
  163. }
  164. func verifyState(ctx *cli.Context) error {
  165. stack, _ := makeConfigNode(ctx)
  166. defer stack.Close()
  167. chain, chaindb := utils.MakeChain(ctx, stack, true)
  168. defer chaindb.Close()
  169. snaptree, err := snapshot.New(chaindb, trie.NewDatabase(chaindb), 256, chain.CurrentBlock().Root(), false, false, false)
  170. if err != nil {
  171. log.Error("Failed to open snapshot tree", "error", err)
  172. return err
  173. }
  174. if ctx.NArg() > 1 {
  175. log.Error("Too many arguments given")
  176. return errors.New("too many arguments")
  177. }
  178. var root = chain.CurrentBlock().Root()
  179. if ctx.NArg() == 1 {
  180. root, err = parseRoot(ctx.Args()[0])
  181. if err != nil {
  182. log.Error("Failed to resolve state root", "error", err)
  183. return err
  184. }
  185. }
  186. if err := snaptree.Verify(root); err != nil {
  187. log.Error("Failed to verfiy state", "error", err)
  188. return err
  189. }
  190. log.Info("Verified the state")
  191. return nil
  192. }
  193. // traverseState is a helper function used for pruning verification.
  194. // Basically it just iterates the trie, ensure all nodes and associated
  195. // contract codes are present.
  196. func traverseState(ctx *cli.Context) error {
  197. stack, _ := makeConfigNode(ctx)
  198. defer stack.Close()
  199. chain, chaindb := utils.MakeChain(ctx, stack, true)
  200. defer chaindb.Close()
  201. if ctx.NArg() > 1 {
  202. log.Error("Too many arguments given")
  203. return errors.New("too many arguments")
  204. }
  205. // Use the HEAD root as the default
  206. head := chain.CurrentBlock()
  207. if head == nil {
  208. log.Error("Head block is missing")
  209. return errors.New("head block is missing")
  210. }
  211. var (
  212. root common.Hash
  213. err error
  214. )
  215. if ctx.NArg() == 1 {
  216. root, err = parseRoot(ctx.Args()[0])
  217. if err != nil {
  218. log.Error("Failed to resolve state root", "error", err)
  219. return err
  220. }
  221. log.Info("Start traversing the state", "root", root)
  222. } else {
  223. root = head.Root()
  224. log.Info("Start traversing the state", "root", root, "number", head.NumberU64())
  225. }
  226. triedb := trie.NewDatabase(chaindb)
  227. t, err := trie.NewSecure(root, triedb)
  228. if err != nil {
  229. log.Error("Failed to open trie", "root", root, "error", err)
  230. return err
  231. }
  232. var (
  233. accounts int
  234. slots int
  235. codes int
  236. lastReport time.Time
  237. start = time.Now()
  238. )
  239. accIter := trie.NewIterator(t.NodeIterator(nil))
  240. for accIter.Next() {
  241. accounts += 1
  242. var acc state.Account
  243. if err := rlp.DecodeBytes(accIter.Value, &acc); err != nil {
  244. log.Error("Invalid account encountered during traversal", "error", err)
  245. return err
  246. }
  247. if acc.Root != emptyRoot {
  248. storageTrie, err := trie.NewSecure(acc.Root, triedb)
  249. if err != nil {
  250. log.Error("Failed to open storage trie", "root", acc.Root, "error", err)
  251. return err
  252. }
  253. storageIter := trie.NewIterator(storageTrie.NodeIterator(nil))
  254. for storageIter.Next() {
  255. slots += 1
  256. }
  257. if storageIter.Err != nil {
  258. log.Error("Failed to traverse storage trie", "root", acc.Root, "error", storageIter.Err)
  259. return storageIter.Err
  260. }
  261. }
  262. if !bytes.Equal(acc.CodeHash, emptyCode) {
  263. code := rawdb.ReadCode(chaindb, common.BytesToHash(acc.CodeHash))
  264. if len(code) == 0 {
  265. log.Error("Code is missing", "hash", common.BytesToHash(acc.CodeHash))
  266. return errors.New("missing code")
  267. }
  268. codes += 1
  269. }
  270. if time.Since(lastReport) > time.Second*8 {
  271. log.Info("Traversing state", "accounts", accounts, "slots", slots, "codes", codes, "elapsed", common.PrettyDuration(time.Since(start)))
  272. lastReport = time.Now()
  273. }
  274. }
  275. if accIter.Err != nil {
  276. log.Error("Failed to traverse state trie", "root", root, "error", accIter.Err)
  277. return accIter.Err
  278. }
  279. log.Info("State is complete", "accounts", accounts, "slots", slots, "codes", codes, "elapsed", common.PrettyDuration(time.Since(start)))
  280. return nil
  281. }
  282. // traverseRawState is a helper function used for pruning verification.
  283. // Basically it just iterates the trie, ensure all nodes and associated
  284. // contract codes are present. It's basically identical to traverseState
  285. // but it will check each trie node.
  286. func traverseRawState(ctx *cli.Context) error {
  287. stack, _ := makeConfigNode(ctx)
  288. defer stack.Close()
  289. chain, chaindb := utils.MakeChain(ctx, stack, true)
  290. defer chaindb.Close()
  291. if ctx.NArg() > 1 {
  292. log.Error("Too many arguments given")
  293. return errors.New("too many arguments")
  294. }
  295. // Use the HEAD root as the default
  296. head := chain.CurrentBlock()
  297. if head == nil {
  298. log.Error("Head block is missing")
  299. return errors.New("head block is missing")
  300. }
  301. var (
  302. root common.Hash
  303. err error
  304. )
  305. if ctx.NArg() == 1 {
  306. root, err = parseRoot(ctx.Args()[0])
  307. if err != nil {
  308. log.Error("Failed to resolve state root", "error", err)
  309. return err
  310. }
  311. log.Info("Start traversing the state", "root", root)
  312. } else {
  313. root = head.Root()
  314. log.Info("Start traversing the state", "root", root, "number", head.NumberU64())
  315. }
  316. triedb := trie.NewDatabase(chaindb)
  317. t, err := trie.NewSecure(root, triedb)
  318. if err != nil {
  319. log.Error("Failed to open trie", "root", root, "error", err)
  320. return err
  321. }
  322. var (
  323. nodes int
  324. accounts int
  325. slots int
  326. codes int
  327. lastReport time.Time
  328. start = time.Now()
  329. )
  330. accIter := t.NodeIterator(nil)
  331. for accIter.Next(true) {
  332. nodes += 1
  333. node := accIter.Hash()
  334. if node != (common.Hash{}) {
  335. // Check the present for non-empty hash node(embedded node doesn't
  336. // have their own hash).
  337. blob := rawdb.ReadTrieNode(chaindb, node)
  338. if len(blob) == 0 {
  339. log.Error("Missing trie node(account)", "hash", node)
  340. return errors.New("missing account")
  341. }
  342. }
  343. // If it's a leaf node, yes we are touching an account,
  344. // dig into the storage trie further.
  345. if accIter.Leaf() {
  346. accounts += 1
  347. var acc state.Account
  348. if err := rlp.DecodeBytes(accIter.LeafBlob(), &acc); err != nil {
  349. log.Error("Invalid account encountered during traversal", "error", err)
  350. return errors.New("invalid account")
  351. }
  352. if acc.Root != emptyRoot {
  353. storageTrie, err := trie.NewSecure(acc.Root, triedb)
  354. if err != nil {
  355. log.Error("Failed to open storage trie", "root", acc.Root, "error", err)
  356. return errors.New("missing storage trie")
  357. }
  358. storageIter := storageTrie.NodeIterator(nil)
  359. for storageIter.Next(true) {
  360. nodes += 1
  361. node := storageIter.Hash()
  362. // Check the present for non-empty hash node(embedded node doesn't
  363. // have their own hash).
  364. if node != (common.Hash{}) {
  365. blob := rawdb.ReadTrieNode(chaindb, node)
  366. if len(blob) == 0 {
  367. log.Error("Missing trie node(storage)", "hash", node)
  368. return errors.New("missing storage")
  369. }
  370. }
  371. // Bump the counter if it's leaf node.
  372. if storageIter.Leaf() {
  373. slots += 1
  374. }
  375. }
  376. if storageIter.Error() != nil {
  377. log.Error("Failed to traverse storage trie", "root", acc.Root, "error", storageIter.Error())
  378. return storageIter.Error()
  379. }
  380. }
  381. if !bytes.Equal(acc.CodeHash, emptyCode) {
  382. code := rawdb.ReadCode(chaindb, common.BytesToHash(acc.CodeHash))
  383. if len(code) == 0 {
  384. log.Error("Code is missing", "account", common.BytesToHash(accIter.LeafKey()))
  385. return errors.New("missing code")
  386. }
  387. codes += 1
  388. }
  389. if time.Since(lastReport) > time.Second*8 {
  390. log.Info("Traversing state", "nodes", nodes, "accounts", accounts, "slots", slots, "codes", codes, "elapsed", common.PrettyDuration(time.Since(start)))
  391. lastReport = time.Now()
  392. }
  393. }
  394. }
  395. if accIter.Error() != nil {
  396. log.Error("Failed to traverse state trie", "root", root, "error", accIter.Error())
  397. return accIter.Error()
  398. }
  399. log.Info("State is complete", "nodes", nodes, "accounts", accounts, "slots", slots, "codes", codes, "elapsed", common.PrettyDuration(time.Since(start)))
  400. return nil
  401. }
  402. func parseRoot(input string) (common.Hash, error) {
  403. var h common.Hash
  404. if err := h.UnmarshalText([]byte(input)); err != nil {
  405. return h, err
  406. }
  407. return h, nil
  408. }