snapshot.go 22 KB

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