snapshot.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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/rlp"
  30. "github.com/ethereum/go-ethereum/trie"
  31. )
  32. var (
  33. snapshotCleanAccountHitMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/hit", nil)
  34. snapshotCleanAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/miss", nil)
  35. snapshotCleanAccountInexMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/inex", nil)
  36. snapshotCleanAccountReadMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/read", nil)
  37. snapshotCleanAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/write", nil)
  38. snapshotCleanStorageHitMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/hit", nil)
  39. snapshotCleanStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/miss", nil)
  40. snapshotCleanStorageInexMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/inex", nil)
  41. snapshotCleanStorageReadMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/read", nil)
  42. snapshotCleanStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/write", nil)
  43. snapshotDirtyAccountHitMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/hit", nil)
  44. snapshotDirtyAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/miss", nil)
  45. snapshotDirtyAccountInexMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/inex", nil)
  46. snapshotDirtyAccountReadMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/read", nil)
  47. snapshotDirtyAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/write", nil)
  48. snapshotDirtyStorageHitMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/hit", nil)
  49. snapshotDirtyStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/miss", nil)
  50. snapshotDirtyStorageInexMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/inex", nil)
  51. snapshotDirtyStorageReadMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/read", nil)
  52. snapshotDirtyStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/write", nil)
  53. snapshotDirtyAccountHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/account/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015))
  54. snapshotDirtyStorageHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/storage/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015))
  55. snapshotFlushAccountItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/item", nil)
  56. snapshotFlushAccountSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/size", nil)
  57. snapshotFlushStorageItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/item", nil)
  58. snapshotFlushStorageSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/size", nil)
  59. snapshotBloomIndexTimer = metrics.NewRegisteredResettingTimer("state/snapshot/bloom/index", nil)
  60. snapshotBloomErrorGauge = metrics.NewRegisteredGaugeFloat64("state/snapshot/bloom/error", nil)
  61. snapshotBloomAccountTrueHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/truehit", nil)
  62. snapshotBloomAccountFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/falsehit", nil)
  63. snapshotBloomAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/miss", nil)
  64. snapshotBloomStorageTrueHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/truehit", nil)
  65. snapshotBloomStorageFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/falsehit", nil)
  66. snapshotBloomStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/miss", nil)
  67. // ErrSnapshotStale is returned from data accessors if the underlying snapshot
  68. // layer had been invalidated due to the chain progressing forward far enough
  69. // to not maintain the layer's original state.
  70. ErrSnapshotStale = errors.New("snapshot stale")
  71. // ErrNotCoveredYet is returned from data accessors if the underlying snapshot
  72. // is being generated currently and the requested data item is not yet in the
  73. // range of accounts covered.
  74. ErrNotCoveredYet = errors.New("not covered yet")
  75. // ErrNotConstructed is returned if the callers want to iterate the snapshot
  76. // while the generation is not finished yet.
  77. ErrNotConstructed = errors.New("snapshot is not constructed")
  78. // errSnapshotCycle is returned if a snapshot is attempted to be inserted
  79. // that forms a cycle in the snapshot tree.
  80. errSnapshotCycle = errors.New("snapshot cycle")
  81. )
  82. // Snapshot represents the functionality supported by a snapshot storage layer.
  83. type Snapshot interface {
  84. // Root returns the root hash for which this snapshot was made.
  85. Root() common.Hash
  86. // Account directly retrieves the account associated with a particular hash in
  87. // the snapshot slim data format.
  88. Account(hash common.Hash) (*Account, error)
  89. // AccountRLP directly retrieves the account RLP associated with a particular
  90. // hash in the snapshot slim data format.
  91. AccountRLP(hash common.Hash) ([]byte, error)
  92. // Storage directly retrieves the storage data associated with a particular hash,
  93. // within a particular account.
  94. Storage(accountHash, storageHash common.Hash) ([]byte, error)
  95. }
  96. // snapshot is the internal version of the snapshot data layer that supports some
  97. // additional methods compared to the public API.
  98. type snapshot interface {
  99. Snapshot
  100. // Parent returns the subsequent layer of a snapshot, or nil if the base was
  101. // reached.
  102. //
  103. // Note, the method is an internal helper to avoid type switching between the
  104. // disk and diff layers. There is no locking involved.
  105. Parent() snapshot
  106. // Update creates a new layer on top of the existing snapshot diff tree with
  107. // the specified data items.
  108. //
  109. // Note, the maps are retained by the method to avoid copying everything.
  110. Update(blockRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer
  111. // Journal commits an entire diff hierarchy to disk into a single journal entry.
  112. // This is meant to be used during shutdown to persist the snapshot without
  113. // flattening everything down (bad for reorgs).
  114. Journal(buffer *bytes.Buffer) (common.Hash, error)
  115. // Stale return whether this layer has become stale (was flattened across) or
  116. // if it's still live.
  117. Stale() bool
  118. // AccountIterator creates an account iterator over an arbitrary layer.
  119. AccountIterator(seek common.Hash) AccountIterator
  120. // StorageIterator creates a storage iterator over an arbitrary layer.
  121. StorageIterator(account common.Hash, seek common.Hash) (StorageIterator, bool)
  122. }
  123. // Tree is an Ethereum state snapshot tree. It consists of one persistent base
  124. // layer backed by a key-value store, on top of which arbitrarily many in-memory
  125. // diff layers are topped. The memory diffs can form a tree with branching, but
  126. // the disk layer is singleton and common to all. If a reorg goes deeper than the
  127. // disk layer, everything needs to be deleted.
  128. //
  129. // The goal of a state snapshot is twofold: to allow direct access to account and
  130. // storage data to avoid expensive multi-level trie lookups; and to allow sorted,
  131. // cheap iteration of the account/storage tries for sync aid.
  132. type Tree struct {
  133. diskdb ethdb.KeyValueStore // Persistent database to store the snapshot
  134. triedb *trie.Database // In-memory cache to access the trie through
  135. cache int // Megabytes permitted to use for read caches
  136. layers map[common.Hash]snapshot // Collection of all known layers
  137. lock sync.RWMutex
  138. capLimit int
  139. }
  140. // New attempts to load an already existing snapshot from a persistent key-value
  141. // store (with a number of memory layers from a journal), ensuring that the head
  142. // of the snapshot matches the expected one.
  143. //
  144. // If the snapshot is missing or the disk layer is broken, the entire is deleted
  145. // and will be reconstructed from scratch based on the tries in the key-value
  146. // store, on a background thread. If the memory layers from the journal is not
  147. // continuous with disk layer or the journal is missing, all diffs will be discarded
  148. // iff it's in "recovery" mode, otherwise rebuild is mandatory.
  149. func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache, cap int, root common.Hash, async bool, rebuild bool, recovery bool) (*Tree, error) {
  150. // Create a new, empty snapshot tree
  151. snap := &Tree{
  152. diskdb: diskdb,
  153. triedb: triedb,
  154. cache: cache,
  155. capLimit: cap,
  156. layers: make(map[common.Hash]snapshot),
  157. }
  158. if !async {
  159. defer snap.waitBuild()
  160. }
  161. // Attempt to load a previously persisted snapshot and rebuild one if failed
  162. head, disabled, err := loadSnapshot(diskdb, triedb, cache, root, recovery)
  163. if disabled {
  164. log.Warn("Snapshot maintenance disabled (syncing)")
  165. return snap, nil
  166. }
  167. if err != nil {
  168. if rebuild {
  169. log.Warn("Failed to load snapshot, regenerating", "err", err)
  170. snap.Rebuild(root)
  171. return snap, nil
  172. }
  173. return nil, err // Bail out the error, don't rebuild automatically.
  174. }
  175. // Existing snapshot loaded, seed all the layers
  176. for head != nil {
  177. snap.layers[head.Root()] = head
  178. head = head.Parent()
  179. }
  180. log.Info("Snapshot loaded", "diskRoot", snap.diskRoot(), "root", root)
  181. return snap, nil
  182. }
  183. // waitBuild blocks until the snapshot finishes rebuilding. This method is meant
  184. // to be used by tests to ensure we're testing what we believe we are.
  185. func (t *Tree) waitBuild() {
  186. // Find the rebuild termination channel
  187. var done chan struct{}
  188. t.lock.RLock()
  189. for _, layer := range t.layers {
  190. if layer, ok := layer.(*diskLayer); ok {
  191. done = layer.genPending
  192. break
  193. }
  194. }
  195. t.lock.RUnlock()
  196. // Wait until the snapshot is generated
  197. if done != nil {
  198. <-done
  199. }
  200. }
  201. // Disable interrupts any pending snapshot generator, deletes all the snapshot
  202. // layers in memory and marks snapshots disabled globally. In order to resume
  203. // the snapshot functionality, the caller must invoke Rebuild.
  204. func (t *Tree) Disable() {
  205. // Interrupt any live snapshot layers
  206. t.lock.Lock()
  207. defer t.lock.Unlock()
  208. for _, layer := range t.layers {
  209. switch layer := layer.(type) {
  210. case *diskLayer:
  211. // If the base layer is generating, abort it
  212. if layer.genAbort != nil {
  213. abort := make(chan *generatorStats)
  214. layer.genAbort <- abort
  215. <-abort
  216. }
  217. // Layer should be inactive now, mark it as stale
  218. layer.lock.Lock()
  219. layer.stale = true
  220. layer.lock.Unlock()
  221. case *diffLayer:
  222. // If the layer is a simple diff, simply mark as stale
  223. layer.lock.Lock()
  224. atomic.StoreUint32(&layer.stale, 1)
  225. layer.lock.Unlock()
  226. default:
  227. panic(fmt.Sprintf("unknown layer type: %T", layer))
  228. }
  229. }
  230. t.layers = map[common.Hash]snapshot{}
  231. // Delete all snapshot liveness information from the database
  232. batch := t.diskdb.NewBatch()
  233. rawdb.WriteSnapshotDisabled(batch)
  234. rawdb.DeleteSnapshotRoot(batch)
  235. rawdb.DeleteSnapshotJournal(batch)
  236. rawdb.DeleteSnapshotGenerator(batch)
  237. rawdb.DeleteSnapshotRecoveryNumber(batch)
  238. // Note, we don't delete the sync progress
  239. if err := batch.Write(); err != nil {
  240. log.Crit("Failed to disable snapshots", "err", err)
  241. }
  242. }
  243. // Snapshot retrieves a snapshot belonging to the given block root, or nil if no
  244. // snapshot is maintained for that block.
  245. func (t *Tree) Snapshot(blockRoot common.Hash) Snapshot {
  246. t.lock.RLock()
  247. defer t.lock.RUnlock()
  248. return t.layers[blockRoot]
  249. }
  250. // Snapshots returns all visited layers from the topmost layer with specific
  251. // root and traverses downward. The layer amount is limited by the given number.
  252. // If nodisk is set, then disk layer is excluded.
  253. func (t *Tree) Snapshots(root common.Hash, limits int, nodisk bool) []Snapshot {
  254. t.lock.RLock()
  255. defer t.lock.RUnlock()
  256. if limits == 0 {
  257. return nil
  258. }
  259. layer := t.layers[root]
  260. if layer == nil {
  261. return nil
  262. }
  263. var ret []Snapshot
  264. for {
  265. if _, isdisk := layer.(*diskLayer); isdisk && nodisk {
  266. break
  267. }
  268. ret = append(ret, layer)
  269. limits -= 1
  270. if limits == 0 {
  271. break
  272. }
  273. parent := layer.Parent()
  274. if parent == nil {
  275. break
  276. }
  277. layer = parent
  278. }
  279. return ret
  280. }
  281. // Update adds a new snapshot into the tree, if that can be linked to an existing
  282. // old parent. It is disallowed to insert a disk layer (the origin of all).
  283. func (t *Tree) Update(blockRoot common.Hash, parentRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) error {
  284. // Reject noop updates to avoid self-loops in the snapshot tree. This is a
  285. // special case that can only happen for Clique networks where empty blocks
  286. // don't modify the state (0 block subsidy).
  287. //
  288. // Although we could silently ignore this internally, it should be the caller's
  289. // responsibility to avoid even attempting to insert such a snapshot.
  290. if blockRoot == parentRoot {
  291. return errSnapshotCycle
  292. }
  293. // Generate a new snapshot on top of the parent
  294. parent := t.Snapshot(parentRoot)
  295. if parent == nil {
  296. return fmt.Errorf("parent [%#x] snapshot missing", parentRoot)
  297. }
  298. snap := parent.(snapshot).Update(blockRoot, destructs, accounts, storage)
  299. // Save the new snapshot for later
  300. t.lock.Lock()
  301. defer t.lock.Unlock()
  302. t.layers[snap.root] = snap
  303. log.Debug("Snapshot updated", "blockRoot", blockRoot)
  304. return nil
  305. }
  306. func (t *Tree) CapLimit() int {
  307. return t.capLimit
  308. }
  309. // Cap traverses downwards the snapshot tree from a head block hash until the
  310. // number of allowed layers are crossed. All layers beyond the permitted number
  311. // are flattened downwards.
  312. //
  313. // Note, the final diff layer count in general will be one more than the amount
  314. // requested. This happens because the bottom-most diff layer is the accumulator
  315. // which may or may not overflow and cascade to disk. Since this last layer's
  316. // survival is only known *after* capping, we need to omit it from the count if
  317. // we want to ensure that *at least* the requested number of diff layers remain.
  318. func (t *Tree) Cap(root common.Hash, layers int) error {
  319. // Retrieve the head snapshot to cap from
  320. snap := t.Snapshot(root)
  321. if snap == nil {
  322. return fmt.Errorf("snapshot [%#x] missing", root)
  323. }
  324. diff, ok := snap.(*diffLayer)
  325. if !ok {
  326. return fmt.Errorf("snapshot [%#x] is disk layer", root)
  327. }
  328. // If the generator is still running, use a more aggressive cap
  329. diff.origin.lock.RLock()
  330. if diff.origin.genMarker != nil && layers > 8 {
  331. layers = 8
  332. }
  333. diff.origin.lock.RUnlock()
  334. // Run the internal capping and discard all stale layers
  335. t.lock.Lock()
  336. defer t.lock.Unlock()
  337. // Flattening the bottom-most diff layer requires special casing since there's
  338. // no child to rewire to the grandparent. In that case we can fake a temporary
  339. // child for the capping and then remove it.
  340. if layers == 0 {
  341. // If full commit was requested, flatten the diffs and merge onto disk
  342. diff.lock.RLock()
  343. base := diffToDisk(diff.flatten().(*diffLayer))
  344. diff.lock.RUnlock()
  345. // Replace the entire snapshot tree with the flat base
  346. t.layers = map[common.Hash]snapshot{base.root: base}
  347. return nil
  348. }
  349. persisted := t.cap(diff, layers)
  350. // Remove any layer that is stale or links into a stale layer
  351. children := make(map[common.Hash][]common.Hash)
  352. for root, snap := range t.layers {
  353. if diff, ok := snap.(*diffLayer); ok {
  354. parent := diff.parent.Root()
  355. children[parent] = append(children[parent], root)
  356. }
  357. }
  358. var remove func(root common.Hash)
  359. remove = func(root common.Hash) {
  360. delete(t.layers, root)
  361. for _, child := range children[root] {
  362. remove(child)
  363. }
  364. delete(children, root)
  365. }
  366. for root, snap := range t.layers {
  367. if snap.Stale() {
  368. remove(root)
  369. }
  370. }
  371. // If the disk layer was modified, regenerate all the cumulative blooms
  372. if persisted != nil {
  373. var rebloom func(root common.Hash)
  374. rebloom = func(root common.Hash) {
  375. if diff, ok := t.layers[root].(*diffLayer); ok {
  376. diff.rebloom(persisted)
  377. }
  378. for _, child := range children[root] {
  379. rebloom(child)
  380. }
  381. }
  382. rebloom(persisted.root)
  383. }
  384. log.Debug("Snapshot capped", "root", root)
  385. return nil
  386. }
  387. // cap traverses downwards the diff tree until the number of allowed layers are
  388. // crossed. All diffs beyond the permitted number are flattened downwards. If the
  389. // layer limit is reached, memory cap is also enforced (but not before).
  390. //
  391. // The method returns the new disk layer if diffs were persisted into it.
  392. //
  393. // Note, the final diff layer count in general will be one more than the amount
  394. // requested. This happens because the bottom-most diff layer is the accumulator
  395. // which may or may not overflow and cascade to disk. Since this last layer's
  396. // survival is only known *after* capping, we need to omit it from the count if
  397. // we want to ensure that *at least* the requested number of diff layers remain.
  398. func (t *Tree) cap(diff *diffLayer, layers int) *diskLayer {
  399. // Dive until we run out of layers or reach the persistent database
  400. for i := 0; i < layers-1; i++ {
  401. // If we still have diff layers below, continue down
  402. if parent, ok := diff.parent.(*diffLayer); ok {
  403. diff = parent
  404. } else {
  405. // Diff stack too shallow, return without modifications
  406. return nil
  407. }
  408. }
  409. // We're out of layers, flatten anything below, stopping if it's the disk or if
  410. // the memory limit is not yet exceeded.
  411. switch parent := diff.parent.(type) {
  412. case *diskLayer:
  413. return nil
  414. case *diffLayer:
  415. // Flatten the parent into the grandparent. The flattening internally obtains a
  416. // write lock on grandparent.
  417. flattened := parent.flatten().(*diffLayer)
  418. t.layers[flattened.root] = flattened
  419. diff.lock.Lock()
  420. defer diff.lock.Unlock()
  421. diff.parent = flattened
  422. if flattened.memory < aggregatorMemoryLimit {
  423. // Accumulator layer is smaller than the limit, so we can abort, unless
  424. // there's a snapshot being generated currently. In that case, the trie
  425. // will move fron underneath the generator so we **must** merge all the
  426. // partial data down into the snapshot and restart the generation.
  427. if flattened.parent.(*diskLayer).genAbort == nil {
  428. return nil
  429. }
  430. }
  431. default:
  432. panic(fmt.Sprintf("unknown data layer: %T", parent))
  433. }
  434. // If the bottom-most layer is larger than our memory cap, persist to disk
  435. bottom := diff.parent.(*diffLayer)
  436. bottom.lock.RLock()
  437. base := diffToDisk(bottom)
  438. bottom.lock.RUnlock()
  439. t.layers[base.root] = base
  440. diff.parent = base
  441. return base
  442. }
  443. // diffToDisk merges a bottom-most diff into the persistent disk layer underneath
  444. // it. The method will panic if called onto a non-bottom-most diff layer.
  445. //
  446. // The disk layer persistence should be operated in an atomic way. All updates should
  447. // be discarded if the whole transition if not finished.
  448. func diffToDisk(bottom *diffLayer) *diskLayer {
  449. var (
  450. base = bottom.parent.(*diskLayer)
  451. batch = base.diskdb.NewBatch()
  452. stats *generatorStats
  453. )
  454. // If the disk layer is running a snapshot generator, abort it
  455. if base.genAbort != nil {
  456. abort := make(chan *generatorStats)
  457. base.genAbort <- abort
  458. stats = <-abort
  459. }
  460. // Put the deletion in the batch writer, flush all updates in the final step.
  461. rawdb.DeleteSnapshotRoot(batch)
  462. // Mark the original base as stale as we're going to create a new wrapper
  463. base.lock.Lock()
  464. if base.stale {
  465. panic("parent disk layer is stale") // we've committed into the same base from two children, boo
  466. }
  467. base.stale = true
  468. base.lock.Unlock()
  469. // Destroy all the destructed accounts from the database
  470. for hash := range bottom.destructSet {
  471. // Skip any account not covered yet by the snapshot
  472. if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 {
  473. continue
  474. }
  475. // Remove all storage slots
  476. rawdb.DeleteAccountSnapshot(batch, hash)
  477. base.cache.Set(hash[:], nil)
  478. it := rawdb.IterateStorageSnapshots(base.diskdb, hash)
  479. for it.Next() {
  480. if key := it.Key(); len(key) == 65 { // TODO(karalabe): Yuck, we should move this into the iterator
  481. batch.Delete(key)
  482. base.cache.Del(key[1:])
  483. snapshotFlushStorageItemMeter.Mark(1)
  484. // Ensure we don't delete too much data blindly (contract can be
  485. // huge). It's ok to flush, the root will go missing in case of a
  486. // crash and we'll detect and regenerate the snapshot.
  487. if batch.ValueSize() > ethdb.IdealBatchSize {
  488. if err := batch.Write(); err != nil {
  489. log.Crit("Failed to write storage deletions", "err", err)
  490. }
  491. batch.Reset()
  492. }
  493. }
  494. }
  495. it.Release()
  496. }
  497. // Push all updated accounts into the database
  498. for hash, data := range bottom.accountData {
  499. // Skip any account not covered yet by the snapshot
  500. if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 {
  501. continue
  502. }
  503. // Push the account to disk
  504. rawdb.WriteAccountSnapshot(batch, hash, data)
  505. base.cache.Set(hash[:], data)
  506. snapshotCleanAccountWriteMeter.Mark(int64(len(data)))
  507. snapshotFlushAccountItemMeter.Mark(1)
  508. snapshotFlushAccountSizeMeter.Mark(int64(len(data)))
  509. // Ensure we don't write too much data blindly. It's ok to flush, the
  510. // root will go missing in case of a crash and we'll detect and regen
  511. // the snapshot.
  512. if batch.ValueSize() > ethdb.IdealBatchSize {
  513. if err := batch.Write(); err != nil {
  514. log.Crit("Failed to write storage deletions", "err", err)
  515. }
  516. batch.Reset()
  517. }
  518. }
  519. // Push all the storage slots into the database
  520. for accountHash, storage := range bottom.storageData {
  521. // Skip any account not covered yet by the snapshot
  522. if base.genMarker != nil && bytes.Compare(accountHash[:], base.genMarker) > 0 {
  523. continue
  524. }
  525. // Generation might be mid-account, track that case too
  526. midAccount := base.genMarker != nil && bytes.Equal(accountHash[:], base.genMarker[:common.HashLength])
  527. for storageHash, data := range storage {
  528. // Skip any slot not covered yet by the snapshot
  529. if midAccount && bytes.Compare(storageHash[:], base.genMarker[common.HashLength:]) > 0 {
  530. continue
  531. }
  532. if len(data) > 0 {
  533. rawdb.WriteStorageSnapshot(batch, accountHash, storageHash, data)
  534. base.cache.Set(append(accountHash[:], storageHash[:]...), data)
  535. snapshotCleanStorageWriteMeter.Mark(int64(len(data)))
  536. } else {
  537. rawdb.DeleteStorageSnapshot(batch, accountHash, storageHash)
  538. base.cache.Set(append(accountHash[:], storageHash[:]...), nil)
  539. }
  540. snapshotFlushStorageItemMeter.Mark(1)
  541. snapshotFlushStorageSizeMeter.Mark(int64(len(data)))
  542. }
  543. }
  544. // Update the snapshot block marker and write any remainder data
  545. rawdb.WriteSnapshotRoot(batch, bottom.root)
  546. // Write out the generator progress marker and report
  547. journalProgress(batch, base.genMarker, stats)
  548. // Flush all the updates in the single db operation. Ensure the
  549. // disk layer transition is atomic.
  550. if err := batch.Write(); err != nil {
  551. log.Crit("Failed to write leftover snapshot", "err", err)
  552. }
  553. log.Debug("Journalled disk layer", "root", bottom.root, "complete", base.genMarker == nil)
  554. res := &diskLayer{
  555. root: bottom.root,
  556. cache: base.cache,
  557. diskdb: base.diskdb,
  558. triedb: base.triedb,
  559. genMarker: base.genMarker,
  560. genPending: base.genPending,
  561. }
  562. // If snapshot generation hasn't finished yet, port over all the starts and
  563. // continue where the previous round left off.
  564. //
  565. // Note, the `base.genAbort` comparison is not used normally, it's checked
  566. // to allow the tests to play with the marker without triggering this path.
  567. if base.genMarker != nil && base.genAbort != nil {
  568. res.genMarker = base.genMarker
  569. res.genAbort = make(chan chan *generatorStats)
  570. go res.generate(stats)
  571. }
  572. return res
  573. }
  574. // Journal commits an entire diff hierarchy to disk into a single journal entry.
  575. // This is meant to be used during shutdown to persist the snapshot without
  576. // flattening everything down (bad for reorgs).
  577. //
  578. // The method returns the root hash of the base layer that needs to be persisted
  579. // to disk as a trie too to allow continuing any pending generation op.
  580. func (t *Tree) Journal(root common.Hash) (common.Hash, error) {
  581. // Retrieve the head snapshot to journal from var snap snapshot
  582. snap := t.Snapshot(root)
  583. if snap == nil {
  584. return common.Hash{}, fmt.Errorf("snapshot [%#x] missing", root)
  585. }
  586. // Run the journaling
  587. t.lock.Lock()
  588. defer t.lock.Unlock()
  589. // Firstly write out the metadata of journal
  590. journal := new(bytes.Buffer)
  591. if err := rlp.Encode(journal, journalVersion); err != nil {
  592. return common.Hash{}, err
  593. }
  594. diskroot := t.diskRoot()
  595. if diskroot == (common.Hash{}) {
  596. return common.Hash{}, errors.New("invalid disk root")
  597. }
  598. // Secondly write out the disk layer root, ensure the
  599. // diff journal is continuous with disk.
  600. if err := rlp.Encode(journal, diskroot); err != nil {
  601. return common.Hash{}, err
  602. }
  603. // Finally write out the journal of each layer in reverse order.
  604. base, err := snap.(snapshot).Journal(journal)
  605. if err != nil {
  606. return common.Hash{}, err
  607. }
  608. // Store the journal into the database and return
  609. rawdb.WriteSnapshotJournal(t.diskdb, journal.Bytes())
  610. return base, nil
  611. }
  612. // Rebuild wipes all available snapshot data from the persistent database and
  613. // discard all caches and diff layers. Afterwards, it starts a new snapshot
  614. // generator with the given root hash.
  615. func (t *Tree) Rebuild(root common.Hash) {
  616. t.lock.Lock()
  617. defer t.lock.Unlock()
  618. // Firstly delete any recovery flag in the database. Because now we are
  619. // building a brand new snapshot. Also reenable the snapshot feature.
  620. rawdb.DeleteSnapshotRecoveryNumber(t.diskdb)
  621. rawdb.DeleteSnapshotDisabled(t.diskdb)
  622. // Iterate over and mark all layers stale
  623. for _, layer := range t.layers {
  624. switch layer := layer.(type) {
  625. case *diskLayer:
  626. // If the base layer is generating, abort it and save
  627. if layer.genAbort != nil {
  628. abort := make(chan *generatorStats)
  629. layer.genAbort <- abort
  630. <-abort
  631. }
  632. // Layer should be inactive now, mark it as stale
  633. layer.lock.Lock()
  634. layer.stale = true
  635. layer.lock.Unlock()
  636. case *diffLayer:
  637. // If the layer is a simple diff, simply mark as stale
  638. layer.lock.Lock()
  639. atomic.StoreUint32(&layer.stale, 1)
  640. layer.lock.Unlock()
  641. default:
  642. panic(fmt.Sprintf("unknown layer type: %T", layer))
  643. }
  644. }
  645. // Start generating a new snapshot from scratch on a background thread. The
  646. // generator will run a wiper first if there's not one running right now.
  647. log.Info("Rebuilding state snapshot")
  648. t.layers = map[common.Hash]snapshot{
  649. root: generateSnapshot(t.diskdb, t.triedb, t.cache, root),
  650. }
  651. }
  652. // AccountIterator creates a new account iterator for the specified root hash and
  653. // seeks to a starting account hash.
  654. func (t *Tree) AccountIterator(root common.Hash, seek common.Hash) (AccountIterator, error) {
  655. ok, err := t.generating()
  656. if err != nil {
  657. return nil, err
  658. }
  659. if ok {
  660. return nil, ErrNotConstructed
  661. }
  662. return newFastAccountIterator(t, root, seek)
  663. }
  664. // StorageIterator creates a new storage iterator for the specified root hash and
  665. // account. The iterator will be move to the specific start position.
  666. func (t *Tree) StorageIterator(root common.Hash, account common.Hash, seek common.Hash) (StorageIterator, error) {
  667. ok, err := t.generating()
  668. if err != nil {
  669. return nil, err
  670. }
  671. if ok {
  672. return nil, ErrNotConstructed
  673. }
  674. return newFastStorageIterator(t, root, account, seek)
  675. }
  676. // Verify iterates the whole state(all the accounts as well as the corresponding storages)
  677. // with the specific root and compares the re-computed hash with the original one.
  678. func (t *Tree) Verify(root common.Hash) error {
  679. acctIt, err := t.AccountIterator(root, common.Hash{})
  680. if err != nil {
  681. return err
  682. }
  683. defer acctIt.Release()
  684. got, err := generateTrieRoot(nil, acctIt, common.Hash{}, stackTrieGenerate, func(db ethdb.KeyValueWriter, accountHash, codeHash common.Hash, stat *generateStats) (common.Hash, error) {
  685. storageIt, err := t.StorageIterator(root, accountHash, common.Hash{})
  686. if err != nil {
  687. return common.Hash{}, err
  688. }
  689. defer storageIt.Release()
  690. hash, err := generateTrieRoot(nil, storageIt, accountHash, stackTrieGenerate, nil, stat, false)
  691. if err != nil {
  692. return common.Hash{}, err
  693. }
  694. return hash, nil
  695. }, newGenerateStats(), true)
  696. if err != nil {
  697. return err
  698. }
  699. if got != root {
  700. return fmt.Errorf("state root hash mismatch: got %x, want %x", got, root)
  701. }
  702. return nil
  703. }
  704. // disklayer is an internal helper function to return the disk layer.
  705. // The lock of snapTree is assumed to be held already.
  706. func (t *Tree) disklayer() *diskLayer {
  707. var snap snapshot
  708. for _, s := range t.layers {
  709. snap = s
  710. break
  711. }
  712. if snap == nil {
  713. return nil
  714. }
  715. switch layer := snap.(type) {
  716. case *diskLayer:
  717. return layer
  718. case *diffLayer:
  719. return layer.origin
  720. default:
  721. panic(fmt.Sprintf("%T: undefined layer", snap))
  722. }
  723. }
  724. // diskRoot is a internal helper function to return the disk layer root.
  725. // The lock of snapTree is assumed to be held already.
  726. func (t *Tree) diskRoot() common.Hash {
  727. disklayer := t.disklayer()
  728. if disklayer == nil {
  729. return common.Hash{}
  730. }
  731. return disklayer.Root()
  732. }
  733. // generating is an internal helper function which reports whether the snapshot
  734. // is still under the construction.
  735. func (t *Tree) generating() (bool, error) {
  736. t.lock.Lock()
  737. defer t.lock.Unlock()
  738. layer := t.disklayer()
  739. if layer == nil {
  740. return false, errors.New("disk layer is missing")
  741. }
  742. layer.lock.RLock()
  743. defer layer.lock.RUnlock()
  744. return layer.genMarker != nil, nil
  745. }
  746. // diskRoot is a external helper function to return the disk layer root.
  747. func (t *Tree) DiskRoot() common.Hash {
  748. t.lock.Lock()
  749. defer t.lock.Unlock()
  750. return t.diskRoot()
  751. }