github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/eth/downloader/downloader.go (about) 1 // Copyright 2015 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 downloader contains the manual full chain synchronisation. 18 package downloader 19 20 import ( 21 "errors" 22 "fmt" 23 "math/big" 24 "sync" 25 "sync/atomic" 26 "time" 27 28 "github.com/ethxdao/go-ethereum/common" 29 "github.com/ethxdao/go-ethereum/core/rawdb" 30 "github.com/ethxdao/go-ethereum/core/state/snapshot" 31 "github.com/ethxdao/go-ethereum/core/types" 32 "github.com/ethxdao/go-ethereum/eth/protocols/snap" 33 "github.com/ethxdao/go-ethereum/ethdb" 34 "github.com/ethxdao/go-ethereum/event" 35 "github.com/ethxdao/go-ethereum/log" 36 "github.com/ethxdao/go-ethereum/params" 37 ) 38 39 var ( 40 MaxBlockFetch = 128 // Amount of blocks to be fetched per retrieval request 41 MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request 42 MaxSkeletonSize = 128 // Number of header fetches to need for a skeleton assembly 43 MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request 44 45 maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection) 46 maxHeadersProcess = 2048 // Number of header download results to import at once into the chain 47 maxResultsProcess = 2048 // Number of content download results to import at once into the chain 48 fullMaxForkAncestry uint64 = params.FullImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it) 49 lightMaxForkAncestry uint64 = params.LightImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it) 50 51 reorgProtThreshold = 48 // Threshold number of recent blocks to disable mini reorg protection 52 reorgProtHeaderDelay = 2 // Number of headers to delay delivering to cover mini reorgs 53 54 fsHeaderCheckFrequency = 100 // Verification frequency of the downloaded headers during snap sync 55 fsHeaderSafetyNet = 2048 // Number of headers to discard in case a chain violation is detected 56 fsHeaderForceVerify = 24 // Number of headers to verify before and after the pivot to accept it 57 fsHeaderContCheck = 3 * time.Second // Time interval to check for header continuations during state download 58 fsMinFullBlocks = 64 // Number of blocks to retrieve fully even in snap sync 59 ) 60 61 var ( 62 errBusy = errors.New("busy") 63 errUnknownPeer = errors.New("peer is unknown or unhealthy") 64 errBadPeer = errors.New("action from bad peer ignored") 65 errStallingPeer = errors.New("peer is stalling") 66 errUnsyncedPeer = errors.New("unsynced peer") 67 errNoPeers = errors.New("no peers to keep download active") 68 errTimeout = errors.New("timeout") 69 errEmptyHeaderSet = errors.New("empty header set by peer") 70 errPeersUnavailable = errors.New("no peers available or all tried for download") 71 errInvalidAncestor = errors.New("retrieved ancestor is invalid") 72 errInvalidChain = errors.New("retrieved hash chain is invalid") 73 errInvalidBody = errors.New("retrieved block body is invalid") 74 errInvalidReceipt = errors.New("retrieved receipt is invalid") 75 errCancelStateFetch = errors.New("state data download canceled (requested)") 76 errCancelContentProcessing = errors.New("content processing canceled (requested)") 77 errCanceled = errors.New("syncing canceled (requested)") 78 errTooOld = errors.New("peer's protocol version too old") 79 errNoAncestorFound = errors.New("no common ancestor found") 80 errNoPivotHeader = errors.New("pivot header is not found") 81 ErrMergeTransition = errors.New("legacy sync reached the merge") 82 ) 83 84 // peerDropFn is a callback type for dropping a peer detected as malicious. 85 type peerDropFn func(id string) 86 87 // badBlockFn is a callback for the async beacon sync to notify the caller that 88 // the origin header requested to sync to, produced a chain with a bad block. 89 type badBlockFn func(invalid *types.Header, origin *types.Header) 90 91 // headerTask is a set of downloaded headers to queue along with their precomputed 92 // hashes to avoid constant rehashing. 93 type headerTask struct { 94 headers []*types.Header 95 hashes []common.Hash 96 } 97 98 type Downloader struct { 99 mode uint32 // Synchronisation mode defining the strategy used (per sync cycle), use d.getMode() to get the SyncMode 100 mux *event.TypeMux // Event multiplexer to announce sync operation events 101 102 checkpoint uint64 // Checkpoint block number to enforce head against (e.g. snap sync) 103 genesis uint64 // Genesis block number to limit sync to (e.g. light client CHT) 104 queue *queue // Scheduler for selecting the hashes to download 105 peers *peerSet // Set of active peers from which download can proceed 106 107 stateDB ethdb.Database // Database to state sync into (and deduplicate via) 108 109 // Statistics 110 syncStatsChainOrigin uint64 // Origin block number where syncing started at 111 syncStatsChainHeight uint64 // Highest block number known when syncing started 112 syncStatsLock sync.RWMutex // Lock protecting the sync stats fields 113 114 lightchain LightChain 115 blockchain BlockChain 116 117 // Callbacks 118 dropPeer peerDropFn // Drops a peer for misbehaving 119 badBlock badBlockFn // Reports a block as rejected by the chain 120 121 // Status 122 synchroniseMock func(id string, hash common.Hash) error // Replacement for synchronise during testing 123 synchronising int32 124 notified int32 125 committed int32 126 ancientLimit uint64 // The maximum block number which can be regarded as ancient data. 127 128 // Channels 129 headerProcCh chan *headerTask // Channel to feed the header processor new tasks 130 131 // Skeleton sync 132 //skeleton *skeleton // Header skeleton to backfill the chain with (eth2 mode) 133 134 // State sync 135 pivotHeader *types.Header // Pivot block header to dynamically push the syncing state root 136 pivotLock sync.RWMutex // Lock protecting pivot header reads from updates 137 138 SnapSyncer *snap.Syncer // TODO(karalabe): make private! hack for now 139 stateSyncStart chan *stateSync 140 141 // Cancellation and termination 142 cancelPeer string // Identifier of the peer currently being used as the master (cancel on drop) 143 cancelCh chan struct{} // Channel to cancel mid-flight syncs 144 cancelLock sync.RWMutex // Lock to protect the cancel channel and peer in delivers 145 cancelWg sync.WaitGroup // Make sure all fetcher goroutines have exited. 146 147 quitCh chan struct{} // Quit channel to signal termination 148 quitLock sync.Mutex // Lock to prevent double closes 149 150 // Testing hooks 151 syncInitHook func(uint64, uint64) // Method to call upon initiating a new sync run 152 bodyFetchHook func([]*types.Header) // Method to call upon starting a block body fetch 153 receiptFetchHook func([]*types.Header) // Method to call upon starting a receipt fetch 154 chainInsertHook func([]*fetchResult) // Method to call upon inserting a chain of blocks (possibly in multiple invocations) 155 } 156 157 // LightChain encapsulates functions required to synchronise a light chain. 158 type LightChain interface { 159 // HasHeader verifies a header's presence in the local chain. 160 HasHeader(common.Hash, uint64) bool 161 162 // GetHeaderByHash retrieves a header from the local chain. 163 GetHeaderByHash(common.Hash) *types.Header 164 165 // CurrentHeader retrieves the head header from the local chain. 166 CurrentHeader() *types.Header 167 168 // GetTd returns the total difficulty of a local block. 169 GetTd(common.Hash, uint64) *big.Int 170 171 // InsertHeaderChain inserts a batch of headers into the local chain. 172 InsertHeaderChain([]*types.Header, int) (int, error) 173 174 // SetHead rewinds the local chain to a new head. 175 SetHead(uint64) error 176 } 177 178 // BlockChain encapsulates functions required to sync a (full or snap) blockchain. 179 type BlockChain interface { 180 LightChain 181 182 // HasBlock verifies a block's presence in the local chain. 183 HasBlock(common.Hash, uint64) bool 184 185 // HasFastBlock verifies a snap block's presence in the local chain. 186 HasFastBlock(common.Hash, uint64) bool 187 188 // GetBlockByHash retrieves a block from the local chain. 189 GetBlockByHash(common.Hash) *types.Block 190 191 // CurrentBlock retrieves the head block from the local chain. 192 CurrentBlock() *types.Block 193 194 // CurrentFastBlock retrieves the head snap block from the local chain. 195 CurrentFastBlock() *types.Block 196 197 // SnapSyncCommitHead directly commits the head block to a certain entity. 198 SnapSyncCommitHead(common.Hash) error 199 200 // InsertChain inserts a batch of blocks into the local chain. 201 InsertChain(types.Blocks) (int, error) 202 203 // InsertReceiptChain inserts a batch of receipts into the local chain. 204 InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error) 205 206 // Snapshots returns the blockchain snapshot tree to paused it during sync. 207 Snapshots() *snapshot.Tree 208 } 209 210 // New creates a new downloader to fetch hashes and blocks from remote peers. 211 func New(checkpoint uint64, stateDb ethdb.Database, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn, success func()) *Downloader { 212 if lightchain == nil { 213 lightchain = chain 214 } 215 dl := &Downloader{ 216 stateDB: stateDb, 217 mux: mux, 218 checkpoint: checkpoint, 219 queue: newQueue(blockCacheMaxItems, blockCacheInitialItems), 220 peers: newPeerSet(), 221 blockchain: chain, 222 lightchain: lightchain, 223 dropPeer: dropPeer, 224 headerProcCh: make(chan *headerTask, 1), 225 quitCh: make(chan struct{}), 226 SnapSyncer: snap.NewSyncer(stateDb), 227 stateSyncStart: make(chan *stateSync), 228 } 229 //dl.skeleton = newSkeleton(stateDb, dl.peers, dropPeer, newBeaconBackfiller(dl, success)) 230 231 go dl.stateFetcher() 232 return dl 233 } 234 235 // Progress retrieves the synchronisation boundaries, specifically the origin 236 // block where synchronisation started at (may have failed/suspended); the block 237 // or header sync is currently at; and the latest known block which the sync targets. 238 // 239 // In addition, during the state download phase of snap synchronisation the number 240 // of processed and the total number of known states are also returned. Otherwise 241 // these are zero. 242 func (d *Downloader) Progress() ethereum.SyncProgress { 243 // Lock the current stats and return the progress 244 d.syncStatsLock.RLock() 245 defer d.syncStatsLock.RUnlock() 246 247 current := uint64(0) 248 mode := d.getMode() 249 switch { 250 case d.blockchain != nil && mode == FullSync: 251 current = d.blockchain.CurrentBlock().NumberU64() 252 case d.blockchain != nil && mode == SnapSync: 253 current = d.blockchain.CurrentFastBlock().NumberU64() 254 case d.lightchain != nil: 255 current = d.lightchain.CurrentHeader().Number.Uint64() 256 default: 257 log.Error("Unknown downloader chain/mode combo", "light", d.lightchain != nil, "full", d.blockchain != nil, "mode", mode) 258 } 259 progress, pending := d.SnapSyncer.Progress() 260 261 return ethereum.SyncProgress{ 262 StartingBlock: d.syncStatsChainOrigin, 263 CurrentBlock: current, 264 HighestBlock: d.syncStatsChainHeight, 265 SyncedAccounts: progress.AccountSynced, 266 SyncedAccountBytes: uint64(progress.AccountBytes), 267 SyncedBytecodes: progress.BytecodeSynced, 268 SyncedBytecodeBytes: uint64(progress.BytecodeBytes), 269 SyncedStorage: progress.StorageSynced, 270 SyncedStorageBytes: uint64(progress.StorageBytes), 271 HealedTrienodes: progress.TrienodeHealSynced, 272 HealedTrienodeBytes: uint64(progress.TrienodeHealBytes), 273 HealedBytecodes: progress.BytecodeHealSynced, 274 HealedBytecodeBytes: uint64(progress.BytecodeHealBytes), 275 HealingTrienodes: pending.TrienodeHeal, 276 HealingBytecode: pending.BytecodeHeal, 277 } 278 } 279 280 // Synchronising returns whether the downloader is currently retrieving blocks. 281 func (d *Downloader) Synchronising() bool { 282 return atomic.LoadInt32(&d.synchronising) > 0 283 } 284 285 // RegisterPeer injects a new download peer into the set of block source to be 286 // used for fetching hashes and blocks from. 287 func (d *Downloader) RegisterPeer(id string, version uint, peer Peer) error { 288 var logger log.Logger 289 if len(id) < 16 { 290 // Tests use short IDs, don't choke on them 291 logger = log.New("peer", id) 292 } else { 293 logger = log.New("peer", id[:8]) 294 } 295 logger.Trace("Registering sync peer") 296 if err := d.peers.Register(newPeerConnection(id, version, peer, logger)); err != nil { 297 logger.Error("Failed to register sync peer", "err", err) 298 return err 299 } 300 return nil 301 } 302 303 // RegisterLightPeer injects a light client peer, wrapping it so it appears as a regular peer. 304 func (d *Downloader) RegisterLightPeer(id string, version uint, peer LightPeer) error { 305 return d.RegisterPeer(id, version, &lightPeerWrapper{peer}) 306 } 307 308 // UnregisterPeer remove a peer from the known list, preventing any action from 309 // the specified peer. An effort is also made to return any pending fetches into 310 // the queue. 311 func (d *Downloader) UnregisterPeer(id string) error { 312 // Unregister the peer from the active peer set and revoke any fetch tasks 313 var logger log.Logger 314 if len(id) < 16 { 315 // Tests use short IDs, don't choke on them 316 logger = log.New("peer", id) 317 } else { 318 logger = log.New("peer", id[:8]) 319 } 320 logger.Trace("Unregistering sync peer") 321 if err := d.peers.Unregister(id); err != nil { 322 logger.Error("Failed to unregister sync peer", "err", err) 323 return err 324 } 325 d.queue.Revoke(id) 326 327 return nil 328 } 329 330 // LegacySync tries to sync up our local block chain with a remote peer, both 331 // adding various sanity checks as well as wrapping it with various log entries. 332 func (d *Downloader) LegacySync(id string, head common.Hash, td, ttd *big.Int, mode SyncMode) error { 333 err := d.synchronise(id, head, td, ttd, mode, false, nil) 334 335 switch err { 336 case nil, errBusy, errCanceled: 337 return err 338 } 339 if errors.Is(err, errInvalidChain) || errors.Is(err, errBadPeer) || errors.Is(err, errTimeout) || 340 errors.Is(err, errStallingPeer) || errors.Is(err, errUnsyncedPeer) || errors.Is(err, errEmptyHeaderSet) || 341 errors.Is(err, errPeersUnavailable) || errors.Is(err, errTooOld) || errors.Is(err, errInvalidAncestor) { 342 log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err) 343 if d.dropPeer == nil { 344 // The dropPeer method is nil when `--copydb` is used for a local copy. 345 // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored 346 log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id) 347 } else { 348 d.dropPeer(id) 349 } 350 return err 351 } 352 if errors.Is(err, ErrMergeTransition) { 353 return err // This is an expected fault, don't keep printing it in a spin-loop 354 } 355 log.Warn("Synchronisation failed, retrying", "err", err) 356 return err 357 } 358 359 // synchronise will select the peer and use it for synchronising. If an empty string is given 360 // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the 361 // checks fail an error will be returned. This method is synchronous 362 func (d *Downloader) synchronise(id string, hash common.Hash, td, ttd *big.Int, mode SyncMode, beaconMode bool, beaconPing chan struct{}) error { 363 // The beacon header syncer is async. It will start this synchronization and 364 // will continue doing other tasks. However, if synchronization needs to be 365 // cancelled, the syncer needs to know if we reached the startup point (and 366 // inited the cancel channel) or not yet. Make sure that we'll signal even in 367 // case of a failure. 368 if beaconPing != nil { 369 defer func() { 370 select { 371 case <-beaconPing: // already notified 372 default: 373 close(beaconPing) // weird exit condition, notify that it's safe to cancel (the nothing) 374 } 375 }() 376 } 377 // Mock out the synchronisation if testing 378 if d.synchroniseMock != nil { 379 return d.synchroniseMock(id, hash) 380 } 381 // Make sure only one goroutine is ever allowed past this point at once 382 if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) { 383 return errBusy 384 } 385 defer atomic.StoreInt32(&d.synchronising, 0) 386 387 // Post a user notification of the sync (only once per session) 388 if atomic.CompareAndSwapInt32(&d.notified, 0, 1) { 389 log.Info("Block synchronisation started") 390 } 391 if mode == SnapSync { 392 // Snap sync uses the snapshot namespace to store potentially flakey data until 393 // sync completely heals and finishes. Pause snapshot maintenance in the mean- 394 // time to prevent access. 395 if snapshots := d.blockchain.Snapshots(); snapshots != nil { // Only nil in tests 396 snapshots.Disable() 397 } 398 } 399 // Reset the queue, peer set and wake channels to clean any internal leftover state 400 d.queue.Reset(blockCacheMaxItems, blockCacheInitialItems) 401 d.peers.Reset() 402 403 for _, ch := range []chan bool{d.queue.blockWakeCh, d.queue.receiptWakeCh} { 404 select { 405 case <-ch: 406 default: 407 } 408 } 409 for empty := false; !empty; { 410 select { 411 case <-d.headerProcCh: 412 default: 413 empty = true 414 } 415 } 416 // Create cancel channel for aborting mid-flight and mark the master peer 417 d.cancelLock.Lock() 418 d.cancelCh = make(chan struct{}) 419 d.cancelPeer = id 420 d.cancelLock.Unlock() 421 422 defer d.Cancel() // No matter what, we can't leave the cancel channel open 423 424 // Atomically set the requested sync mode 425 atomic.StoreUint32(&d.mode, uint32(mode)) 426 427 // Retrieve the origin peer and initiate the downloading process 428 var p *peerConnection 429 if !beaconMode { // Beacon mode doesn't need a peer to sync from 430 p = d.peers.Peer(id) 431 if p == nil { 432 return errUnknownPeer 433 } 434 } 435 if beaconPing != nil { 436 close(beaconPing) 437 } 438 return d.syncWithPeer(p, hash, td, ttd, beaconMode) 439 } 440 441 func (d *Downloader) getMode() SyncMode { 442 return SyncMode(atomic.LoadUint32(&d.mode)) 443 } 444 445 // syncWithPeer starts a block synchronization based on the hash chain from the 446 // specified peer and head hash. 447 func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td, ttd *big.Int, beaconMode bool) (err error) { 448 d.mux.Post(StartEvent{}) 449 defer func() { 450 // reset on error 451 if err != nil { 452 d.mux.Post(FailedEvent{err}) 453 } else { 454 latest := d.lightchain.CurrentHeader() 455 d.mux.Post(DoneEvent{latest}) 456 } 457 }() 458 mode := d.getMode() 459 460 if !beaconMode { 461 log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", mode) 462 } else { 463 log.Debug("Backfilling with the network", "mode", mode) 464 } 465 defer func(start time.Time) { 466 log.Debug("Synchronisation terminated", "elapsed", common.PrettyDuration(time.Since(start))) 467 }(time.Now()) 468 469 // Look up the sync boundaries: the common ancestor and the target block 470 var latest, pivot *types.Header 471 //if !beaconMode { 472 // In legacy mode, use the master peer to retrieve the headers from 473 latest, pivot, err = d.fetchHead(p) 474 if err != nil { 475 return err 476 } 477 //} else { 478 // // In beacon mode, user the skeleton chain to retrieve the headers from 479 // //latest, _, err = d.skeleton.Bounds() 480 // //if err != nil { 481 // // return err 482 // //} 483 // if latest.Number.Uint64() > uint64(fsMinFullBlocks) { 484 // number := latest.Number.Uint64() - uint64(fsMinFullBlocks) 485 // 486 // // Retrieve the pivot header from the skeleton chain segment but 487 // // fallback to local chain if it's not found in skeleton space. 488 // if pivot = d.skeleton.Header(number); pivot == nil { 489 // _, oldest, _ := d.skeleton.Bounds() // error is already checked 490 // if number < oldest.Number.Uint64() { 491 // count := int(oldest.Number.Uint64() - number) // it's capped by fsMinFullBlocks 492 // headers := d.readHeaderRange(oldest, count) 493 // if len(headers) == count { 494 // pivot = headers[len(headers)-1] 495 // log.Warn("Retrieved pivot header from local", "number", pivot.Number, "hash", pivot.Hash(), "latest", latest.Number, "oldest", oldest.Number) 496 // } 497 // } 498 // } 499 // // Print an error log and return directly in case the pivot header 500 // // is still not found. It means the skeleton chain is not linked 501 // // correctly with local chain. 502 // if pivot == nil { 503 // log.Error("Pivot header is not found", "number", number) 504 // return errNoPivotHeader 505 // } 506 // } 507 //} 508 // If no pivot block was returned, the head is below the min full block 509 // threshold (i.e. new chain). In that case we won't really snap sync 510 // anyway, but still need a valid pivot block to avoid some code hitting 511 // nil panics on access. 512 if mode == SnapSync && pivot == nil { 513 pivot = d.blockchain.CurrentBlock().Header() 514 } 515 height := latest.Number.Uint64() 516 517 var origin uint64 518 //if !beaconMode { 519 // In legacy mode, reach out to the network and find the ancestor 520 origin, err = d.findAncestor(p, latest) 521 if err != nil { 522 return err 523 } 524 //} else { 525 // // In beacon mode, use the skeleton chain for the ancestor lookup 526 // origin, err = d.findBeaconAncestor() 527 // if err != nil { 528 // return err 529 // } 530 //} 531 d.syncStatsLock.Lock() 532 if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin { 533 d.syncStatsChainOrigin = origin 534 } 535 d.syncStatsChainHeight = height 536 d.syncStatsLock.Unlock() 537 538 // Ensure our origin point is below any snap sync pivot point 539 if mode == SnapSync { 540 if height <= uint64(fsMinFullBlocks) { 541 origin = 0 542 } else { 543 pivotNumber := pivot.Number.Uint64() 544 if pivotNumber <= origin { 545 origin = pivotNumber - 1 546 } 547 // Write out the pivot into the database so a rollback beyond it will 548 // reenable snap sync 549 rawdb.WriteLastPivotNumber(d.stateDB, pivotNumber) 550 } 551 } 552 d.committed = 1 553 if mode == SnapSync && pivot.Number.Uint64() != 0 { 554 d.committed = 0 555 } 556 if mode == SnapSync { 557 // Set the ancient data limitation. 558 // If we are running snap sync, all block data older than ancientLimit will be 559 // written to the ancient store. More recent data will be written to the active 560 // database and will wait for the freezer to migrate. 561 // 562 // If there is a checkpoint available, then calculate the ancientLimit through 563 // that. Otherwise calculate the ancient limit through the advertised height 564 // of the remote peer. 565 // 566 // The reason for picking checkpoint first is that a malicious peer can give us 567 // a fake (very high) height, forcing the ancient limit to also be very high. 568 // The peer would start to feed us valid blocks until head, resulting in all of 569 // the blocks might be written into the ancient store. A following mini-reorg 570 // could cause issues. 571 if d.checkpoint != 0 && d.checkpoint > fullMaxForkAncestry+1 { 572 d.ancientLimit = d.checkpoint 573 } else if height > fullMaxForkAncestry+1 { 574 d.ancientLimit = height - fullMaxForkAncestry - 1 575 } else { 576 d.ancientLimit = 0 577 } 578 frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here. 579 580 // If a part of blockchain data has already been written into active store, 581 // disable the ancient style insertion explicitly. 582 if origin >= frozen && frozen != 0 { 583 d.ancientLimit = 0 584 log.Info("Disabling direct-ancient mode", "origin", origin, "ancient", frozen-1) 585 } else if d.ancientLimit > 0 { 586 log.Debug("Enabling direct-ancient mode", "ancient", d.ancientLimit) 587 } 588 // Rewind the ancient store and blockchain if reorg happens. 589 if origin+1 < frozen { 590 if err := d.lightchain.SetHead(origin); err != nil { 591 return err 592 } 593 } 594 } 595 // Initiate the sync using a concurrent header and content retrieval algorithm 596 d.queue.Prepare(origin+1, mode) 597 if d.syncInitHook != nil { 598 d.syncInitHook(origin, height) 599 } 600 var headerFetcher func() error 601 //if !beaconMode { 602 // In legacy mode, headers are retrieved from the network 603 headerFetcher = func() error { return d.fetchHeaders(p, origin+1, latest.Number.Uint64()) } 604 //} else { 605 // // In beacon mode, headers are served by the skeleton syncer 606 // headerFetcher = func() error { return d.fetchBeaconHeaders(origin + 1) } 607 //} 608 fetchers := []func() error{ 609 headerFetcher, // Headers are always retrieved 610 func() error { return d.fetchBodies(origin+1, beaconMode) }, // Bodies are retrieved during normal and snap sync 611 func() error { return d.fetchReceipts(origin+1, beaconMode) }, // Receipts are retrieved during snap sync 612 func() error { return d.processHeaders(origin+1, td, ttd, beaconMode) }, 613 } 614 if mode == SnapSync { 615 d.pivotLock.Lock() 616 d.pivotHeader = pivot 617 d.pivotLock.Unlock() 618 619 fetchers = append(fetchers, func() error { return d.processSnapSyncContent() }) 620 } else if mode == FullSync { 621 fetchers = append(fetchers, func() error { return d.processFullSyncContent(ttd, beaconMode) }) 622 } 623 return d.spawnSync(fetchers) 624 } 625 626 // spawnSync runs d.process and all given fetcher functions to completion in 627 // separate goroutines, returning the first error that appears. 628 func (d *Downloader) spawnSync(fetchers []func() error) error { 629 errc := make(chan error, len(fetchers)) 630 d.cancelWg.Add(len(fetchers)) 631 for _, fn := range fetchers { 632 fn := fn 633 go func() { defer d.cancelWg.Done(); errc <- fn() }() 634 } 635 // Wait for the first error, then terminate the others. 636 var err error 637 for i := 0; i < len(fetchers); i++ { 638 if i == len(fetchers)-1 { 639 // Close the queue when all fetchers have exited. 640 // This will cause the block processor to end when 641 // it has processed the queue. 642 d.queue.Close() 643 } 644 if err = <-errc; err != nil && err != errCanceled { 645 break 646 } 647 } 648 d.queue.Close() 649 d.Cancel() 650 return err 651 } 652 653 // cancel aborts all of the operations and resets the queue. However, cancel does 654 // not wait for the running download goroutines to finish. This method should be 655 // used when cancelling the downloads from inside the downloader. 656 func (d *Downloader) cancel() { 657 // Close the current cancel channel 658 d.cancelLock.Lock() 659 defer d.cancelLock.Unlock() 660 661 if d.cancelCh != nil { 662 select { 663 case <-d.cancelCh: 664 // Channel was already closed 665 default: 666 close(d.cancelCh) 667 } 668 } 669 } 670 671 // Cancel aborts all of the operations and waits for all download goroutines to 672 // finish before returning. 673 func (d *Downloader) Cancel() { 674 d.cancel() 675 d.cancelWg.Wait() 676 } 677 678 // Terminate interrupts the downloader, canceling all pending operations. 679 // The downloader cannot be reused after calling Terminate. 680 func (d *Downloader) Terminate() { 681 // Close the termination channel (make sure double close is allowed) 682 d.quitLock.Lock() 683 select { 684 case <-d.quitCh: 685 default: 686 close(d.quitCh) 687 688 // Terminate the internal beacon syncer 689 //d.skeleton.Terminate() 690 } 691 d.quitLock.Unlock() 692 693 // Cancel any pending download requests 694 d.Cancel() 695 } 696 697 // fetchHead retrieves the head header and prior pivot block (if available) from 698 // a remote peer. 699 func (d *Downloader) fetchHead(p *peerConnection) (head *types.Header, pivot *types.Header, err error) { 700 p.log.Debug("Retrieving remote chain head") 701 mode := d.getMode() 702 703 // Request the advertised remote head block and wait for the response 704 latest, _ := p.peer.Head() 705 fetch := 1 706 if mode == SnapSync { 707 fetch = 2 // head + pivot headers 708 } 709 headers, hashes, err := d.fetchHeadersByHash(p, latest, fetch, fsMinFullBlocks-1, true) 710 if err != nil { 711 return nil, nil, err 712 } 713 // Make sure the peer gave us at least one and at most the requested headers 714 if len(headers) == 0 || len(headers) > fetch { 715 return nil, nil, fmt.Errorf("%w: returned headers %d != requested %d", errBadPeer, len(headers), fetch) 716 } 717 // The first header needs to be the head, validate against the checkpoint 718 // and request. If only 1 header was returned, make sure there's no pivot 719 // or there was not one requested. 720 head = headers[0] 721 if (mode == SnapSync || mode == LightSync) && head.Number.Uint64() < d.checkpoint { 722 return nil, nil, fmt.Errorf("%w: remote head %d below checkpoint %d", errUnsyncedPeer, head.Number, d.checkpoint) 723 } 724 if len(headers) == 1 { 725 if mode == SnapSync && head.Number.Uint64() > uint64(fsMinFullBlocks) { 726 return nil, nil, fmt.Errorf("%w: no pivot included along head header", errBadPeer) 727 } 728 p.log.Debug("Remote head identified, no pivot", "number", head.Number, "hash", hashes[0]) 729 return head, nil, nil 730 } 731 // At this point we have 2 headers in total and the first is the 732 // validated head of the chain. Check the pivot number and return, 733 pivot = headers[1] 734 if pivot.Number.Uint64() != head.Number.Uint64()-uint64(fsMinFullBlocks) { 735 return nil, nil, fmt.Errorf("%w: remote pivot %d != requested %d", errInvalidChain, pivot.Number, head.Number.Uint64()-uint64(fsMinFullBlocks)) 736 } 737 return head, pivot, nil 738 } 739 740 // calculateRequestSpan calculates what headers to request from a peer when trying to determine the 741 // common ancestor. 742 // It returns parameters to be used for peer.RequestHeadersByNumber: 743 // from - starting block number 744 // count - number of headers to request 745 // skip - number of headers to skip 746 // and also returns 'max', the last block which is expected to be returned by the remote peers, 747 // given the (from,count,skip) 748 func calculateRequestSpan(remoteHeight, localHeight uint64) (int64, int, int, uint64) { 749 var ( 750 from int 751 count int 752 MaxCount = MaxHeaderFetch / 16 753 ) 754 // requestHead is the highest block that we will ask for. If requestHead is not offset, 755 // the highest block that we will get is 16 blocks back from head, which means we 756 // will fetch 14 or 15 blocks unnecessarily in the case the height difference 757 // between us and the peer is 1-2 blocks, which is most common 758 requestHead := int(remoteHeight) - 1 759 if requestHead < 0 { 760 requestHead = 0 761 } 762 // requestBottom is the lowest block we want included in the query 763 // Ideally, we want to include the one just below our own head 764 requestBottom := int(localHeight - 1) 765 if requestBottom < 0 { 766 requestBottom = 0 767 } 768 totalSpan := requestHead - requestBottom 769 span := 1 + totalSpan/MaxCount 770 if span < 2 { 771 span = 2 772 } 773 if span > 16 { 774 span = 16 775 } 776 777 count = 1 + totalSpan/span 778 if count > MaxCount { 779 count = MaxCount 780 } 781 if count < 2 { 782 count = 2 783 } 784 from = requestHead - (count-1)*span 785 if from < 0 { 786 from = 0 787 } 788 max := from + (count-1)*span 789 return int64(from), count, span - 1, uint64(max) 790 } 791 792 // findAncestor tries to locate the common ancestor link of the local chain and 793 // a remote peers blockchain. In the general case when our node was in sync and 794 // on the correct chain, checking the top N links should already get us a match. 795 // In the rare scenario when we ended up on a long reorganisation (i.e. none of 796 // the head links match), we do a binary search to find the common ancestor. 797 func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header) (uint64, error) { 798 // Figure out the valid ancestor range to prevent rewrite attacks 799 var ( 800 floor = int64(-1) 801 localHeight uint64 802 remoteHeight = remoteHeader.Number.Uint64() 803 ) 804 mode := d.getMode() 805 switch mode { 806 case FullSync: 807 localHeight = d.blockchain.CurrentBlock().NumberU64() 808 case SnapSync: 809 localHeight = d.blockchain.CurrentFastBlock().NumberU64() 810 default: 811 localHeight = d.lightchain.CurrentHeader().Number.Uint64() 812 } 813 p.log.Debug("Looking for common ancestor", "local", localHeight, "remote", remoteHeight) 814 815 // Recap floor value for binary search 816 maxForkAncestry := fullMaxForkAncestry 817 if d.getMode() == LightSync { 818 maxForkAncestry = lightMaxForkAncestry 819 } 820 if localHeight >= maxForkAncestry { 821 // We're above the max reorg threshold, find the earliest fork point 822 floor = int64(localHeight - maxForkAncestry) 823 } 824 // If we're doing a light sync, ensure the floor doesn't go below the CHT, as 825 // all headers before that point will be missing. 826 if mode == LightSync { 827 // If we don't know the current CHT position, find it 828 if d.genesis == 0 { 829 header := d.lightchain.CurrentHeader() 830 for header != nil { 831 d.genesis = header.Number.Uint64() 832 if floor >= int64(d.genesis)-1 { 833 break 834 } 835 header = d.lightchain.GetHeaderByHash(header.ParentHash) 836 } 837 } 838 // We already know the "genesis" block number, cap floor to that 839 if floor < int64(d.genesis)-1 { 840 floor = int64(d.genesis) - 1 841 } 842 } 843 844 ancestor, err := d.findAncestorSpanSearch(p, mode, remoteHeight, localHeight, floor) 845 if err == nil { 846 return ancestor, nil 847 } 848 // The returned error was not nil. 849 // If the error returned does not reflect that a common ancestor was not found, return it. 850 // If the error reflects that a common ancestor was not found, continue to binary search, 851 // where the error value will be reassigned. 852 if !errors.Is(err, errNoAncestorFound) { 853 return 0, err 854 } 855 856 ancestor, err = d.findAncestorBinarySearch(p, mode, remoteHeight, floor) 857 if err != nil { 858 return 0, err 859 } 860 return ancestor, nil 861 } 862 863 func (d *Downloader) findAncestorSpanSearch(p *peerConnection, mode SyncMode, remoteHeight, localHeight uint64, floor int64) (uint64, error) { 864 from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight) 865 866 p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip) 867 headers, hashes, err := d.fetchHeadersByNumber(p, uint64(from), count, skip, false) 868 if err != nil { 869 return 0, err 870 } 871 // Wait for the remote response to the head fetch 872 number, hash := uint64(0), common.Hash{} 873 874 // Make sure the peer actually gave something valid 875 if len(headers) == 0 { 876 p.log.Warn("Empty head header set") 877 return 0, errEmptyHeaderSet 878 } 879 // Make sure the peer's reply conforms to the request 880 for i, header := range headers { 881 expectNumber := from + int64(i)*int64(skip+1) 882 if number := header.Number.Int64(); number != expectNumber { 883 p.log.Warn("Head headers broke chain ordering", "index", i, "requested", expectNumber, "received", number) 884 return 0, fmt.Errorf("%w: %v", errInvalidChain, errors.New("head headers broke chain ordering")) 885 } 886 } 887 // Check if a common ancestor was found 888 for i := len(headers) - 1; i >= 0; i-- { 889 // Skip any headers that underflow/overflow our requested set 890 if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > max { 891 continue 892 } 893 // Otherwise check if we already know the header or not 894 h := hashes[i] 895 n := headers[i].Number.Uint64() 896 897 var known bool 898 switch mode { 899 case FullSync: 900 known = d.blockchain.HasBlock(h, n) 901 case SnapSync: 902 known = d.blockchain.HasFastBlock(h, n) 903 default: 904 known = d.lightchain.HasHeader(h, n) 905 } 906 if known { 907 number, hash = n, h 908 break 909 } 910 } 911 // If the head fetch already found an ancestor, return 912 if hash != (common.Hash{}) { 913 if int64(number) <= floor { 914 p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor) 915 return 0, errInvalidAncestor 916 } 917 p.log.Debug("Found common ancestor", "number", number, "hash", hash) 918 return number, nil 919 } 920 return 0, errNoAncestorFound 921 } 922 923 func (d *Downloader) findAncestorBinarySearch(p *peerConnection, mode SyncMode, remoteHeight uint64, floor int64) (uint64, error) { 924 hash := common.Hash{} 925 926 // Ancestor not found, we need to binary search over our chain 927 start, end := uint64(0), remoteHeight 928 if floor > 0 { 929 start = uint64(floor) 930 } 931 p.log.Trace("Binary searching for common ancestor", "start", start, "end", end) 932 933 for start+1 < end { 934 // Split our chain interval in two, and request the hash to cross check 935 check := (start + end) / 2 936 937 headers, hashes, err := d.fetchHeadersByNumber(p, check, 1, 0, false) 938 if err != nil { 939 return 0, err 940 } 941 // Make sure the peer actually gave something valid 942 if len(headers) != 1 { 943 p.log.Warn("Multiple headers for single request", "headers", len(headers)) 944 return 0, fmt.Errorf("%w: multiple headers (%d) for single request", errBadPeer, len(headers)) 945 } 946 // Modify the search interval based on the response 947 h := hashes[0] 948 n := headers[0].Number.Uint64() 949 950 var known bool 951 switch mode { 952 case FullSync: 953 known = d.blockchain.HasBlock(h, n) 954 case SnapSync: 955 known = d.blockchain.HasFastBlock(h, n) 956 default: 957 known = d.lightchain.HasHeader(h, n) 958 } 959 if !known { 960 end = check 961 continue 962 } 963 header := d.lightchain.GetHeaderByHash(h) // Independent of sync mode, header surely exists 964 if header.Number.Uint64() != check { 965 p.log.Warn("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check) 966 return 0, fmt.Errorf("%w: non-requested header (%d)", errBadPeer, header.Number) 967 } 968 start = check 969 hash = h 970 } 971 // Ensure valid ancestry and return 972 if int64(start) <= floor { 973 p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor) 974 return 0, errInvalidAncestor 975 } 976 p.log.Debug("Found common ancestor", "number", start, "hash", hash) 977 return start, nil 978 } 979 980 // fetchHeaders keeps retrieving headers concurrently from the number 981 // requested, until no more are returned, potentially throttling on the way. To 982 // facilitate concurrency but still protect against malicious nodes sending bad 983 // headers, we construct a header chain skeleton using the "origin" peer we are 984 // syncing with, and fill in the missing headers using anyone else. Headers from 985 // other peers are only accepted if they map cleanly to the skeleton. If no one 986 // can fill in the skeleton - not even the origin peer - it's assumed invalid and 987 // the origin is dropped. 988 func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, head uint64) error { 989 p.log.Debug("Directing header downloads", "origin", from) 990 defer p.log.Debug("Header download terminated") 991 992 // Start pulling the header chain skeleton until all is done 993 var ( 994 skeleton = true // Skeleton assembly phase or finishing up 995 pivoting = false // Whether the next request is pivot verification 996 ancestor = from 997 mode = d.getMode() 998 ) 999 for { 1000 // Pull the next batch of headers, it either: 1001 // - Pivot check to see if the chain moved too far 1002 // - Skeleton retrieval to permit concurrent header fetches 1003 // - Full header retrieval if we're near the chain head 1004 var ( 1005 headers []*types.Header 1006 hashes []common.Hash 1007 err error 1008 ) 1009 switch { 1010 case pivoting: 1011 d.pivotLock.RLock() 1012 pivot := d.pivotHeader.Number.Uint64() 1013 d.pivotLock.RUnlock() 1014 1015 p.log.Trace("Fetching next pivot header", "number", pivot+uint64(fsMinFullBlocks)) 1016 headers, hashes, err = d.fetchHeadersByNumber(p, pivot+uint64(fsMinFullBlocks), 2, fsMinFullBlocks-9, false) // move +64 when it's 2x64-8 deep 1017 1018 case skeleton: 1019 p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from) 1020 headers, hashes, err = d.fetchHeadersByNumber(p, from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false) 1021 1022 default: 1023 p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from) 1024 headers, hashes, err = d.fetchHeadersByNumber(p, from, MaxHeaderFetch, 0, false) 1025 } 1026 switch err { 1027 case nil: 1028 // Headers retrieved, continue with processing 1029 1030 case errCanceled: 1031 // Sync cancelled, no issue, propagate up 1032 return err 1033 1034 default: 1035 // Header retrieval either timed out, or the peer failed in some strange way 1036 // (e.g. disconnect). Consider the master peer bad and drop 1037 d.dropPeer(p.id) 1038 1039 // Finish the sync gracefully instead of dumping the gathered data though 1040 for _, ch := range []chan bool{d.queue.blockWakeCh, d.queue.receiptWakeCh} { 1041 select { 1042 case ch <- false: 1043 case <-d.cancelCh: 1044 } 1045 } 1046 select { 1047 case d.headerProcCh <- nil: 1048 case <-d.cancelCh: 1049 } 1050 return fmt.Errorf("%w: header request failed: %v", errBadPeer, err) 1051 } 1052 // If the pivot is being checked, move if it became stale and run the real retrieval 1053 var pivot uint64 1054 1055 d.pivotLock.RLock() 1056 if d.pivotHeader != nil { 1057 pivot = d.pivotHeader.Number.Uint64() 1058 } 1059 d.pivotLock.RUnlock() 1060 1061 if pivoting { 1062 if len(headers) == 2 { 1063 if have, want := headers[0].Number.Uint64(), pivot+uint64(fsMinFullBlocks); have != want { 1064 log.Warn("Peer sent invalid next pivot", "have", have, "want", want) 1065 return fmt.Errorf("%w: next pivot number %d != requested %d", errInvalidChain, have, want) 1066 } 1067 if have, want := headers[1].Number.Uint64(), pivot+2*uint64(fsMinFullBlocks)-8; have != want { 1068 log.Warn("Peer sent invalid pivot confirmer", "have", have, "want", want) 1069 return fmt.Errorf("%w: next pivot confirmer number %d != requested %d", errInvalidChain, have, want) 1070 } 1071 log.Warn("Pivot seemingly stale, moving", "old", pivot, "new", headers[0].Number) 1072 pivot = headers[0].Number.Uint64() 1073 1074 d.pivotLock.Lock() 1075 d.pivotHeader = headers[0] 1076 d.pivotLock.Unlock() 1077 1078 // Write out the pivot into the database so a rollback beyond 1079 // it will reenable snap sync and update the state root that 1080 // the state syncer will be downloading. 1081 rawdb.WriteLastPivotNumber(d.stateDB, pivot) 1082 } 1083 // Disable the pivot check and fetch the next batch of headers 1084 pivoting = false 1085 continue 1086 } 1087 // If the skeleton's finished, pull any remaining head headers directly from the origin 1088 if skeleton && len(headers) == 0 { 1089 // A malicious node might withhold advertised headers indefinitely 1090 if from+uint64(MaxHeaderFetch)-1 <= head { 1091 p.log.Warn("Peer withheld skeleton headers", "advertised", head, "withheld", from+uint64(MaxHeaderFetch)-1) 1092 return fmt.Errorf("%w: withheld skeleton headers: advertised %d, withheld #%d", errStallingPeer, head, from+uint64(MaxHeaderFetch)-1) 1093 } 1094 p.log.Debug("No skeleton, fetching headers directly") 1095 skeleton = false 1096 continue 1097 } 1098 // If no more headers are inbound, notify the content fetchers and return 1099 if len(headers) == 0 { 1100 // Don't abort header fetches while the pivot is downloading 1101 if atomic.LoadInt32(&d.committed) == 0 && pivot <= from { 1102 p.log.Debug("No headers, waiting for pivot commit") 1103 select { 1104 case <-time.After(fsHeaderContCheck): 1105 continue 1106 case <-d.cancelCh: 1107 return errCanceled 1108 } 1109 } 1110 // Pivot done (or not in snap sync) and no more headers, terminate the process 1111 p.log.Debug("No more headers available") 1112 select { 1113 case d.headerProcCh <- nil: 1114 return nil 1115 case <-d.cancelCh: 1116 return errCanceled 1117 } 1118 } 1119 // If we received a skeleton batch, resolve internals concurrently 1120 var progressed bool 1121 if skeleton { 1122 filled, hashset, proced, err := d.fillHeaderSkeleton(from, headers) 1123 if err != nil { 1124 p.log.Debug("Skeleton chain invalid", "err", err) 1125 return fmt.Errorf("%w: %v", errInvalidChain, err) 1126 } 1127 headers = filled[proced:] 1128 hashes = hashset[proced:] 1129 1130 progressed = proced > 0 1131 from += uint64(proced) 1132 } else { 1133 // A malicious node might withhold advertised headers indefinitely 1134 if n := len(headers); n < MaxHeaderFetch && headers[n-1].Number.Uint64() < head { 1135 p.log.Warn("Peer withheld headers", "advertised", head, "delivered", headers[n-1].Number.Uint64()) 1136 return fmt.Errorf("%w: withheld headers: advertised %d, delivered %d", errStallingPeer, head, headers[n-1].Number.Uint64()) 1137 } 1138 // If we're closing in on the chain head, but haven't yet reached it, delay 1139 // the last few headers so mini reorgs on the head don't cause invalid hash 1140 // chain errors. 1141 if n := len(headers); n > 0 { 1142 // Retrieve the current head we're at 1143 var head uint64 1144 if mode == LightSync { 1145 head = d.lightchain.CurrentHeader().Number.Uint64() 1146 } else { 1147 head = d.blockchain.CurrentFastBlock().NumberU64() 1148 if full := d.blockchain.CurrentBlock().NumberU64(); head < full { 1149 head = full 1150 } 1151 } 1152 // If the head is below the common ancestor, we're actually deduplicating 1153 // already existing chain segments, so use the ancestor as the fake head. 1154 // Otherwise, we might end up delaying header deliveries pointlessly. 1155 if head < ancestor { 1156 head = ancestor 1157 } 1158 // If the head is way older than this batch, delay the last few headers 1159 if head+uint64(reorgProtThreshold) < headers[n-1].Number.Uint64() { 1160 delay := reorgProtHeaderDelay 1161 if delay > n { 1162 delay = n 1163 } 1164 headers = headers[:n-delay] 1165 hashes = hashes[:n-delay] 1166 } 1167 } 1168 } 1169 // If no headers have bene delivered, or all of them have been delayed, 1170 // sleep a bit and retry. Take care with headers already consumed during 1171 // skeleton filling 1172 if len(headers) == 0 && !progressed { 1173 p.log.Trace("All headers delayed, waiting") 1174 select { 1175 case <-time.After(fsHeaderContCheck): 1176 continue 1177 case <-d.cancelCh: 1178 return errCanceled 1179 } 1180 } 1181 // Insert any remaining new headers and fetch the next batch 1182 if len(headers) > 0 { 1183 p.log.Trace("Scheduling new headers", "count", len(headers), "from", from) 1184 select { 1185 case d.headerProcCh <- &headerTask{ 1186 headers: headers, 1187 hashes: hashes, 1188 }: 1189 case <-d.cancelCh: 1190 return errCanceled 1191 } 1192 from += uint64(len(headers)) 1193 } 1194 // If we're still skeleton filling snap sync, check pivot staleness 1195 // before continuing to the next skeleton filling 1196 if skeleton && pivot > 0 { 1197 pivoting = true 1198 } 1199 } 1200 } 1201 1202 // fillHeaderSkeleton concurrently retrieves headers from all our available peers 1203 // and maps them to the provided skeleton header chain. 1204 // 1205 // Any partial results from the beginning of the skeleton is (if possible) forwarded 1206 // immediately to the header processor to keep the rest of the pipeline full even 1207 // in the case of header stalls. 1208 // 1209 // The method returns the entire filled skeleton and also the number of headers 1210 // already forwarded for processing. 1211 func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, []common.Hash, int, error) { 1212 log.Debug("Filling up skeleton", "from", from) 1213 d.queue.ScheduleSkeleton(from, skeleton) 1214 1215 err := d.concurrentFetch((*headerQueue)(d), false) 1216 if err != nil { 1217 log.Debug("Skeleton fill failed", "err", err) 1218 } 1219 filled, hashes, proced := d.queue.RetrieveHeaders() 1220 if err == nil { 1221 log.Debug("Skeleton fill succeeded", "filled", len(filled), "processed", proced) 1222 } 1223 return filled, hashes, proced, err 1224 } 1225 1226 // fetchBodies iteratively downloads the scheduled block bodies, taking any 1227 // available peers, reserving a chunk of blocks for each, waiting for delivery 1228 // and also periodically checking for timeouts. 1229 func (d *Downloader) fetchBodies(from uint64, beaconMode bool) error { 1230 log.Debug("Downloading block bodies", "origin", from) 1231 err := d.concurrentFetch((*bodyQueue)(d), beaconMode) 1232 1233 log.Debug("Block body download terminated", "err", err) 1234 return err 1235 } 1236 1237 // fetchReceipts iteratively downloads the scheduled block receipts, taking any 1238 // available peers, reserving a chunk of receipts for each, waiting for delivery 1239 // and also periodically checking for timeouts. 1240 func (d *Downloader) fetchReceipts(from uint64, beaconMode bool) error { 1241 log.Debug("Downloading receipts", "origin", from) 1242 err := d.concurrentFetch((*receiptQueue)(d), beaconMode) 1243 1244 log.Debug("Receipt download terminated", "err", err) 1245 return err 1246 } 1247 1248 // processHeaders takes batches of retrieved headers from an input channel and 1249 // keeps processing and scheduling them into the header chain and downloader's 1250 // queue until the stream ends or a failure occurs. 1251 func (d *Downloader) processHeaders(origin uint64, td, ttd *big.Int, beaconMode bool) error { 1252 // Keep a count of uncertain headers to roll back 1253 var ( 1254 rollback uint64 // Zero means no rollback (fine as you can't unroll the genesis) 1255 rollbackErr error 1256 mode = d.getMode() 1257 ) 1258 defer func() { 1259 if rollback > 0 { 1260 lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0 1261 if mode != LightSync { 1262 lastFastBlock = d.blockchain.CurrentFastBlock().Number() 1263 lastBlock = d.blockchain.CurrentBlock().Number() 1264 } 1265 if err := d.lightchain.SetHead(rollback - 1); err != nil { // -1 to target the parent of the first uncertain block 1266 // We're already unwinding the stack, only print the error to make it more visible 1267 log.Error("Failed to roll back chain segment", "head", rollback-1, "err", err) 1268 } 1269 curFastBlock, curBlock := common.Big0, common.Big0 1270 if mode != LightSync { 1271 curFastBlock = d.blockchain.CurrentFastBlock().Number() 1272 curBlock = d.blockchain.CurrentBlock().Number() 1273 } 1274 log.Warn("Rolled back chain segment", 1275 "header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number), 1276 "snap", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock), 1277 "block", fmt.Sprintf("%d->%d", lastBlock, curBlock), "reason", rollbackErr) 1278 } 1279 }() 1280 // Wait for batches of headers to process 1281 gotHeaders := false 1282 1283 for { 1284 select { 1285 case <-d.cancelCh: 1286 rollbackErr = errCanceled 1287 return errCanceled 1288 1289 case task := <-d.headerProcCh: 1290 // Terminate header processing if we synced up 1291 if task == nil || len(task.headers) == 0 { 1292 // Notify everyone that headers are fully processed 1293 for _, ch := range []chan bool{d.queue.blockWakeCh, d.queue.receiptWakeCh} { 1294 select { 1295 case ch <- false: 1296 case <-d.cancelCh: 1297 } 1298 } 1299 // If we're in legacy sync mode, we need to check total difficulty 1300 // violations from malicious peers. That is not needed in beacon 1301 // mode and we can skip to terminating sync. 1302 if !beaconMode { 1303 // If no headers were retrieved at all, the peer violated its TD promise that it had a 1304 // better chain compared to ours. The only exception is if its promised blocks were 1305 // already imported by other means (e.g. fetcher): 1306 // 1307 // R <remote peer>, L <local node>: Both at block 10 1308 // R: Mine block 11, and propagate it to L 1309 // L: Queue block 11 for import 1310 // L: Notice that R's head and TD increased compared to ours, start sync 1311 // L: Import of block 11 finishes 1312 // L: Sync begins, and finds common ancestor at 11 1313 // L: Request new headers up from 11 (R's TD was higher, it must have something) 1314 // R: Nothing to give 1315 if mode != LightSync { 1316 head := d.blockchain.CurrentBlock() 1317 if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 { 1318 return errStallingPeer 1319 } 1320 } 1321 // If snap or light syncing, ensure promised headers are indeed delivered. This is 1322 // needed to detect scenarios where an attacker feeds a bad pivot and then bails out 1323 // of delivering the post-pivot blocks that would flag the invalid content. 1324 // 1325 // This check cannot be executed "as is" for full imports, since blocks may still be 1326 // queued for processing when the header download completes. However, as long as the 1327 // peer gave us something useful, we're already happy/progressed (above check). 1328 if mode == SnapSync || mode == LightSync { 1329 head := d.lightchain.CurrentHeader() 1330 if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 { 1331 return errStallingPeer 1332 } 1333 } 1334 } 1335 // Disable any rollback and return 1336 rollback = 0 1337 return nil 1338 } 1339 // Otherwise split the chunk of headers into batches and process them 1340 headers, hashes := task.headers, task.hashes 1341 1342 gotHeaders = true 1343 for len(headers) > 0 { 1344 // Terminate if something failed in between processing chunks 1345 select { 1346 case <-d.cancelCh: 1347 rollbackErr = errCanceled 1348 return errCanceled 1349 default: 1350 } 1351 // Select the next chunk of headers to import 1352 limit := maxHeadersProcess 1353 if limit > len(headers) { 1354 limit = len(headers) 1355 } 1356 chunkHeaders := headers[:limit] 1357 chunkHashes := hashes[:limit] 1358 1359 // In case of header only syncing, validate the chunk immediately 1360 if mode == SnapSync || mode == LightSync { 1361 // If we're importing pure headers, verify based on their recentness 1362 var pivot uint64 1363 1364 d.pivotLock.RLock() 1365 if d.pivotHeader != nil { 1366 pivot = d.pivotHeader.Number.Uint64() 1367 } 1368 d.pivotLock.RUnlock() 1369 1370 frequency := fsHeaderCheckFrequency 1371 if chunkHeaders[len(chunkHeaders)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot { 1372 frequency = 1 1373 } 1374 // Although the received headers might be all valid, a legacy 1375 // PoW/PoA sync must not accept post-merge headers. Make sure 1376 // that any transition is rejected at this point. 1377 var ( 1378 rejected []*types.Header 1379 td *big.Int 1380 ) 1381 if !beaconMode && ttd != nil { 1382 td = d.blockchain.GetTd(chunkHeaders[0].ParentHash, chunkHeaders[0].Number.Uint64()-1) 1383 if td == nil { 1384 // This should never really happen, but handle gracefully for now 1385 log.Error("Failed to retrieve parent header TD", "number", chunkHeaders[0].Number.Uint64()-1, "hash", chunkHeaders[0].ParentHash) 1386 return fmt.Errorf("%w: parent TD missing", errInvalidChain) 1387 } 1388 for i, header := range chunkHeaders { 1389 td = new(big.Int).Add(td, header.Difficulty) 1390 if td.Cmp(ttd) >= 0 { 1391 // Terminal total difficulty reached, allow the last header in 1392 if new(big.Int).Sub(td, header.Difficulty).Cmp(ttd) < 0 { 1393 chunkHeaders, rejected = chunkHeaders[:i+1], chunkHeaders[i+1:] 1394 if len(rejected) > 0 { 1395 // Make a nicer user log as to the first TD truly rejected 1396 td = new(big.Int).Add(td, rejected[0].Difficulty) 1397 } 1398 } else { 1399 chunkHeaders, rejected = chunkHeaders[:i], chunkHeaders[i:] 1400 } 1401 break 1402 } 1403 } 1404 } 1405 if len(chunkHeaders) > 0 { 1406 if n, err := d.lightchain.InsertHeaderChain(chunkHeaders, frequency); err != nil { 1407 rollbackErr = err 1408 1409 // If some headers were inserted, track them as uncertain 1410 if (mode == SnapSync || frequency > 1) && n > 0 && rollback == 0 { 1411 rollback = chunkHeaders[0].Number.Uint64() 1412 } 1413 log.Warn("Invalid header encountered", "number", chunkHeaders[n].Number, "hash", chunkHashes[n], "parent", chunkHeaders[n].ParentHash, "err", err) 1414 return fmt.Errorf("%w: %v", errInvalidChain, err) 1415 } 1416 // All verifications passed, track all headers within the allowed limits 1417 if mode == SnapSync { 1418 head := chunkHeaders[len(chunkHeaders)-1].Number.Uint64() 1419 if head-rollback > uint64(fsHeaderSafetyNet) { 1420 rollback = head - uint64(fsHeaderSafetyNet) 1421 } else { 1422 rollback = 1 1423 } 1424 } 1425 } 1426 if len(rejected) != 0 { 1427 // Merge threshold reached, stop importing, but don't roll back 1428 rollback = 0 1429 1430 log.Info("Legacy sync reached merge threshold", "number", rejected[0].Number, "hash", rejected[0].Hash(), "td", td, "ttd", ttd) 1431 return ErrMergeTransition 1432 } 1433 } 1434 // Unless we're doing light chains, schedule the headers for associated content retrieval 1435 if mode == FullSync || mode == SnapSync { 1436 // If we've reached the allowed number of pending headers, stall a bit 1437 for d.queue.PendingBodies() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders { 1438 select { 1439 case <-d.cancelCh: 1440 rollbackErr = errCanceled 1441 return errCanceled 1442 case <-time.After(time.Second): 1443 } 1444 } 1445 // Otherwise insert the headers for content retrieval 1446 inserts := d.queue.Schedule(chunkHeaders, chunkHashes, origin) 1447 if len(inserts) != len(chunkHeaders) { 1448 rollbackErr = fmt.Errorf("stale headers: len inserts %v len(chunk) %v", len(inserts), len(chunkHeaders)) 1449 return fmt.Errorf("%w: stale headers", errBadPeer) 1450 } 1451 } 1452 headers = headers[limit:] 1453 hashes = hashes[limit:] 1454 origin += uint64(limit) 1455 } 1456 // Update the highest block number we know if a higher one is found. 1457 d.syncStatsLock.Lock() 1458 if d.syncStatsChainHeight < origin { 1459 d.syncStatsChainHeight = origin - 1 1460 } 1461 d.syncStatsLock.Unlock() 1462 1463 // Signal the content downloaders of the availability of new tasks 1464 for _, ch := range []chan bool{d.queue.blockWakeCh, d.queue.receiptWakeCh} { 1465 select { 1466 case ch <- true: 1467 default: 1468 } 1469 } 1470 } 1471 } 1472 } 1473 1474 // processFullSyncContent takes fetch results from the queue and imports them into the chain. 1475 func (d *Downloader) processFullSyncContent(ttd *big.Int, beaconMode bool) error { 1476 for { 1477 results := d.queue.Results(true) 1478 if len(results) == 0 { 1479 return nil 1480 } 1481 if d.chainInsertHook != nil { 1482 d.chainInsertHook(results) 1483 } 1484 // Although the received blocks might be all valid, a legacy PoW/PoA sync 1485 // must not accept post-merge blocks. Make sure that pre-merge blocks are 1486 // imported, but post-merge ones are rejected. 1487 var ( 1488 rejected []*fetchResult 1489 td *big.Int 1490 ) 1491 if !beaconMode && ttd != nil { 1492 td = d.blockchain.GetTd(results[0].Header.ParentHash, results[0].Header.Number.Uint64()-1) 1493 if td == nil { 1494 // This should never really happen, but handle gracefully for now 1495 log.Error("Failed to retrieve parent block TD", "number", results[0].Header.Number.Uint64()-1, "hash", results[0].Header.ParentHash) 1496 return fmt.Errorf("%w: parent TD missing", errInvalidChain) 1497 } 1498 for i, result := range results { 1499 td = new(big.Int).Add(td, result.Header.Difficulty) 1500 if td.Cmp(ttd) >= 0 { 1501 // Terminal total difficulty reached, allow the last block in 1502 if new(big.Int).Sub(td, result.Header.Difficulty).Cmp(ttd) < 0 { 1503 results, rejected = results[:i+1], results[i+1:] 1504 if len(rejected) > 0 { 1505 // Make a nicer user log as to the first TD truly rejected 1506 td = new(big.Int).Add(td, rejected[0].Header.Difficulty) 1507 } 1508 } else { 1509 results, rejected = results[:i], results[i:] 1510 } 1511 break 1512 } 1513 } 1514 } 1515 if err := d.importBlockResults(results); err != nil { 1516 return err 1517 } 1518 if len(rejected) != 0 { 1519 log.Info("Legacy sync reached merge threshold", "number", rejected[0].Header.Number, "hash", rejected[0].Header.Hash(), "td", td, "ttd", ttd) 1520 return ErrMergeTransition 1521 } 1522 } 1523 } 1524 1525 func (d *Downloader) importBlockResults(results []*fetchResult) error { 1526 // Check for any early termination requests 1527 if len(results) == 0 { 1528 return nil 1529 } 1530 select { 1531 case <-d.quitCh: 1532 return errCancelContentProcessing 1533 default: 1534 } 1535 // Retrieve a batch of results to import 1536 first, last := results[0].Header, results[len(results)-1].Header 1537 log.Debug("Inserting downloaded chain", "items", len(results), 1538 "firstnum", first.Number, "firsthash", first.Hash(), 1539 "lastnum", last.Number, "lasthash", last.Hash(), 1540 ) 1541 blocks := make([]*types.Block, len(results)) 1542 for i, result := range results { 1543 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1544 } 1545 // Downloaded blocks are always regarded as trusted after the 1546 // transition. Because the downloaded chain is guided by the 1547 // consensus-layer. 1548 if index, err := d.blockchain.InsertChain(blocks); err != nil { 1549 if index < len(results) { 1550 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1551 1552 // In post-merge, notify the engine API of encountered bad chains 1553 if d.badBlock != nil { 1554 //head, _, err := d.skeleton.Bounds() 1555 if err != nil { 1556 log.Error("Failed to retrieve beacon bounds for bad block reporting", "err", err) 1557 } 1558 //else { 1559 // d.badBlock(blocks[index].Header(), head) 1560 //} 1561 } 1562 } else { 1563 // The InsertChain method in blockchain.go will sometimes return an out-of-bounds index, 1564 // when it needs to preprocess blocks to import a sidechain. 1565 // The importer will put together a new list of blocks to import, which is a superset 1566 // of the blocks delivered from the downloader, and the indexing will be off. 1567 log.Debug("Downloaded item processing failed on sidechain import", "index", index, "err", err) 1568 } 1569 return fmt.Errorf("%w: %v", errInvalidChain, err) 1570 } 1571 return nil 1572 } 1573 1574 // processSnapSyncContent takes fetch results from the queue and writes them to the 1575 // database. It also controls the synchronisation of state nodes of the pivot block. 1576 func (d *Downloader) processSnapSyncContent() error { 1577 // Start syncing state of the reported head block. This should get us most of 1578 // the state of the pivot block. 1579 d.pivotLock.RLock() 1580 sync := d.syncState(d.pivotHeader.Root) 1581 d.pivotLock.RUnlock() 1582 1583 defer func() { 1584 // The `sync` object is replaced every time the pivot moves. We need to 1585 // defer close the very last active one, hence the lazy evaluation vs. 1586 // calling defer sync.Cancel() !!! 1587 sync.Cancel() 1588 }() 1589 1590 closeOnErr := func(s *stateSync) { 1591 if err := s.Wait(); err != nil && err != errCancelStateFetch && err != errCanceled && err != snap.ErrCancelled { 1592 d.queue.Close() // wake up Results 1593 } 1594 } 1595 go closeOnErr(sync) 1596 1597 // To cater for moving pivot points, track the pivot block and subsequently 1598 // accumulated download results separately. 1599 var ( 1600 oldPivot *fetchResult // Locked in pivot block, might change eventually 1601 oldTail []*fetchResult // Downloaded content after the pivot 1602 ) 1603 for { 1604 // Wait for the next batch of downloaded data to be available, and if the pivot 1605 // block became stale, move the goalpost 1606 results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness 1607 if len(results) == 0 { 1608 // If pivot sync is done, stop 1609 if oldPivot == nil { 1610 return sync.Cancel() 1611 } 1612 // If sync failed, stop 1613 select { 1614 case <-d.cancelCh: 1615 sync.Cancel() 1616 return errCanceled 1617 default: 1618 } 1619 } 1620 if d.chainInsertHook != nil { 1621 d.chainInsertHook(results) 1622 } 1623 // If we haven't downloaded the pivot block yet, check pivot staleness 1624 // notifications from the header downloader 1625 d.pivotLock.RLock() 1626 pivot := d.pivotHeader 1627 d.pivotLock.RUnlock() 1628 1629 if oldPivot == nil { 1630 if pivot.Root != sync.root { 1631 sync.Cancel() 1632 sync = d.syncState(pivot.Root) 1633 1634 go closeOnErr(sync) 1635 } 1636 } else { 1637 results = append(append([]*fetchResult{oldPivot}, oldTail...), results...) 1638 } 1639 // Split around the pivot block and process the two sides via snap/full sync 1640 if atomic.LoadInt32(&d.committed) == 0 { 1641 latest := results[len(results)-1].Header 1642 // If the height is above the pivot block by 2 sets, it means the pivot 1643 // become stale in the network and it was garbage collected, move to a 1644 // new pivot. 1645 // 1646 // Note, we have `reorgProtHeaderDelay` number of blocks withheld, Those 1647 // need to be taken into account, otherwise we're detecting the pivot move 1648 // late and will drop peers due to unavailable state!!! 1649 if height := latest.Number.Uint64(); height >= pivot.Number.Uint64()+2*uint64(fsMinFullBlocks)-uint64(reorgProtHeaderDelay) { 1650 log.Warn("Pivot became stale, moving", "old", pivot.Number.Uint64(), "new", height-uint64(fsMinFullBlocks)+uint64(reorgProtHeaderDelay)) 1651 pivot = results[len(results)-1-fsMinFullBlocks+reorgProtHeaderDelay].Header // must exist as lower old pivot is uncommitted 1652 1653 d.pivotLock.Lock() 1654 d.pivotHeader = pivot 1655 d.pivotLock.Unlock() 1656 1657 // Write out the pivot into the database so a rollback beyond it will 1658 // reenable snap sync 1659 rawdb.WriteLastPivotNumber(d.stateDB, pivot.Number.Uint64()) 1660 } 1661 } 1662 P, beforeP, afterP := splitAroundPivot(pivot.Number.Uint64(), results) 1663 if err := d.commitSnapSyncData(beforeP, sync); err != nil { 1664 return err 1665 } 1666 if P != nil { 1667 // If new pivot block found, cancel old state retrieval and restart 1668 if oldPivot != P { 1669 sync.Cancel() 1670 sync = d.syncState(P.Header.Root) 1671 1672 go closeOnErr(sync) 1673 oldPivot = P 1674 } 1675 // Wait for completion, occasionally checking for pivot staleness 1676 select { 1677 case <-sync.done: 1678 if sync.err != nil { 1679 return sync.err 1680 } 1681 if err := d.commitPivotBlock(P); err != nil { 1682 return err 1683 } 1684 oldPivot = nil 1685 1686 case <-time.After(time.Second): 1687 oldTail = afterP 1688 continue 1689 } 1690 } 1691 // Fast sync done, pivot commit done, full import 1692 if err := d.importBlockResults(afterP); err != nil { 1693 return err 1694 } 1695 } 1696 } 1697 1698 func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) { 1699 if len(results) == 0 { 1700 return nil, nil, nil 1701 } 1702 if lastNum := results[len(results)-1].Header.Number.Uint64(); lastNum < pivot { 1703 // the pivot is somewhere in the future 1704 return nil, results, nil 1705 } 1706 // This can also be optimized, but only happens very seldom 1707 for _, result := range results { 1708 num := result.Header.Number.Uint64() 1709 switch { 1710 case num < pivot: 1711 before = append(before, result) 1712 case num == pivot: 1713 p = result 1714 default: 1715 after = append(after, result) 1716 } 1717 } 1718 return p, before, after 1719 } 1720 1721 func (d *Downloader) commitSnapSyncData(results []*fetchResult, stateSync *stateSync) error { 1722 // Check for any early termination requests 1723 if len(results) == 0 { 1724 return nil 1725 } 1726 select { 1727 case <-d.quitCh: 1728 return errCancelContentProcessing 1729 case <-stateSync.done: 1730 if err := stateSync.Wait(); err != nil { 1731 return err 1732 } 1733 default: 1734 } 1735 // Retrieve the a batch of results to import 1736 first, last := results[0].Header, results[len(results)-1].Header 1737 log.Debug("Inserting snap-sync blocks", "items", len(results), 1738 "firstnum", first.Number, "firsthash", first.Hash(), 1739 "lastnumn", last.Number, "lasthash", last.Hash(), 1740 ) 1741 blocks := make([]*types.Block, len(results)) 1742 receipts := make([]types.Receipts, len(results)) 1743 for i, result := range results { 1744 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1745 receipts[i] = result.Receipts 1746 } 1747 if index, err := d.blockchain.InsertReceiptChain(blocks, receipts, d.ancientLimit); err != nil { 1748 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1749 return fmt.Errorf("%w: %v", errInvalidChain, err) 1750 } 1751 return nil 1752 } 1753 1754 func (d *Downloader) commitPivotBlock(result *fetchResult) error { 1755 block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1756 log.Debug("Committing snap sync pivot as new head", "number", block.Number(), "hash", block.Hash()) 1757 1758 // Commit the pivot block as the new head, will require full sync from here on 1759 if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}, d.ancientLimit); err != nil { 1760 return err 1761 } 1762 if err := d.blockchain.SnapSyncCommitHead(block.Hash()); err != nil { 1763 return err 1764 } 1765 atomic.StoreInt32(&d.committed, 1) 1766 return nil 1767 } 1768 1769 // DeliverSnapPacket is invoked from a peer's message handler when it transmits a 1770 // data packet for the local node to consume. 1771 func (d *Downloader) DeliverSnapPacket(peer *snap.Peer, packet snap.Packet) error { 1772 switch packet := packet.(type) { 1773 case *snap.AccountRangePacket: 1774 hashes, accounts, err := packet.Unpack() 1775 if err != nil { 1776 return err 1777 } 1778 return d.SnapSyncer.OnAccounts(peer, packet.ID, hashes, accounts, packet.Proof) 1779 1780 case *snap.StorageRangesPacket: 1781 hashset, slotset := packet.Unpack() 1782 return d.SnapSyncer.OnStorage(peer, packet.ID, hashset, slotset, packet.Proof) 1783 1784 case *snap.ByteCodesPacket: 1785 return d.SnapSyncer.OnByteCodes(peer, packet.ID, packet.Codes) 1786 1787 case *snap.TrieNodesPacket: 1788 return d.SnapSyncer.OnTrieNodes(peer, packet.ID, packet.Nodes) 1789 1790 default: 1791 return fmt.Errorf("unexpected snap packet type: %T", packet) 1792 } 1793 } 1794 1795 // readHeaderRange returns a list of headers, using the given last header as the base, 1796 // and going backwards towards genesis. This method assumes that the caller already has 1797 // placed a reasonable cap on count. 1798 func (d *Downloader) readHeaderRange(last *types.Header, count int) []*types.Header { 1799 var ( 1800 current = last 1801 headers []*types.Header 1802 ) 1803 for { 1804 parent := d.lightchain.GetHeaderByHash(current.ParentHash) 1805 if parent == nil { 1806 break // The chain is not continuous, or the chain is exhausted 1807 } 1808 headers = append(headers, parent) 1809 if len(headers) >= count { 1810 break 1811 } 1812 current = parent 1813 } 1814 return headers 1815 }