pruner.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 pruner
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "math"
  23. "os"
  24. "path/filepath"
  25. "strings"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/state/snapshot"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "github.com/ethereum/go-ethereum/trie"
  36. )
  37. const (
  38. // stateBloomFilePrefix is the filename prefix of state bloom filter.
  39. stateBloomFilePrefix = "statebloom"
  40. // stateBloomFilePrefix is the filename suffix of state bloom filter.
  41. stateBloomFileSuffix = "bf.gz"
  42. // stateBloomFileTempSuffix is the filename suffix of state bloom filter
  43. // while it is being written out to detect write aborts.
  44. stateBloomFileTempSuffix = ".tmp"
  45. // rangeCompactionThreshold is the minimal deleted entry number for
  46. // triggering range compaction. It's a quite arbitrary number but just
  47. // to avoid triggering range compaction because of small deletion.
  48. rangeCompactionThreshold = 100000
  49. )
  50. var (
  51. // emptyRoot is the known root hash of an empty trie.
  52. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  53. // emptyCode is the known hash of the empty EVM bytecode.
  54. emptyCode = crypto.Keccak256(nil)
  55. )
  56. // Pruner is an offline tool to prune the stale state with the
  57. // help of the snapshot. The workflow of pruner is very simple:
  58. //
  59. // - iterate the snapshot, reconstruct the relevant state
  60. // - iterate the database, delete all other state entries which
  61. // don't belong to the target state and the genesis state
  62. //
  63. // It can take several hours(around 2 hours for mainnet) to finish
  64. // the whole pruning work. It's recommended to run this offline tool
  65. // periodically in order to release the disk usage and improve the
  66. // disk read performance to some extent.
  67. type Pruner struct {
  68. db ethdb.Database
  69. stateBloom *stateBloom
  70. datadir string
  71. trieCachePath string
  72. headHeader *types.Header
  73. snaptree *snapshot.Tree
  74. }
  75. // NewPruner creates the pruner instance.
  76. func NewPruner(db ethdb.Database, datadir, trieCachePath string, bloomSize uint64) (*Pruner, error) {
  77. headBlock := rawdb.ReadHeadBlock(db)
  78. if headBlock == nil {
  79. return nil, errors.New("Failed to load head block")
  80. }
  81. snaptree, err := snapshot.New(db, trie.NewDatabase(db), 256, headBlock.Root(), false, false, false)
  82. if err != nil {
  83. return nil, err // The relevant snapshot(s) might not exist
  84. }
  85. // Sanitize the bloom filter size if it's too small.
  86. if bloomSize < 256 {
  87. log.Warn("Sanitizing bloomfilter size", "provided(MB)", bloomSize, "updated(MB)", 256)
  88. bloomSize = 256
  89. }
  90. stateBloom, err := newStateBloomWithSize(bloomSize)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return &Pruner{
  95. db: db,
  96. stateBloom: stateBloom,
  97. datadir: datadir,
  98. trieCachePath: trieCachePath,
  99. headHeader: headBlock.Header(),
  100. snaptree: snaptree,
  101. }, nil
  102. }
  103. func prune(snaptree *snapshot.Tree, root common.Hash, maindb ethdb.Database, stateBloom *stateBloom, bloomPath string, middleStateRoots map[common.Hash]struct{}, start time.Time) error {
  104. // Delete all stale trie nodes in the disk. With the help of state bloom
  105. // the trie nodes(and codes) belong to the active state will be filtered
  106. // out. A very small part of stale tries will also be filtered because of
  107. // the false-positive rate of bloom filter. But the assumption is held here
  108. // that the false-positive is low enough(~0.05%). The probablity of the
  109. // dangling node is the state root is super low. So the dangling nodes in
  110. // theory will never ever be visited again.
  111. var (
  112. count int
  113. size common.StorageSize
  114. pstart = time.Now()
  115. logged = time.Now()
  116. batch = maindb.NewBatch()
  117. iter = maindb.NewIterator(nil, nil)
  118. )
  119. for iter.Next() {
  120. key := iter.Key()
  121. // All state entries don't belong to specific state and genesis are deleted here
  122. // - trie node
  123. // - legacy contract code
  124. // - new-scheme contract code
  125. isCode, codeKey := rawdb.IsCodeKey(key)
  126. if len(key) == common.HashLength || isCode {
  127. checkKey := key
  128. if isCode {
  129. checkKey = codeKey
  130. }
  131. if _, exist := middleStateRoots[common.BytesToHash(checkKey)]; exist {
  132. log.Debug("Forcibly delete the middle state roots", "hash", common.BytesToHash(checkKey))
  133. } else {
  134. if ok, err := stateBloom.Contain(checkKey); err != nil {
  135. return err
  136. } else if ok {
  137. continue
  138. }
  139. }
  140. count += 1
  141. size += common.StorageSize(len(key) + len(iter.Value()))
  142. batch.Delete(key)
  143. var eta time.Duration // Realistically will never remain uninited
  144. if done := binary.BigEndian.Uint64(key[:8]); done > 0 {
  145. var (
  146. left = math.MaxUint64 - binary.BigEndian.Uint64(key[:8])
  147. speed = done/uint64(time.Since(pstart)/time.Millisecond+1) + 1 // +1s to avoid division by zero
  148. )
  149. eta = time.Duration(left/speed) * time.Millisecond
  150. }
  151. if time.Since(logged) > 8*time.Second {
  152. log.Info("Pruning state data", "nodes", count, "size", size,
  153. "elapsed", common.PrettyDuration(time.Since(pstart)), "eta", common.PrettyDuration(eta))
  154. logged = time.Now()
  155. }
  156. // Recreate the iterator after every batch commit in order
  157. // to allow the underlying compactor to delete the entries.
  158. if batch.ValueSize() >= ethdb.IdealBatchSize {
  159. batch.Write()
  160. batch.Reset()
  161. iter.Release()
  162. iter = maindb.NewIterator(nil, key)
  163. }
  164. }
  165. }
  166. if batch.ValueSize() > 0 {
  167. batch.Write()
  168. batch.Reset()
  169. }
  170. iter.Release()
  171. log.Info("Pruned state data", "nodes", count, "size", size, "elapsed", common.PrettyDuration(time.Since(pstart)))
  172. // Pruning is done, now drop the "useless" layers from the snapshot.
  173. // Firstly, flushing the target layer into the disk. After that all
  174. // diff layers below the target will all be merged into the disk.
  175. if err := snaptree.Cap(root, 0); err != nil {
  176. return err
  177. }
  178. // Secondly, flushing the snapshot journal into the disk. All diff
  179. // layers upon are dropped silently. Eventually the entire snapshot
  180. // tree is converted into a single disk layer with the pruning target
  181. // as the root.
  182. if _, err := snaptree.Journal(root); err != nil {
  183. return err
  184. }
  185. // Delete the state bloom, it marks the entire pruning procedure is
  186. // finished. If any crashes or manual exit happens before this,
  187. // `RecoverPruning` will pick it up in the next restarts to redo all
  188. // the things.
  189. os.RemoveAll(bloomPath)
  190. // Start compactions, will remove the deleted data from the disk immediately.
  191. // Note for small pruning, the compaction is skipped.
  192. if count >= rangeCompactionThreshold {
  193. cstart := time.Now()
  194. for b := 0x00; b <= 0xf0; b += 0x10 {
  195. var (
  196. start = []byte{byte(b)}
  197. end = []byte{byte(b + 0x10)}
  198. )
  199. if b == 0xf0 {
  200. end = nil
  201. }
  202. log.Info("Compacting database", "range", fmt.Sprintf("%#x-%#x", start, end), "elapsed", common.PrettyDuration(time.Since(cstart)))
  203. if err := maindb.Compact(start, end); err != nil {
  204. log.Error("Database compaction failed", "error", err)
  205. return err
  206. }
  207. }
  208. log.Info("Database compaction finished", "elapsed", common.PrettyDuration(time.Since(cstart)))
  209. }
  210. log.Info("State pruning successful", "pruned", size, "elapsed", common.PrettyDuration(time.Since(start)))
  211. return nil
  212. }
  213. // Prune deletes all historical state nodes except the nodes belong to the
  214. // specified state version. If user doesn't specify the state version, use
  215. // the bottom-most snapshot diff layer as the target.
  216. func (p *Pruner) Prune(root common.Hash) error {
  217. // If the state bloom filter is already committed previously,
  218. // reuse it for pruning instead of generating a new one. It's
  219. // mandatory because a part of state may already be deleted,
  220. // the recovery procedure is necessary.
  221. _, stateBloomRoot, err := findBloomFilter(p.datadir)
  222. if err != nil {
  223. return err
  224. }
  225. if stateBloomRoot != (common.Hash{}) {
  226. return RecoverPruning(p.datadir, p.db, p.trieCachePath)
  227. }
  228. // If the target state root is not specified, use the HEAD-127 as the
  229. // target. The reason for picking it is:
  230. // - in most of the normal cases, the related state is available
  231. // - the probability of this layer being reorg is very low
  232. var layers []snapshot.Snapshot
  233. if root == (common.Hash{}) {
  234. // Retrieve all snapshot layers from the current HEAD.
  235. // In theory there are 128 difflayers + 1 disk layer present,
  236. // so 128 diff layers are expected to be returned.
  237. layers = p.snaptree.Snapshots(p.headHeader.Root, 128, true)
  238. if len(layers) != 128 {
  239. // Reject if the accumulated diff layers are less than 128. It
  240. // means in most of normal cases, there is no associated state
  241. // with bottom-most diff layer.
  242. return fmt.Errorf("snapshot not old enough yet: need %d more blocks", 128-len(layers))
  243. }
  244. // Use the bottom-most diff layer as the target
  245. root = layers[len(layers)-1].Root()
  246. }
  247. // Ensure the root is really present. The weak assumption
  248. // is the presence of root can indicate the presence of the
  249. // entire trie.
  250. if !rawdb.HasTrieNode(p.db, root) {
  251. // The special case is for clique based networks(rinkeby, goerli
  252. // and some other private networks), it's possible that two
  253. // consecutive blocks will have same root. In this case snapshot
  254. // difflayer won't be created. So HEAD-127 may not paired with
  255. // head-127 layer. Instead the paired layer is higher than the
  256. // bottom-most diff layer. Try to find the bottom-most snapshot
  257. // layer with state available.
  258. //
  259. // Note HEAD and HEAD-1 is ignored. Usually there is the associated
  260. // state available, but we don't want to use the topmost state
  261. // as the pruning target.
  262. var found bool
  263. for i := len(layers) - 2; i >= 2; i-- {
  264. if rawdb.HasTrieNode(p.db, layers[i].Root()) {
  265. root = layers[i].Root()
  266. found = true
  267. log.Info("Selecting middle-layer as the pruning target", "root", root, "depth", i)
  268. break
  269. }
  270. }
  271. if !found {
  272. if len(layers) > 0 {
  273. return errors.New("no snapshot paired state")
  274. }
  275. return fmt.Errorf("associated state[%x] is not present", root)
  276. }
  277. } else {
  278. if len(layers) > 0 {
  279. log.Info("Selecting bottom-most difflayer as the pruning target", "root", root, "height", p.headHeader.Number.Uint64()-127)
  280. } else {
  281. log.Info("Selecting user-specified state as the pruning target", "root", root)
  282. }
  283. }
  284. // Before start the pruning, delete the clean trie cache first.
  285. // It's necessary otherwise in the next restart we will hit the
  286. // deleted state root in the "clean cache" so that the incomplete
  287. // state is picked for usage.
  288. deleteCleanTrieCache(p.trieCachePath)
  289. // All the state roots of the middle layer should be forcibly pruned,
  290. // otherwise the dangling state will be left.
  291. middleRoots := make(map[common.Hash]struct{})
  292. for _, layer := range layers {
  293. if layer.Root() == root {
  294. break
  295. }
  296. middleRoots[layer.Root()] = struct{}{}
  297. }
  298. // Traverse the target state, re-construct the whole state trie and
  299. // commit to the given bloom filter.
  300. start := time.Now()
  301. if err := snapshot.GenerateTrie(p.snaptree, root, p.db, p.stateBloom); err != nil {
  302. return err
  303. }
  304. // Traverse the genesis, put all genesis state entries into the
  305. // bloom filter too.
  306. if err := extractGenesis(p.db, p.stateBloom); err != nil {
  307. return err
  308. }
  309. filterName := bloomFilterName(p.datadir, root)
  310. log.Info("Writing state bloom to disk", "name", filterName)
  311. if err := p.stateBloom.Commit(filterName, filterName+stateBloomFileTempSuffix); err != nil {
  312. return err
  313. }
  314. log.Info("State bloom filter committed", "name", filterName)
  315. return prune(p.snaptree, root, p.db, p.stateBloom, filterName, middleRoots, start)
  316. }
  317. // RecoverPruning will resume the pruning procedure during the system restart.
  318. // This function is used in this case: user tries to prune state data, but the
  319. // system was interrupted midway because of crash or manual-kill. In this case
  320. // if the bloom filter for filtering active state is already constructed, the
  321. // pruning can be resumed. What's more if the bloom filter is constructed, the
  322. // pruning **has to be resumed**. Otherwise a lot of dangling nodes may be left
  323. // in the disk.
  324. func RecoverPruning(datadir string, db ethdb.Database, trieCachePath string) error {
  325. stateBloomPath, stateBloomRoot, err := findBloomFilter(datadir)
  326. if err != nil {
  327. return err
  328. }
  329. if stateBloomPath == "" {
  330. return nil // nothing to recover
  331. }
  332. headBlock := rawdb.ReadHeadBlock(db)
  333. if headBlock == nil {
  334. return errors.New("Failed to load head block")
  335. }
  336. // Initialize the snapshot tree in recovery mode to handle this special case:
  337. // - Users run the `prune-state` command multiple times
  338. // - Neither these `prune-state` running is finished(e.g. interrupted manually)
  339. // - The state bloom filter is already generated, a part of state is deleted,
  340. // so that resuming the pruning here is mandatory
  341. // - The state HEAD is rewound already because of multiple incomplete `prune-state`
  342. // In this case, even the state HEAD is not exactly matched with snapshot, it
  343. // still feasible to recover the pruning correctly.
  344. snaptree, err := snapshot.New(db, trie.NewDatabase(db), 256, headBlock.Root(), false, false, true)
  345. if err != nil {
  346. return err // The relevant snapshot(s) might not exist
  347. }
  348. stateBloom, err := NewStateBloomFromDisk(stateBloomPath)
  349. if err != nil {
  350. return err
  351. }
  352. log.Info("Loaded state bloom filter", "path", stateBloomPath)
  353. // Before start the pruning, delete the clean trie cache first.
  354. // It's necessary otherwise in the next restart we will hit the
  355. // deleted state root in the "clean cache" so that the incomplete
  356. // state is picked for usage.
  357. deleteCleanTrieCache(trieCachePath)
  358. // All the state roots of the middle layers should be forcibly pruned,
  359. // otherwise the dangling state will be left.
  360. var (
  361. found bool
  362. layers = snaptree.Snapshots(headBlock.Root(), 128, true)
  363. middleRoots = make(map[common.Hash]struct{})
  364. )
  365. for _, layer := range layers {
  366. if layer.Root() == stateBloomRoot {
  367. found = true
  368. break
  369. }
  370. middleRoots[layer.Root()] = struct{}{}
  371. }
  372. if !found {
  373. log.Error("Pruning target state is not existent")
  374. return errors.New("non-existent target state")
  375. }
  376. return prune(snaptree, stateBloomRoot, db, stateBloom, stateBloomPath, middleRoots, time.Now())
  377. }
  378. // extractGenesis loads the genesis state and commits all the state entries
  379. // into the given bloomfilter.
  380. func extractGenesis(db ethdb.Database, stateBloom *stateBloom) error {
  381. genesisHash := rawdb.ReadCanonicalHash(db, 0)
  382. if genesisHash == (common.Hash{}) {
  383. return errors.New("missing genesis hash")
  384. }
  385. genesis := rawdb.ReadBlock(db, genesisHash, 0)
  386. if genesis == nil {
  387. return errors.New("missing genesis block")
  388. }
  389. t, err := trie.NewStateTrie(common.Hash{}, genesis.Root(), trie.NewDatabase(db))
  390. if err != nil {
  391. return err
  392. }
  393. accIter := t.NodeIterator(nil)
  394. for accIter.Next(true) {
  395. hash := accIter.Hash()
  396. // Embedded nodes don't have hash.
  397. if hash != (common.Hash{}) {
  398. stateBloom.Put(hash.Bytes(), nil)
  399. }
  400. // If it's a leaf node, yes we are touching an account,
  401. // dig into the storage trie further.
  402. if accIter.Leaf() {
  403. var acc types.StateAccount
  404. if err := rlp.DecodeBytes(accIter.LeafBlob(), &acc); err != nil {
  405. return err
  406. }
  407. if acc.Root != emptyRoot {
  408. storageTrie, err := trie.NewStateTrie(common.BytesToHash(accIter.LeafKey()), acc.Root, trie.NewDatabase(db))
  409. if err != nil {
  410. return err
  411. }
  412. storageIter := storageTrie.NodeIterator(nil)
  413. for storageIter.Next(true) {
  414. hash := storageIter.Hash()
  415. if hash != (common.Hash{}) {
  416. stateBloom.Put(hash.Bytes(), nil)
  417. }
  418. }
  419. if storageIter.Error() != nil {
  420. return storageIter.Error()
  421. }
  422. }
  423. if !bytes.Equal(acc.CodeHash, emptyCode) {
  424. stateBloom.Put(acc.CodeHash, nil)
  425. }
  426. }
  427. }
  428. return accIter.Error()
  429. }
  430. func bloomFilterName(datadir string, hash common.Hash) string {
  431. return filepath.Join(datadir, fmt.Sprintf("%s.%s.%s", stateBloomFilePrefix, hash.Hex(), stateBloomFileSuffix))
  432. }
  433. func isBloomFilter(filename string) (bool, common.Hash) {
  434. filename = filepath.Base(filename)
  435. if strings.HasPrefix(filename, stateBloomFilePrefix) && strings.HasSuffix(filename, stateBloomFileSuffix) {
  436. return true, common.HexToHash(filename[len(stateBloomFilePrefix)+1 : len(filename)-len(stateBloomFileSuffix)-1])
  437. }
  438. return false, common.Hash{}
  439. }
  440. func findBloomFilter(datadir string) (string, common.Hash, error) {
  441. var (
  442. stateBloomPath string
  443. stateBloomRoot common.Hash
  444. )
  445. if err := filepath.Walk(datadir, func(path string, info os.FileInfo, err error) error {
  446. if info != nil && !info.IsDir() {
  447. ok, root := isBloomFilter(path)
  448. if ok {
  449. stateBloomPath = path
  450. stateBloomRoot = root
  451. }
  452. }
  453. return nil
  454. }); err != nil {
  455. return "", common.Hash{}, err
  456. }
  457. return stateBloomPath, stateBloomRoot, nil
  458. }
  459. const warningLog = `
  460. WARNING!
  461. The clean trie cache is not found. Please delete it by yourself after the
  462. pruning. Remember don't start the Geth without deleting the clean trie cache
  463. otherwise the entire database may be damaged!
  464. Check the command description "geth snapshot prune-state --help" for more details.
  465. `
  466. func deleteCleanTrieCache(path string) {
  467. if !common.FileExist(path) {
  468. log.Warn(warningLog)
  469. return
  470. }
  471. os.RemoveAll(path)
  472. log.Info("Deleted trie clean cache", "path", path)
  473. }