snapshot.go 28 KB

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