snapshot.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. // Copyright 2019 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 snapshot implements a journalled, dynamic state dump.
  17. package snapshot
  18. import (
  19. "bytes"
  20. "errors"
  21. "fmt"
  22. "sync"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/rawdb"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/metrics"
  28. "github.com/ethereum/go-ethereum/trie"
  29. )
  30. var (
  31. snapshotCleanAccountHitMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/hit", nil)
  32. snapshotCleanAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/miss", nil)
  33. snapshotCleanAccountInexMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/inex", nil)
  34. snapshotCleanAccountReadMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/read", nil)
  35. snapshotCleanAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/write", nil)
  36. snapshotCleanStorageHitMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/hit", nil)
  37. snapshotCleanStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/miss", nil)
  38. snapshotCleanStorageInexMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/inex", nil)
  39. snapshotCleanStorageReadMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/read", nil)
  40. snapshotCleanStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/write", nil)
  41. snapshotDirtyAccountHitMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/hit", nil)
  42. snapshotDirtyAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/miss", nil)
  43. snapshotDirtyAccountInexMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/inex", nil)
  44. snapshotDirtyAccountReadMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/read", nil)
  45. snapshotDirtyAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/write", nil)
  46. snapshotDirtyStorageHitMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/hit", nil)
  47. snapshotDirtyStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/miss", nil)
  48. snapshotDirtyStorageInexMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/inex", nil)
  49. snapshotDirtyStorageReadMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/read", nil)
  50. snapshotDirtyStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/write", nil)
  51. snapshotDirtyAccountHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/account/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015))
  52. snapshotDirtyStorageHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/storage/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015))
  53. snapshotFlushAccountItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/item", nil)
  54. snapshotFlushAccountSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/size", nil)
  55. snapshotFlushStorageItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/item", nil)
  56. snapshotFlushStorageSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/size", nil)
  57. snapshotBloomIndexTimer = metrics.NewRegisteredResettingTimer("state/snapshot/bloom/index", nil)
  58. snapshotBloomErrorGauge = metrics.NewRegisteredGaugeFloat64("state/snapshot/bloom/error", nil)
  59. snapshotBloomAccountTrueHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/truehit", nil)
  60. snapshotBloomAccountFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/falsehit", nil)
  61. snapshotBloomAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/miss", nil)
  62. snapshotBloomStorageTrueHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/truehit", nil)
  63. snapshotBloomStorageFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/falsehit", nil)
  64. snapshotBloomStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/miss", nil)
  65. // ErrSnapshotStale is returned from data accessors if the underlying snapshot
  66. // layer had been invalidated due to the chain progressing forward far enough
  67. // to not maintain the layer's original state.
  68. ErrSnapshotStale = errors.New("snapshot stale")
  69. // ErrNotCoveredYet is returned from data accessors if the underlying snapshot
  70. // is being generated currently and the requested data item is not yet in the
  71. // range of accounts covered.
  72. ErrNotCoveredYet = errors.New("not covered yet")
  73. // errSnapshotCycle is returned if a snapshot is attempted to be inserted
  74. // that forms a cycle in the snapshot tree.
  75. errSnapshotCycle = errors.New("snapshot cycle")
  76. )
  77. // Snapshot represents the functionality supported by a snapshot storage layer.
  78. type Snapshot interface {
  79. // Root returns the root hash for which this snapshot was made.
  80. Root() common.Hash
  81. // Account directly retrieves the account associated with a particular hash in
  82. // the snapshot slim data format.
  83. Account(hash common.Hash) (*Account, error)
  84. // AccountRLP directly retrieves the account RLP associated with a particular
  85. // hash in the snapshot slim data format.
  86. AccountRLP(hash common.Hash) ([]byte, error)
  87. // Storage directly retrieves the storage data associated with a particular hash,
  88. // within a particular account.
  89. Storage(accountHash, storageHash common.Hash) ([]byte, error)
  90. }
  91. // snapshot is the internal version of the snapshot data layer that supports some
  92. // additional methods compared to the public API.
  93. type snapshot interface {
  94. Snapshot
  95. // Update creates a new layer on top of the existing snapshot diff tree with
  96. // the specified data items. Note, the maps are retained by the method to avoid
  97. // copying everything.
  98. Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer
  99. // Journal commits an entire diff hierarchy to disk into a single journal entry.
  100. // This is meant to be used during shutdown to persist the snapshot without
  101. // flattening everything down (bad for reorgs).
  102. Journal(buffer *bytes.Buffer) (common.Hash, error)
  103. // Stale return whether this layer has become stale (was flattened across) or
  104. // if it's still live.
  105. Stale() bool
  106. }
  107. // SnapshotTree is an Ethereum state snapshot tree. It consists of one persistent
  108. // base layer backed by a key-value store, on top of which arbitrarily many in-
  109. // memory diff layers are topped. The memory diffs can form a tree with branching,
  110. // but the disk layer is singleton and common to all. If a reorg goes deeper than
  111. // the disk layer, everything needs to be deleted.
  112. //
  113. // The goal of a state snapshot is twofold: to allow direct access to account and
  114. // storage data to avoid expensive multi-level trie lookups; and to allow sorted,
  115. // cheap iteration of the account/storage tries for sync aid.
  116. type Tree struct {
  117. diskdb ethdb.KeyValueStore // Persistent database to store the snapshot
  118. triedb *trie.Database // In-memory cache to access the trie through
  119. cache int // Megabytes permitted to use for read caches
  120. layers map[common.Hash]snapshot // Collection of all known layers
  121. lock sync.RWMutex
  122. }
  123. // New attempts to load an already existing snapshot from a persistent key-value
  124. // store (with a number of memory layers from a journal), ensuring that the head
  125. // of the snapshot matches the expected one.
  126. //
  127. // If the snapshot is missing or inconsistent, the entirety is deleted and will
  128. // be reconstructed from scratch based on the tries in the key-value store, on a
  129. // background thread.
  130. func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash) *Tree {
  131. // Create a new, empty snapshot tree
  132. snap := &Tree{
  133. diskdb: diskdb,
  134. triedb: triedb,
  135. cache: cache,
  136. layers: make(map[common.Hash]snapshot),
  137. }
  138. // Attempt to load a previously persisted snapshot and rebuild one if failed
  139. head, err := loadSnapshot(diskdb, triedb, cache, root)
  140. if err != nil {
  141. log.Warn("Failed to load snapshot, regenerating", "err", err)
  142. snap.Rebuild(root)
  143. return snap
  144. }
  145. // Existing snapshot loaded, seed all the layers
  146. for head != nil {
  147. snap.layers[head.Root()] = head
  148. switch self := head.(type) {
  149. case *diffLayer:
  150. head = self.parent
  151. case *diskLayer:
  152. head = nil
  153. default:
  154. panic(fmt.Sprintf("unknown data layer: %T", self))
  155. }
  156. }
  157. return snap
  158. }
  159. // Snapshot retrieves a snapshot belonging to the given block root, or nil if no
  160. // snapshot is maintained for that block.
  161. func (t *Tree) Snapshot(blockRoot common.Hash) Snapshot {
  162. t.lock.RLock()
  163. defer t.lock.RUnlock()
  164. return t.layers[blockRoot]
  165. }
  166. // Update adds a new snapshot into the tree, if that can be linked to an existing
  167. // old parent. It is disallowed to insert a disk layer (the origin of all).
  168. func (t *Tree) Update(blockRoot common.Hash, parentRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) error {
  169. // Reject noop updates to avoid self-loops in the snapshot tree. This is a
  170. // special case that can only happen for Clique networks where empty blocks
  171. // don't modify the state (0 block subsidy).
  172. //
  173. // Although we could silently ignore this internally, it should be the caller's
  174. // responsibility to avoid even attempting to insert such a snapshot.
  175. if blockRoot == parentRoot {
  176. return errSnapshotCycle
  177. }
  178. // Generate a new snapshot on top of the parent
  179. parent := t.Snapshot(parentRoot).(snapshot)
  180. if parent == nil {
  181. return fmt.Errorf("parent [%#x] snapshot missing", parentRoot)
  182. }
  183. snap := parent.Update(blockRoot, accounts, storage)
  184. // Save the new snapshot for later
  185. t.lock.Lock()
  186. defer t.lock.Unlock()
  187. t.layers[snap.root] = snap
  188. return nil
  189. }
  190. // Cap traverses downwards the snapshot tree from a head block hash until the
  191. // number of allowed layers are crossed. All layers beyond the permitted number
  192. // are flattened downwards.
  193. func (t *Tree) Cap(root common.Hash, layers int) error {
  194. // Retrieve the head snapshot to cap from
  195. snap := t.Snapshot(root)
  196. if snap == nil {
  197. return fmt.Errorf("snapshot [%#x] missing", root)
  198. }
  199. diff, ok := snap.(*diffLayer)
  200. if !ok {
  201. return fmt.Errorf("snapshot [%#x] is disk layer", root)
  202. }
  203. // Run the internal capping and discard all stale layers
  204. t.lock.Lock()
  205. defer t.lock.Unlock()
  206. // Flattening the bottom-most diff layer requires special casing since there's
  207. // no child to rewire to the grandparent. In that case we can fake a temporary
  208. // child for the capping and then remove it.
  209. var persisted *diskLayer
  210. switch layers {
  211. case 0:
  212. // If full commit was requested, flatten the diffs and merge onto disk
  213. diff.lock.RLock()
  214. base := diffToDisk(diff.flatten().(*diffLayer))
  215. diff.lock.RUnlock()
  216. // Replace the entire snapshot tree with the flat base
  217. t.layers = map[common.Hash]snapshot{base.root: base}
  218. return nil
  219. case 1:
  220. // If full flattening was requested, flatten the diffs but only merge if the
  221. // memory limit was reached
  222. var (
  223. bottom *diffLayer
  224. base *diskLayer
  225. )
  226. diff.lock.RLock()
  227. bottom = diff.flatten().(*diffLayer)
  228. if bottom.memory >= aggregatorMemoryLimit {
  229. base = diffToDisk(bottom)
  230. }
  231. diff.lock.RUnlock()
  232. // If all diff layers were removed, replace the entire snapshot tree
  233. if base != nil {
  234. t.layers = map[common.Hash]snapshot{base.root: base}
  235. return nil
  236. }
  237. // Merge the new aggregated layer into the snapshot tree, clean stales below
  238. t.layers[bottom.root] = bottom
  239. default:
  240. // Many layers requested to be retained, cap normally
  241. persisted = t.cap(diff, layers)
  242. }
  243. // Remove any layer that is stale or links into a stale layer
  244. children := make(map[common.Hash][]common.Hash)
  245. for root, snap := range t.layers {
  246. if diff, ok := snap.(*diffLayer); ok {
  247. parent := diff.parent.Root()
  248. children[parent] = append(children[parent], root)
  249. }
  250. }
  251. var remove func(root common.Hash)
  252. remove = func(root common.Hash) {
  253. delete(t.layers, root)
  254. for _, child := range children[root] {
  255. remove(child)
  256. }
  257. delete(children, root)
  258. }
  259. for root, snap := range t.layers {
  260. if snap.Stale() {
  261. remove(root)
  262. }
  263. }
  264. // If the disk layer was modified, regenerate all the cummulative blooms
  265. if persisted != nil {
  266. var rebloom func(root common.Hash)
  267. rebloom = func(root common.Hash) {
  268. if diff, ok := t.layers[root].(*diffLayer); ok {
  269. diff.rebloom(persisted)
  270. }
  271. for _, child := range children[root] {
  272. rebloom(child)
  273. }
  274. }
  275. rebloom(persisted.root)
  276. }
  277. return nil
  278. }
  279. // cap traverses downwards the diff tree until the number of allowed layers are
  280. // crossed. All diffs beyond the permitted number are flattened downwards. If the
  281. // layer limit is reached, memory cap is also enforced (but not before).
  282. //
  283. // The method returns the new disk layer if diffs were persistend into it.
  284. func (t *Tree) cap(diff *diffLayer, layers int) *diskLayer {
  285. // Dive until we run out of layers or reach the persistent database
  286. for ; layers > 2; layers-- {
  287. // If we still have diff layers below, continue down
  288. if parent, ok := diff.parent.(*diffLayer); ok {
  289. diff = parent
  290. } else {
  291. // Diff stack too shallow, return without modifications
  292. return nil
  293. }
  294. }
  295. // We're out of layers, flatten anything below, stopping if it's the disk or if
  296. // the memory limit is not yet exceeded.
  297. switch parent := diff.parent.(type) {
  298. case *diskLayer:
  299. return nil
  300. case *diffLayer:
  301. // Flatten the parent into the grandparent. The flattening internally obtains a
  302. // write lock on grandparent.
  303. flattened := parent.flatten().(*diffLayer)
  304. t.layers[flattened.root] = flattened
  305. diff.lock.Lock()
  306. defer diff.lock.Unlock()
  307. diff.parent = flattened
  308. if flattened.memory < aggregatorMemoryLimit {
  309. // Accumulator layer is smaller than the limit, so we can abort, unless
  310. // there's a snapshot being generated currently. In that case, the trie
  311. // will move fron underneath the generator so we **must** merge all the
  312. // partial data down into the snapshot and restart the generation.
  313. if flattened.parent.(*diskLayer).genAbort == nil {
  314. return nil
  315. }
  316. }
  317. default:
  318. panic(fmt.Sprintf("unknown data layer: %T", parent))
  319. }
  320. // If the bottom-most layer is larger than our memory cap, persist to disk
  321. bottom := diff.parent.(*diffLayer)
  322. bottom.lock.RLock()
  323. base := diffToDisk(bottom)
  324. bottom.lock.RUnlock()
  325. t.layers[base.root] = base
  326. diff.parent = base
  327. return base
  328. }
  329. // diffToDisk merges a bottom-most diff into the persistent disk layer underneath
  330. // it. The method will panic if called onto a non-bottom-most diff layer.
  331. func diffToDisk(bottom *diffLayer) *diskLayer {
  332. var (
  333. base = bottom.parent.(*diskLayer)
  334. batch = base.diskdb.NewBatch()
  335. stats *generatorStats
  336. )
  337. // If the disk layer is running a snapshot generator, abort it
  338. if base.genAbort != nil {
  339. abort := make(chan *generatorStats)
  340. base.genAbort <- abort
  341. stats = <-abort
  342. }
  343. // Start by temporarily deleting the current snapshot block marker. This
  344. // ensures that in the case of a crash, the entire snapshot is invalidated.
  345. rawdb.DeleteSnapshotRoot(batch)
  346. // Mark the original base as stale as we're going to create a new wrapper
  347. base.lock.Lock()
  348. if base.stale {
  349. panic("parent disk layer is stale") // we've committed into the same base from two children, boo
  350. }
  351. base.stale = true
  352. base.lock.Unlock()
  353. // Push all the accounts into the database
  354. for hash, data := range bottom.accountData {
  355. // Skip any account not covered yet by the snapshot
  356. if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 {
  357. continue
  358. }
  359. if len(data) > 0 {
  360. // Account was updated, push to disk
  361. rawdb.WriteAccountSnapshot(batch, hash, data)
  362. base.cache.Set(hash[:], data)
  363. snapshotCleanAccountWriteMeter.Mark(int64(len(data)))
  364. if batch.ValueSize() > ethdb.IdealBatchSize {
  365. if err := batch.Write(); err != nil {
  366. log.Crit("Failed to write account snapshot", "err", err)
  367. }
  368. batch.Reset()
  369. }
  370. } else {
  371. // Account was deleted, remove all storage slots too
  372. rawdb.DeleteAccountSnapshot(batch, hash)
  373. base.cache.Set(hash[:], nil)
  374. it := rawdb.IterateStorageSnapshots(base.diskdb, hash)
  375. for it.Next() {
  376. if key := it.Key(); len(key) == 65 { // TODO(karalabe): Yuck, we should move this into the iterator
  377. batch.Delete(key)
  378. base.cache.Del(key[1:])
  379. snapshotFlushStorageItemMeter.Mark(1)
  380. snapshotFlushStorageSizeMeter.Mark(int64(len(data)))
  381. }
  382. }
  383. it.Release()
  384. }
  385. snapshotFlushAccountItemMeter.Mark(1)
  386. snapshotFlushAccountSizeMeter.Mark(int64(len(data)))
  387. }
  388. // Push all the storage slots into the database
  389. for accountHash, storage := range bottom.storageData {
  390. // Skip any account not covered yet by the snapshot
  391. if base.genMarker != nil && bytes.Compare(accountHash[:], base.genMarker) > 0 {
  392. continue
  393. }
  394. // Generation might be mid-account, track that case too
  395. midAccount := base.genMarker != nil && bytes.Equal(accountHash[:], base.genMarker[:common.HashLength])
  396. for storageHash, data := range storage {
  397. // Skip any slot not covered yet by the snapshot
  398. if midAccount && bytes.Compare(storageHash[:], base.genMarker[common.HashLength:]) > 0 {
  399. continue
  400. }
  401. if len(data) > 0 {
  402. rawdb.WriteStorageSnapshot(batch, accountHash, storageHash, data)
  403. base.cache.Set(append(accountHash[:], storageHash[:]...), data)
  404. snapshotCleanStorageWriteMeter.Mark(int64(len(data)))
  405. } else {
  406. rawdb.DeleteStorageSnapshot(batch, accountHash, storageHash)
  407. base.cache.Set(append(accountHash[:], storageHash[:]...), nil)
  408. }
  409. snapshotFlushStorageItemMeter.Mark(1)
  410. snapshotFlushStorageSizeMeter.Mark(int64(len(data)))
  411. }
  412. if batch.ValueSize() > ethdb.IdealBatchSize {
  413. if err := batch.Write(); err != nil {
  414. log.Crit("Failed to write storage snapshot", "err", err)
  415. }
  416. batch.Reset()
  417. }
  418. }
  419. // Update the snapshot block marker and write any remainder data
  420. rawdb.WriteSnapshotRoot(batch, bottom.root)
  421. if err := batch.Write(); err != nil {
  422. log.Crit("Failed to write leftover snapshot", "err", err)
  423. }
  424. res := &diskLayer{
  425. root: bottom.root,
  426. cache: base.cache,
  427. diskdb: base.diskdb,
  428. triedb: base.triedb,
  429. genMarker: base.genMarker,
  430. }
  431. // If snapshot generation hasn't finished yet, port over all the starts and
  432. // continue where the previous round left off.
  433. //
  434. // Note, the `base.genAbort` comparison is not used normally, it's checked
  435. // to allow the tests to play with the marker without triggering this path.
  436. if base.genMarker != nil && base.genAbort != nil {
  437. res.genMarker = base.genMarker
  438. res.genAbort = make(chan chan *generatorStats)
  439. go res.generate(stats)
  440. }
  441. return res
  442. }
  443. // Journal commits an entire diff hierarchy to disk into a single journal entry.
  444. // This is meant to be used during shutdown to persist the snapshot without
  445. // flattening everything down (bad for reorgs).
  446. //
  447. // The method returns the root hash of the base layer that needs to be persisted
  448. // to disk as a trie too to allow continuing any pending generation op.
  449. func (t *Tree) Journal(root common.Hash) (common.Hash, error) {
  450. // Retrieve the head snapshot to journal from var snap snapshot
  451. snap := t.Snapshot(root)
  452. if snap == nil {
  453. return common.Hash{}, fmt.Errorf("snapshot [%#x] missing", root)
  454. }
  455. // Run the journaling
  456. t.lock.Lock()
  457. defer t.lock.Unlock()
  458. journal := new(bytes.Buffer)
  459. base, err := snap.(snapshot).Journal(journal)
  460. if err != nil {
  461. return common.Hash{}, err
  462. }
  463. // Store the journal into the database and return
  464. rawdb.WriteSnapshotJournal(t.diskdb, journal.Bytes())
  465. return base, nil
  466. }
  467. // Rebuild wipes all available snapshot data from the persistent database and
  468. // discard all caches and diff layers. Afterwards, it starts a new snapshot
  469. // generator with the given root hash.
  470. func (t *Tree) Rebuild(root common.Hash) {
  471. t.lock.Lock()
  472. defer t.lock.Unlock()
  473. // Track whether there's a wipe currently running and keep it alive if so
  474. var wiper chan struct{}
  475. // Iterate over and mark all layers stale
  476. for _, layer := range t.layers {
  477. switch layer := layer.(type) {
  478. case *diskLayer:
  479. // If the base layer is generating, abort it and save
  480. if layer.genAbort != nil {
  481. abort := make(chan *generatorStats)
  482. layer.genAbort <- abort
  483. if stats := <-abort; stats != nil {
  484. wiper = stats.wiping
  485. }
  486. }
  487. // Layer should be inactive now, mark it as stale
  488. layer.lock.Lock()
  489. layer.stale = true
  490. layer.lock.Unlock()
  491. case *diffLayer:
  492. // If the layer is a simple diff, simply mark as stale
  493. layer.lock.Lock()
  494. layer.stale = true
  495. layer.lock.Unlock()
  496. default:
  497. panic(fmt.Sprintf("unknown layer type: %T", layer))
  498. }
  499. }
  500. // Start generating a new snapshot from scratch on a backgroung thread. The
  501. // generator will run a wiper first if there's not one running right now.
  502. log.Info("Rebuilding state snapshot")
  503. t.layers = map[common.Hash]snapshot{
  504. root: generateSnapshot(t.diskdb, t.triedb, t.cache, root, wiper),
  505. }
  506. }