snapshot.go 13 KB

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