github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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/zhiqiangxu/go-ethereum/common" 28 "github.com/zhiqiangxu/go-ethereum/core/rawdb" 29 "github.com/zhiqiangxu/go-ethereum/ethdb" 30 "github.com/zhiqiangxu/go-ethereum/log" 31 "github.com/zhiqiangxu/go-ethereum/metrics" 32 "github.com/zhiqiangxu/go-ethereum/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 ethdb.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 ethdb.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 // Run the internal capping and discard all stale layers 267 t.lock.Lock() 268 defer t.lock.Unlock() 269 270 // Flattening the bottom-most diff layer requires special casing since there's 271 // no child to rewire to the grandparent. In that case we can fake a temporary 272 // child for the capping and then remove it. 273 var persisted *diskLayer 274 275 switch layers { 276 case 0: 277 // If full commit was requested, flatten the diffs and merge onto disk 278 diff.lock.RLock() 279 base := diffToDisk(diff.flatten().(*diffLayer)) 280 diff.lock.RUnlock() 281 282 // Replace the entire snapshot tree with the flat base 283 t.layers = map[common.Hash]snapshot{base.root: base} 284 return nil 285 286 case 1: 287 // If full flattening was requested, flatten the diffs but only merge if the 288 // memory limit was reached 289 var ( 290 bottom *diffLayer 291 base *diskLayer 292 ) 293 diff.lock.RLock() 294 bottom = diff.flatten().(*diffLayer) 295 if bottom.memory >= aggregatorMemoryLimit { 296 base = diffToDisk(bottom) 297 } 298 diff.lock.RUnlock() 299 300 // If all diff layers were removed, replace the entire snapshot tree 301 if base != nil { 302 t.layers = map[common.Hash]snapshot{base.root: base} 303 return nil 304 } 305 // Merge the new aggregated layer into the snapshot tree, clean stales below 306 t.layers[bottom.root] = bottom 307 308 default: 309 // Many layers requested to be retained, cap normally 310 persisted = t.cap(diff, layers) 311 } 312 // Remove any layer that is stale or links into a stale layer 313 children := make(map[common.Hash][]common.Hash) 314 for root, snap := range t.layers { 315 if diff, ok := snap.(*diffLayer); ok { 316 parent := diff.parent.Root() 317 children[parent] = append(children[parent], root) 318 } 319 } 320 var remove func(root common.Hash) 321 remove = func(root common.Hash) { 322 delete(t.layers, root) 323 for _, child := range children[root] { 324 remove(child) 325 } 326 delete(children, root) 327 } 328 for root, snap := range t.layers { 329 if snap.Stale() { 330 remove(root) 331 } 332 } 333 // If the disk layer was modified, regenerate all the cumulative blooms 334 if persisted != nil { 335 var rebloom func(root common.Hash) 336 rebloom = func(root common.Hash) { 337 if diff, ok := t.layers[root].(*diffLayer); ok { 338 diff.rebloom(persisted) 339 } 340 for _, child := range children[root] { 341 rebloom(child) 342 } 343 } 344 rebloom(persisted.root) 345 } 346 return nil 347 } 348 349 // cap traverses downwards the diff tree until the number of allowed layers are 350 // crossed. All diffs beyond the permitted number are flattened downwards. If the 351 // layer limit is reached, memory cap is also enforced (but not before). 352 // 353 // The method returns the new disk layer if diffs were persistend into it. 354 func (t *Tree) cap(diff *diffLayer, layers int) *diskLayer { 355 // Dive until we run out of layers or reach the persistent database 356 for ; layers > 2; layers-- { 357 // If we still have diff layers below, continue down 358 if parent, ok := diff.parent.(*diffLayer); ok { 359 diff = parent 360 } else { 361 // Diff stack too shallow, return without modifications 362 return nil 363 } 364 } 365 // We're out of layers, flatten anything below, stopping if it's the disk or if 366 // the memory limit is not yet exceeded. 367 switch parent := diff.parent.(type) { 368 case *diskLayer: 369 return nil 370 371 case *diffLayer: 372 // Flatten the parent into the grandparent. The flattening internally obtains a 373 // write lock on grandparent. 374 flattened := parent.flatten().(*diffLayer) 375 t.layers[flattened.root] = flattened 376 377 diff.lock.Lock() 378 defer diff.lock.Unlock() 379 380 diff.parent = flattened 381 if flattened.memory < aggregatorMemoryLimit { 382 // Accumulator layer is smaller than the limit, so we can abort, unless 383 // there's a snapshot being generated currently. In that case, the trie 384 // will move fron underneath the generator so we **must** merge all the 385 // partial data down into the snapshot and restart the generation. 386 if flattened.parent.(*diskLayer).genAbort == nil { 387 return nil 388 } 389 } 390 default: 391 panic(fmt.Sprintf("unknown data layer: %T", parent)) 392 } 393 // If the bottom-most layer is larger than our memory cap, persist to disk 394 bottom := diff.parent.(*diffLayer) 395 396 bottom.lock.RLock() 397 base := diffToDisk(bottom) 398 bottom.lock.RUnlock() 399 400 t.layers[base.root] = base 401 diff.parent = base 402 return base 403 } 404 405 // diffToDisk merges a bottom-most diff into the persistent disk layer underneath 406 // it. The method will panic if called onto a non-bottom-most diff layer. 407 func diffToDisk(bottom *diffLayer) *diskLayer { 408 var ( 409 base = bottom.parent.(*diskLayer) 410 batch = base.diskdb.NewBatch() 411 stats *generatorStats 412 ) 413 // If the disk layer is running a snapshot generator, abort it 414 if base.genAbort != nil { 415 abort := make(chan *generatorStats) 416 base.genAbort <- abort 417 stats = <-abort 418 } 419 // Start by temporarily deleting the current snapshot block marker. This 420 // ensures that in the case of a crash, the entire snapshot is invalidated. 421 rawdb.DeleteSnapshotRoot(batch) 422 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 431 // Destroy all the destructed accounts from the database 432 for hash := range bottom.destructSet { 433 // Skip any account not covered yet by the snapshot 434 if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 { 435 continue 436 } 437 // Remove all storage slots 438 rawdb.DeleteAccountSnapshot(batch, hash) 439 base.cache.Set(hash[:], nil) 440 441 it := rawdb.IterateStorageSnapshots(base.diskdb, hash) 442 for it.Next() { 443 if key := it.Key(); len(key) == 65 { // TODO(karalabe): Yuck, we should move this into the iterator 444 batch.Delete(key) 445 base.cache.Del(key[1:]) 446 447 snapshotFlushStorageItemMeter.Mark(1) 448 } 449 } 450 it.Release() 451 } 452 // Push all updated accounts into the database 453 for hash, data := range bottom.accountData { 454 // Skip any account not covered yet by the snapshot 455 if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 { 456 continue 457 } 458 // Push the account to disk 459 rawdb.WriteAccountSnapshot(batch, hash, data) 460 base.cache.Set(hash[:], data) 461 snapshotCleanAccountWriteMeter.Mark(int64(len(data))) 462 463 if batch.ValueSize() > ethdb.IdealBatchSize { 464 if err := batch.Write(); err != nil { 465 log.Crit("Failed to write account snapshot", "err", err) 466 } 467 batch.Reset() 468 } 469 snapshotFlushAccountItemMeter.Mark(1) 470 snapshotFlushAccountSizeMeter.Mark(int64(len(data))) 471 } 472 // Push all the storage slots into the database 473 for accountHash, storage := range bottom.storageData { 474 // Skip any account not covered yet by the snapshot 475 if base.genMarker != nil && bytes.Compare(accountHash[:], base.genMarker) > 0 { 476 continue 477 } 478 // Generation might be mid-account, track that case too 479 midAccount := base.genMarker != nil && bytes.Equal(accountHash[:], base.genMarker[:common.HashLength]) 480 481 for storageHash, data := range storage { 482 // Skip any slot not covered yet by the snapshot 483 if midAccount && bytes.Compare(storageHash[:], base.genMarker[common.HashLength:]) > 0 { 484 continue 485 } 486 if len(data) > 0 { 487 rawdb.WriteStorageSnapshot(batch, accountHash, storageHash, data) 488 base.cache.Set(append(accountHash[:], storageHash[:]...), data) 489 snapshotCleanStorageWriteMeter.Mark(int64(len(data))) 490 } else { 491 rawdb.DeleteStorageSnapshot(batch, accountHash, storageHash) 492 base.cache.Set(append(accountHash[:], storageHash[:]...), nil) 493 } 494 snapshotFlushStorageItemMeter.Mark(1) 495 snapshotFlushStorageSizeMeter.Mark(int64(len(data))) 496 } 497 if batch.ValueSize() > ethdb.IdealBatchSize { 498 if err := batch.Write(); err != nil { 499 log.Crit("Failed to write storage snapshot", "err", err) 500 } 501 batch.Reset() 502 } 503 } 504 // Update the snapshot block marker and write any remainder data 505 rawdb.WriteSnapshotRoot(batch, bottom.root) 506 if err := batch.Write(); err != nil { 507 log.Crit("Failed to write leftover snapshot", "err", err) 508 } 509 res := &diskLayer{ 510 root: bottom.root, 511 cache: base.cache, 512 diskdb: base.diskdb, 513 triedb: base.triedb, 514 genMarker: base.genMarker, 515 genPending: base.genPending, 516 } 517 // If snapshot generation hasn't finished yet, port over all the starts and 518 // continue where the previous round left off. 519 // 520 // Note, the `base.genAbort` comparison is not used normally, it's checked 521 // to allow the tests to play with the marker without triggering this path. 522 if base.genMarker != nil && base.genAbort != nil { 523 res.genMarker = base.genMarker 524 res.genAbort = make(chan chan *generatorStats) 525 go res.generate(stats) 526 } 527 return res 528 } 529 530 // Journal commits an entire diff hierarchy to disk into a single journal entry. 531 // This is meant to be used during shutdown to persist the snapshot without 532 // flattening everything down (bad for reorgs). 533 // 534 // The method returns the root hash of the base layer that needs to be persisted 535 // to disk as a trie too to allow continuing any pending generation op. 536 func (t *Tree) Journal(root common.Hash) (common.Hash, error) { 537 // Retrieve the head snapshot to journal from var snap snapshot 538 snap := t.Snapshot(root) 539 if snap == nil { 540 return common.Hash{}, fmt.Errorf("snapshot [%#x] missing", root) 541 } 542 // Run the journaling 543 t.lock.Lock() 544 defer t.lock.Unlock() 545 546 journal := new(bytes.Buffer) 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 556 // Rebuild wipes all available snapshot data from the persistent database and 557 // discard all caches and diff layers. Afterwards, it starts a new snapshot 558 // generator with the given root hash. 559 func (t *Tree) Rebuild(root common.Hash) { 560 t.lock.Lock() 561 defer t.lock.Unlock() 562 563 // Track whether there's a wipe currently running and keep it alive if so 564 var wiper chan struct{} 565 566 // Iterate over and mark all layers stale 567 for _, layer := range t.layers { 568 switch layer := layer.(type) { 569 case *diskLayer: 570 // If the base layer is generating, abort it and save 571 if layer.genAbort != nil { 572 abort := make(chan *generatorStats) 573 layer.genAbort <- abort 574 575 if stats := <-abort; stats != nil { 576 wiper = stats.wiping 577 } 578 } 579 // Layer should be inactive now, mark it as stale 580 layer.lock.Lock() 581 layer.stale = true 582 layer.lock.Unlock() 583 584 case *diffLayer: 585 // If the layer is a simple diff, simply mark as stale 586 layer.lock.Lock() 587 atomic.StoreUint32(&layer.stale, 1) 588 layer.lock.Unlock() 589 590 default: 591 panic(fmt.Sprintf("unknown layer type: %T", layer)) 592 } 593 } 594 // Start generating a new snapshot from scratch on a backgroung thread. The 595 // generator will run a wiper first if there's not one running right now. 596 log.Info("Rebuilding state snapshot") 597 t.layers = map[common.Hash]snapshot{ 598 root: generateSnapshot(t.diskdb, t.triedb, t.cache, root, wiper), 599 } 600 } 601 602 // AccountIterator creates a new account iterator for the specified root hash and 603 // seeks to a starting account hash. 604 func (t *Tree) AccountIterator(root common.Hash, seek common.Hash) (AccountIterator, error) { 605 return newFastAccountIterator(t, root, seek) 606 } 607 608 // StorageIterator creates a new storage iterator for the specified root hash and 609 // account. The iterator will be move to the specific start position. 610 func (t *Tree) StorageIterator(root common.Hash, account common.Hash, seek common.Hash) (StorageIterator, error) { 611 return newFastStorageIterator(t, root, account, seek) 612 }