pruner.go 18 KB

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