snapshot.go 31 KB

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