snapshot.go 30 KB

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