snapshot.go 21 KB

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