snapshot.go 30 KB

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