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