github.com/ccm-chain/ccmchain@v1.0.0/core/state/snapshot/snapshot.go (about) 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 17 // Package snapshot implements a journalled, dynamic state dump. 18 package snapshot 19 20 import ( 21 "bytes" 22 "errors" 23 "fmt" 24 "sync" 25 "sync/atomic" 26 27 "github.com/ccm-chain/ccmchain/common" 28 "github.com/ccm-chain/ccmchain/core/rawdb" 29 "github.com/ccm-chain/ccmchain/database" 30 "github.com/ccm-chain/ccmchain/log" 31 "github.com/ccm-chain/ccmchain/metrics" 32 "github.com/ccm-chain/ccmchain/trie" 33 ) 34 35 var ( 36 snapshotCleanAccountHitMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/hit", nil) 37 snapshotCleanAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/miss", nil) 38 snapshotCleanAccountInexMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/inex", nil) 39 snapshotCleanAccountReadMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/read", nil) 40 snapshotCleanAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/write", nil) 41 42 snapshotCleanStorageHitMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/hit", nil) 43 snapshotCleanStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/miss", nil) 44 snapshotCleanStorageInexMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/inex", nil) 45 snapshotCleanStorageReadMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/read", nil) 46 snapshotCleanStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/write", nil) 47 48 snapshotDirtyAccountHitMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/hit", nil) 49 snapshotDirtyAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/miss", nil) 50 snapshotDirtyAccountInexMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/inex", nil) 51 snapshotDirtyAccountReadMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/read", nil) 52 snapshotDirtyAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/write", nil) 53 54 snapshotDirtyStorageHitMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/hit", nil) 55 snapshotDirtyStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/miss", nil) 56 snapshotDirtyStorageInexMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/inex", nil) 57 snapshotDirtyStorageReadMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/read", nil) 58 snapshotDirtyStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/write", nil) 59 60 snapshotDirtyAccountHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/account/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015)) 61 snapshotDirtyStorageHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/storage/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015)) 62 63 snapshotFlushAccountItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/item", nil) 64 snapshotFlushAccountSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/size", nil) 65 snapshotFlushStorageItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/item", nil) 66 snapshotFlushStorageSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/size", nil) 67 68 snapshotBloomIndexTimer = metrics.NewRegisteredResettingTimer("state/snapshot/bloom/index", nil) 69 snapshotBloomErrorGauge = metrics.NewRegisteredGaugeFloat64("state/snapshot/bloom/error", nil) 70 71 snapshotBloomAccountTrueHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/truehit", nil) 72 snapshotBloomAccountFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/falsehit", nil) 73 snapshotBloomAccountMissMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/miss", nil) 74 75 snapshotBloomStorageTrueHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/truehit", nil) 76 snapshotBloomStorageFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/falsehit", nil) 77 snapshotBloomStorageMissMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/miss", nil) 78 79 // ErrSnapshotStale is returned from data accessors if the underlying snapshot 80 // layer had been invalidated due to the chain progressing forward far enough 81 // to not maintain the layer's original state. 82 ErrSnapshotStale = errors.New("snapshot stale") 83 84 // ErrNotCoveredYet is returned from data accessors if the underlying snapshot 85 // is being generated currently and the requested data item is not yet in the 86 // range of accounts covered. 87 ErrNotCoveredYet = errors.New("not covered yet") 88 89 // errSnapshotCycle is returned if a snapshot is attempted to be inserted 90 // that forms a cycle in the snapshot tree. 91 errSnapshotCycle = errors.New("snapshot cycle") 92 ) 93 94 // Snapshot represents the functionality supported by a snapshot storage layer. 95 type Snapshot interface { 96 // Root returns the root hash for which this snapshot was made. 97 Root() common.Hash 98 99 // Account directly retrieves the account associated with a particular hash in 100 // the snapshot slim data format. 101 Account(hash common.Hash) (*Account, error) 102 103 // AccountRLP directly retrieves the account RLP associated with a particular 104 // hash in the snapshot slim data format. 105 AccountRLP(hash common.Hash) ([]byte, error) 106 107 // Storage directly retrieves the storage data associated with a particular hash, 108 // within a particular account. 109 Storage(accountHash, storageHash common.Hash) ([]byte, error) 110 } 111 112 // snapshot is the internal version of the snapshot data layer that supports some 113 // additional methods compared to the public API. 114 type snapshot interface { 115 Snapshot 116 117 // Parent returns the subsequent layer of a snapshot, or nil if the base was 118 // reached. 119 // 120 // Note, the method is an internal helper to avoid type switching between the 121 // disk and diff layers. There is no locking involved. 122 Parent() snapshot 123 124 // Update creates a new layer on top of the existing snapshot diff tree with 125 // the specified data items. 126 // 127 // Note, the maps are retained by the method to avoid copying everything. 128 Update(blockRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer 129 130 // Journal commits an entire diff hierarchy to disk into a single journal entry. 131 // This is meant to be used during shutdown to persist the snapshot without 132 // flattening everything down (bad for reorgs). 133 Journal(buffer *bytes.Buffer) (common.Hash, error) 134 135 // Stale return whether this layer has become stale (was flattened across) or 136 // if it's still live. 137 Stale() bool 138 139 // AccountIterator creates an account iterator over an arbitrary layer. 140 AccountIterator(seek common.Hash) AccountIterator 141 142 // StorageIterator creates a storage iterator over an arbitrary layer. 143 StorageIterator(account common.Hash, seek common.Hash) (StorageIterator, bool) 144 } 145 146 // SnapshotTree is an Ethereum state snapshot tree. It consists of one persistent 147 // base layer backed by a key-value store, on top of which arbitrarily many in- 148 // memory diff layers are topped. The memory diffs can form a tree with branching, 149 // but the disk layer is singleton and common to all. If a reorg goes deeper than 150 // the disk layer, everything needs to be deleted. 151 // 152 // The goal of a state snapshot is twofold: to allow direct access to account and 153 // storage data to avoid expensive multi-level trie lookups; and to allow sorted, 154 // cheap iteration of the account/storage tries for sync aid. 155 type Tree struct { 156 diskdb database.KeyValueStore // Persistent database to store the snapshot 157 triedb *trie.Database // In-memory cache to access the trie through 158 cache int // Megabytes permitted to use for read caches 159 layers map[common.Hash]snapshot // Collection of all known layers 160 lock sync.RWMutex 161 } 162 163 // New attempts to load an already existing snapshot from a persistent key-value 164 // store (with a number of memory layers from a journal), ensuring that the head 165 // of the snapshot matches the expected one. 166 // 167 // If the snapshot is missing or inconsistent, the entirety is deleted and will 168 // be reconstructed from scratch based on the tries in the key-value store, on a 169 // background thread. 170 func New(diskdb database.KeyValueStore, triedb *trie.Database, cache int, root common.Hash, async bool) *Tree { 171 // Create a new, empty snapshot tree 172 snap := &Tree{ 173 diskdb: diskdb, 174 triedb: triedb, 175 cache: cache, 176 layers: make(map[common.Hash]snapshot), 177 } 178 if !async { 179 defer snap.waitBuild() 180 } 181 // Attempt to load a previously persisted snapshot and rebuild one if failed 182 head, err := loadSnapshot(diskdb, triedb, cache, root) 183 if err != nil { 184 log.Warn("Failed to load snapshot, regenerating", "err", err) 185 snap.Rebuild(root) 186 return snap 187 } 188 // Existing snapshot loaded, seed all the layers 189 for head != nil { 190 snap.layers[head.Root()] = head 191 head = head.Parent() 192 } 193 return snap 194 } 195 196 // waitBuild blocks until the snapshot finishes rebuilding. This method is meant 197 // to be used by tests to ensure we're testing what we believe we are. 198 func (t *Tree) waitBuild() { 199 // Find the rebuild termination channel 200 var done chan struct{} 201 202 t.lock.RLock() 203 for _, layer := range t.layers { 204 if layer, ok := layer.(*diskLayer); ok { 205 done = layer.genPending 206 break 207 } 208 } 209 t.lock.RUnlock() 210 211 // Wait until the snapshot is generated 212 if done != nil { 213 <-done 214 } 215 } 216 217 // Snapshot retrieves a snapshot belonging to the given block root, or nil if no 218 // snapshot is maintained for that block. 219 func (t *Tree) Snapshot(blockRoot common.Hash) Snapshot { 220 t.lock.RLock() 221 defer t.lock.RUnlock() 222 223 return t.layers[blockRoot] 224 } 225 226 // Update adds a new snapshot into the tree, if that can be linked to an existing 227 // old parent. It is disallowed to insert a disk layer (the origin of all). 228 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 { 229 // Reject noop updates to avoid self-loops in the snapshot tree. This is a 230 // special case that can only happen for Clique networks where empty blocks 231 // don't modify the state (0 block subsidy). 232 // 233 // Although we could silently ignore this internally, it should be the caller's 234 // responsibility to avoid even attempting to insert such a snapshot. 235 if blockRoot == parentRoot { 236 return errSnapshotCycle 237 } 238 // Generate a new snapshot on top of the parent 239 parent := t.Snapshot(parentRoot).(snapshot) 240 if parent == nil { 241 return fmt.Errorf("parent [%#x] snapshot missing", parentRoot) 242 } 243 snap := parent.Update(blockRoot, destructs, accounts, storage) 244 245 // Save the new snapshot for later 246 t.lock.Lock() 247 defer t.lock.Unlock() 248 249 t.layers[snap.root] = snap 250 return nil 251 } 252 253 // Cap traverses downwards the snapshot tree from a head block hash until the 254 // number of allowed layers are crossed. All layers beyond the permitted number 255 // are flattened downwards. 256 func (t *Tree) Cap(root common.Hash, layers int) error { 257 // Retrieve the head snapshot to cap from 258 snap := t.Snapshot(root) 259 if snap == nil { 260 return fmt.Errorf("snapshot [%#x] missing", root) 261 } 262 diff, ok := snap.(*diffLayer) 263 if !ok { 264 return fmt.Errorf("snapshot [%#x] is disk layer", root) 265 } 266 // If the generator is still running, use a more aggressive cap 267 diff.origin.lock.RLock() 268 if diff.origin.genMarker != nil && layers > 8 { 269 layers = 8 270 } 271 diff.origin.lock.RUnlock() 272 273 // Run the internal capping and discard all stale layers 274 t.lock.Lock() 275 defer t.lock.Unlock() 276 277 // Flattening the bottom-most diff layer requires special casing since there's 278 // no child to rewire to the grandparent. In that case we can fake a temporary 279 // child for the capping and then remove it. 280 var persisted *diskLayer 281 282 switch layers { 283 case 0: 284 // If full commit was requested, flatten the diffs and merge onto disk 285 diff.lock.RLock() 286 base := diffToDisk(diff.flatten().(*diffLayer)) 287 diff.lock.RUnlock() 288 289 // Replace the entire snapshot tree with the flat base 290 t.layers = map[common.Hash]snapshot{base.root: base} 291 return nil 292 293 case 1: 294 // If full flattening was requested, flatten the diffs but only merge if the 295 // memory limit was reached 296 var ( 297 bottom *diffLayer 298 base *diskLayer 299 ) 300 diff.lock.RLock() 301 bottom = diff.flatten().(*diffLayer) 302 if bottom.memory >= aggregatorMemoryLimit { 303 base = diffToDisk(bottom) 304 } 305 diff.lock.RUnlock() 306 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 315 default: 316 // Many layers requested to be retained, cap normally 317 persisted = t.cap(diff, layers) 318 } 319 // Remove any layer that is stale or links into a stale layer 320 children := make(map[common.Hash][]common.Hash) 321 for root, snap := range t.layers { 322 if diff, ok := snap.(*diffLayer); ok { 323 parent := diff.parent.Root() 324 children[parent] = append(children[parent], root) 325 } 326 } 327 var remove func(root common.Hash) 328 remove = func(root common.Hash) { 329 delete(t.layers, root) 330 for _, child := range children[root] { 331 remove(child) 332 } 333 delete(children, root) 334 } 335 for root, snap := range t.layers { 336 if snap.Stale() { 337 remove(root) 338 } 339 } 340 // If the disk layer was modified, regenerate all the cumulative blooms 341 if persisted != nil { 342 var rebloom func(root common.Hash) 343 rebloom = func(root common.Hash) { 344 if diff, ok := t.layers[root].(*diffLayer); ok { 345 diff.rebloom(persisted) 346 } 347 for _, child := range children[root] { 348 rebloom(child) 349 } 350 } 351 rebloom(persisted.root) 352 } 353 return nil 354 } 355 356 // cap traverses downwards the diff tree until the number of allowed layers are 357 // crossed. All diffs beyond the permitted number are flattened downwards. If the 358 // layer limit is reached, memory cap is also enforced (but not before). 359 // 360 // The method returns the new disk layer if diffs were persistend into it. 361 func (t *Tree) cap(diff *diffLayer, layers int) *diskLayer { 362 // Dive until we run out of layers or reach the persistent database 363 for ; layers > 2; layers-- { 364 // If we still have diff layers below, continue down 365 if parent, ok := diff.parent.(*diffLayer); ok { 366 diff = parent 367 } else { 368 // Diff stack too shallow, return without modifications 369 return nil 370 } 371 } 372 // We're out of layers, flatten anything below, stopping if it's the disk or if 373 // the memory limit is not yet exceeded. 374 switch parent := diff.parent.(type) { 375 case *diskLayer: 376 return nil 377 378 case *diffLayer: 379 // Flatten the parent into the grandparent. The flattening internally obtains a 380 // write lock on grandparent. 381 flattened := parent.flatten().(*diffLayer) 382 t.layers[flattened.root] = flattened 383 384 diff.lock.Lock() 385 defer diff.lock.Unlock() 386 387 diff.parent = flattened 388 if flattened.memory < aggregatorMemoryLimit { 389 // Accumulator layer is smaller than the limit, so we can abort, unless 390 // there's a snapshot being generated currently. In that case, the trie 391 // will move fron underneath the generator so we **must** merge all the 392 // partial data down into the snapshot and restart the generation. 393 if flattened.parent.(*diskLayer).genAbort == nil { 394 return nil 395 } 396 } 397 default: 398 panic(fmt.Sprintf("unknown data layer: %T", parent)) 399 } 400 // If the bottom-most layer is larger than our memory cap, persist to disk 401 bottom := diff.parent.(*diffLayer) 402 403 bottom.lock.RLock() 404 base := diffToDisk(bottom) 405 bottom.lock.RUnlock() 406 407 t.layers[base.root] = base 408 diff.parent = base 409 return base 410 } 411 412 // diffToDisk merges a bottom-most diff into the persistent disk layer underneath 413 // it. The method will panic if called onto a non-bottom-most diff layer. 414 func diffToDisk(bottom *diffLayer) *diskLayer { 415 var ( 416 base = bottom.parent.(*diskLayer) 417 batch = base.diskdb.NewBatch() 418 stats *generatorStats 419 ) 420 // If the disk layer is running a snapshot generator, abort it 421 if base.genAbort != nil { 422 abort := make(chan *generatorStats) 423 base.genAbort <- abort 424 stats = <-abort 425 } 426 // Start by temporarily deleting the current snapshot block marker. This 427 // ensures that in the case of a crash, the entire snapshot is invalidated. 428 rawdb.DeleteSnapshotRoot(batch) 429 430 // Mark the original base as stale as we're going to create a new wrapper 431 base.lock.Lock() 432 if base.stale { 433 panic("parent disk layer is stale") // we've committed into the same base from two children, boo 434 } 435 base.stale = true 436 base.lock.Unlock() 437 438 // Destroy all the destructed accounts from the database 439 for hash := range bottom.destructSet { 440 // Skip any account not covered yet by the snapshot 441 if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 { 442 continue 443 } 444 // Remove all storage slots 445 rawdb.DeleteAccountSnapshot(batch, hash) 446 base.cache.Set(hash[:], nil) 447 448 it := rawdb.IterateStorageSnapshots(base.diskdb, hash) 449 for it.Next() { 450 if key := it.Key(); len(key) == 65 { // TODO(karalabe): Yuck, we should move this into the iterator 451 batch.Delete(key) 452 base.cache.Del(key[1:]) 453 454 snapshotFlushStorageItemMeter.Mark(1) 455 } 456 } 457 it.Release() 458 } 459 // Push all updated accounts into the database 460 for hash, data := range bottom.accountData { 461 // Skip any account not covered yet by the snapshot 462 if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 { 463 continue 464 } 465 // Push the account to disk 466 rawdb.WriteAccountSnapshot(batch, hash, data) 467 base.cache.Set(hash[:], data) 468 snapshotCleanAccountWriteMeter.Mark(int64(len(data))) 469 470 if batch.ValueSize() > database.IdealBatchSize { 471 if err := batch.Write(); err != nil { 472 log.Crit("Failed to write account snapshot", "err", err) 473 } 474 batch.Reset() 475 } 476 snapshotFlushAccountItemMeter.Mark(1) 477 snapshotFlushAccountSizeMeter.Mark(int64(len(data))) 478 } 479 // Push all the storage slots into the database 480 for accountHash, storage := range bottom.storageData { 481 // Skip any account not covered yet by the snapshot 482 if base.genMarker != nil && bytes.Compare(accountHash[:], base.genMarker) > 0 { 483 continue 484 } 485 // Generation might be mid-account, track that case too 486 midAccount := base.genMarker != nil && bytes.Equal(accountHash[:], base.genMarker[:common.HashLength]) 487 488 for storageHash, data := range storage { 489 // Skip any slot not covered yet by the snapshot 490 if midAccount && bytes.Compare(storageHash[:], base.genMarker[common.HashLength:]) > 0 { 491 continue 492 } 493 if len(data) > 0 { 494 rawdb.WriteStorageSnapshot(batch, accountHash, storageHash, data) 495 base.cache.Set(append(accountHash[:], storageHash[:]...), data) 496 snapshotCleanStorageWriteMeter.Mark(int64(len(data))) 497 } else { 498 rawdb.DeleteStorageSnapshot(batch, accountHash, storageHash) 499 base.cache.Set(append(accountHash[:], storageHash[:]...), nil) 500 } 501 snapshotFlushStorageItemMeter.Mark(1) 502 snapshotFlushStorageSizeMeter.Mark(int64(len(data))) 503 } 504 if batch.ValueSize() > database.IdealBatchSize { 505 if err := batch.Write(); err != nil { 506 log.Crit("Failed to write storage snapshot", "err", err) 507 } 508 batch.Reset() 509 } 510 } 511 // Update the snapshot block marker and write any remainder data 512 rawdb.WriteSnapshotRoot(batch, bottom.root) 513 if err := batch.Write(); err != nil { 514 log.Crit("Failed to write leftover snapshot", "err", err) 515 } 516 res := &diskLayer{ 517 root: bottom.root, 518 cache: base.cache, 519 diskdb: base.diskdb, 520 triedb: base.triedb, 521 genMarker: base.genMarker, 522 genPending: base.genPending, 523 } 524 // If snapshot generation hasn't finished yet, port over all the starts and 525 // continue where the previous round left off. 526 // 527 // Note, the `base.genAbort` comparison is not used normally, it's checked 528 // to allow the tests to play with the marker without triggering this path. 529 if base.genMarker != nil && base.genAbort != nil { 530 res.genMarker = base.genMarker 531 res.genAbort = make(chan chan *generatorStats) 532 go res.generate(stats) 533 } 534 return res 535 } 536 537 // Journal commits an entire diff hierarchy to disk into a single journal entry. 538 // This is meant to be used during shutdown to persist the snapshot without 539 // flattening everything down (bad for reorgs). 540 // 541 // The method returns the root hash of the base layer that needs to be persisted 542 // to disk as a trie too to allow continuing any pending generation op. 543 func (t *Tree) Journal(root common.Hash) (common.Hash, error) { 544 // Retrieve the head snapshot to journal from var snap snapshot 545 snap := t.Snapshot(root) 546 if snap == nil { 547 return common.Hash{}, fmt.Errorf("snapshot [%#x] missing", root) 548 } 549 // Run the journaling 550 t.lock.Lock() 551 defer t.lock.Unlock() 552 553 journal := new(bytes.Buffer) 554 base, err := snap.(snapshot).Journal(journal) 555 if err != nil { 556 return common.Hash{}, err 557 } 558 // Store the journal into the database and return 559 rawdb.WriteSnapshotJournal(t.diskdb, journal.Bytes()) 560 return base, nil 561 } 562 563 // Rebuild wipes all available snapshot data from the persistent database and 564 // discard all caches and diff layers. Afterwards, it starts a new snapshot 565 // generator with the given root hash. 566 func (t *Tree) Rebuild(root common.Hash) { 567 t.lock.Lock() 568 defer t.lock.Unlock() 569 570 // Track whether there's a wipe currently running and keep it alive if so 571 var wiper chan struct{} 572 573 // Iterate over and mark all layers stale 574 for _, layer := range t.layers { 575 switch layer := layer.(type) { 576 case *diskLayer: 577 // If the base layer is generating, abort it and save 578 if layer.genAbort != nil { 579 abort := make(chan *generatorStats) 580 layer.genAbort <- abort 581 582 if stats := <-abort; stats != nil { 583 wiper = stats.wiping 584 } 585 } 586 // Layer should be inactive now, mark it as stale 587 layer.lock.Lock() 588 layer.stale = true 589 layer.lock.Unlock() 590 591 case *diffLayer: 592 // If the layer is a simple diff, simply mark as stale 593 layer.lock.Lock() 594 atomic.StoreUint32(&layer.stale, 1) 595 layer.lock.Unlock() 596 597 default: 598 panic(fmt.Sprintf("unknown layer type: %T", layer)) 599 } 600 } 601 // Start generating a new snapshot from scratch on a backgroung thread. The 602 // generator will run a wiper first if there's not one running right now. 603 log.Info("Rebuilding state snapshot") 604 t.layers = map[common.Hash]snapshot{ 605 root: generateSnapshot(t.diskdb, t.triedb, t.cache, root, wiper), 606 } 607 } 608 609 // AccountIterator creates a new account iterator for the specified root hash and 610 // seeks to a starting account hash. 611 func (t *Tree) AccountIterator(root common.Hash, seek common.Hash) (AccountIterator, error) { 612 return newFastAccountIterator(t, root, seek) 613 } 614 615 // StorageIterator creates a new storage iterator for the specified root hash and 616 // account. The iterator will be move to the specific start position. 617 func (t *Tree) StorageIterator(root common.Hash, account common.Hash, seek common.Hash) (StorageIterator, error) { 618 return newFastStorageIterator(t, root, account, seek) 619 }