snapshot.go 22 KB

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