github.com/fff-chain/go-fff@v0.0.0-20220726032732-1c84420b8a99/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/fff-chain/go-fff" 29 "github.com/fff-chain/go-fff/common" 30 "github.com/fff-chain/go-fff/core/rawdb" 31 "github.com/fff-chain/go-fff/core/state/snapshot" 32 "github.com/fff-chain/go-fff/core/types" 33 "github.com/fff-chain/go-fff/eth/protocols/eth" 34 "github.com/fff-chain/go-fff/eth/protocols/snap" 35 "github.com/fff-chain/go-fff/ethdb" 36 "github.com/fff-chain/go-fff/event" 37 "github.com/fff-chain/go-fff/log" 38 "github.com/fff-chain/go-fff/metrics" 39 "github.com/fff-chain/go-fff/params" 40 "github.com/fff-chain/go-fff/trie" 41 ) 42 43 var ( 44 MaxBlockFetch = 128 // Amount of blocks to be fetched per retrieval request 45 MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request 46 MaxSkeletonSize = 128 // Number of header fetches to need for a skeleton assembly 47 MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request 48 MaxStateFetch = 384 // Amount of node state values to allow fetching per request 49 50 rttMinEstimate = 2 * time.Second // Minimum round-trip time to target for download requests 51 rttMaxEstimate = 20 * time.Second // Maximum round-trip time to target for download requests 52 rttMinConfidence = 0.1 // Worse confidence factor in our estimated RTT value 53 ttlScaling = 3 // Constant scaling factor for RTT -> TTL conversion 54 ttlLimit = time.Minute // Maximum TTL allowance to prevent reaching crazy timeouts 55 56 diffFetchTick = 10 * time.Millisecond 57 diffFetchLimit = 5 58 59 qosTuningPeers = 5 // Number of peers to tune based on (best peers) 60 qosConfidenceCap = 10 // Number of peers above which not to modify RTT confidence 61 qosTuningImpact = 0.25 // Impact that a new tuning target has on the previous value 62 63 maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection) 64 maxHeadersProcess = 2048 // Number of header download results to import at once into the chain 65 maxResultsProcess = 2048 // Number of content download results to import at once into the chain 66 fullMaxForkAncestry uint64 = params.FullImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it) 67 lightMaxForkAncestry uint64 = params.LightImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it) 68 69 reorgProtThreshold = 48 // Threshold number of recent blocks to disable mini reorg protection 70 reorgProtHeaderDelay = 2 // Number of headers to delay delivering to cover mini reorgs 71 72 fsHeaderCheckFrequency = 100 // Verification frequency of the downloaded headers during fast sync 73 fsHeaderSafetyNet = 2048 // Number of headers to discard in case a chain violation is detected 74 fsHeaderForceVerify = 24 // Number of headers to verify before and after the pivot to accept it 75 fsHeaderContCheck = 3 * time.Second // Time interval to check for header continuations during state download 76 fsMinFullBlocks = 64 // Number of blocks to retrieve fully even in fast sync 77 ) 78 79 var ( 80 errBusy = errors.New("busy") 81 errUnknownPeer = errors.New("peer is unknown or unhealthy") 82 errBadPeer = errors.New("action from bad peer ignored") 83 errStallingPeer = errors.New("peer is stalling") 84 errUnsyncedPeer = errors.New("unsynced peer") 85 errNoPeers = errors.New("no peers to keep download active") 86 errTimeout = errors.New("timeout") 87 errEmptyHeaderSet = errors.New("empty header set by peer") 88 errPeersUnavailable = errors.New("no peers available or all tried for download") 89 errInvalidAncestor = errors.New("retrieved ancestor is invalid") 90 errInvalidChain = errors.New("retrieved hash chain is invalid") 91 errInvalidBody = errors.New("retrieved block body is invalid") 92 errInvalidReceipt = errors.New("retrieved receipt is invalid") 93 errCancelStateFetch = errors.New("state data download canceled (requested)") 94 errCancelContentProcessing = errors.New("content processing canceled (requested)") 95 errCanceled = errors.New("syncing canceled (requested)") 96 errNoSyncActive = errors.New("no sync active") 97 errTooOld = errors.New("peer's protocol version too old") 98 errNoAncestorFound = errors.New("no common ancestor found") 99 ) 100 101 type Downloader struct { 102 // WARNING: The `rttEstimate` and `rttConfidence` fields are accessed atomically. 103 // On 32 bit platforms, only 64-bit aligned fields can be atomic. The struct is 104 // guaranteed to be so aligned, so take advantage of that. For more information, 105 // see https://golang.org/pkg/sync/atomic/#pkg-note-BUG. 106 rttEstimate uint64 // Round trip time to target for download requests 107 rttConfidence uint64 // Confidence in the estimated RTT (unit: millionths to allow atomic ops) 108 109 mode uint32 // Synchronisation mode defining the strategy used (per sync cycle), use d.getMode() to get the SyncMode 110 mux *event.TypeMux // Event multiplexer to announce sync operation events 111 112 checkpoint uint64 // Checkpoint block number to enforce head against (e.g. fast sync) 113 genesis uint64 // Genesis block number to limit sync to (e.g. light client CHT) 114 queue *queue // Scheduler for selecting the hashes to download 115 peers *peerSet // Set of active peers from which download can proceed 116 117 stateDB ethdb.Database // Database to state sync into (and deduplicate via) 118 stateBloom *trie.SyncBloom // Bloom filter for fast trie node and contract code existence checks 119 120 // Statistics 121 syncStatsChainOrigin uint64 // Origin block number where syncing started at 122 syncStatsChainHeight uint64 // Highest block number known when syncing started 123 syncStatsState stateSyncStats 124 syncStatsLock sync.RWMutex // Lock protecting the sync stats fields 125 126 lightchain LightChain 127 blockchain BlockChain 128 129 // Callbacks 130 dropPeer peerDropFn // Drops a peer for misbehaving 131 132 // Status 133 synchroniseMock func(id string, hash common.Hash) error // Replacement for synchronise during testing 134 synchronising int32 135 notified int32 136 committed int32 137 ancientLimit uint64 // The maximum block number which can be regarded as ancient data. 138 139 // Channels 140 headerCh chan dataPack // Channel receiving inbound block headers 141 bodyCh chan dataPack // Channel receiving inbound block bodies 142 receiptCh chan dataPack // Channel receiving inbound receipts 143 bodyWakeCh chan bool // Channel to signal the block body fetcher of new tasks 144 receiptWakeCh chan bool // Channel to signal the receipt fetcher of new tasks 145 headerProcCh chan []*types.Header // Channel to feed the header processor new tasks 146 147 // State sync 148 pivotHeader *types.Header // Pivot block header to dynamically push the syncing state root 149 pivotLock sync.RWMutex // Lock protecting pivot header reads from updates 150 151 snapSync bool // Whether to run state sync over the snap protocol 152 SnapSyncer *snap.Syncer // TODO(karalabe): make private! hack for now 153 stateSyncStart chan *stateSync 154 trackStateReq chan *stateReq 155 stateCh chan dataPack // Channel receiving inbound node state data 156 157 // Cancellation and termination 158 cancelPeer string // Identifier of the peer currently being used as the master (cancel on drop) 159 cancelCh chan struct{} // Channel to cancel mid-flight syncs 160 cancelLock sync.RWMutex // Lock to protect the cancel channel and peer in delivers 161 cancelWg sync.WaitGroup // Make sure all fetcher goroutines have exited. 162 163 quitCh chan struct{} // Quit channel to signal termination 164 quitLock sync.Mutex // Lock to prevent double closes 165 166 // Testing hooks 167 syncInitHook func(uint64, uint64) // Method to call upon initiating a new sync run 168 bodyFetchHook func([]*types.Header) // Method to call upon starting a block body fetch 169 receiptFetchHook func([]*types.Header) // Method to call upon starting a receipt fetch 170 chainInsertHook func([]*fetchResult, chan struct{}) // Method to call upon inserting a chain of blocks (possibly in multiple invocations) 171 } 172 173 // LightChain encapsulates functions required to synchronise a light chain. 174 type LightChain interface { 175 // HasHeader verifies a header's presence in the local chain. 176 HasHeader(common.Hash, uint64) bool 177 178 // GetHeaderByHash retrieves a header from the local chain. 179 GetHeaderByHash(common.Hash) *types.Header 180 181 // CurrentHeader retrieves the head header from the local chain. 182 CurrentHeader() *types.Header 183 184 // GetTd returns the total difficulty of a local block. 185 GetTd(common.Hash, uint64) *big.Int 186 187 // InsertHeaderChain inserts a batch of headers into the local chain. 188 InsertHeaderChain([]*types.Header, int) (int, error) 189 190 // SetHead rewinds the local chain to a new head. 191 SetHead(uint64) error 192 } 193 194 // BlockChain encapsulates functions required to sync a (full or fast) blockchain. 195 type BlockChain interface { 196 LightChain 197 198 // HasBlock verifies a block's presence in the local chain. 199 HasBlock(common.Hash, uint64) bool 200 201 // HasFastBlock verifies a fast block's presence in the local chain. 202 HasFastBlock(common.Hash, uint64) bool 203 204 // GetBlockByHash retrieves a block from the local chain. 205 GetBlockByHash(common.Hash) *types.Block 206 207 // CurrentBlock retrieves the head block from the local chain. 208 CurrentBlock() *types.Block 209 210 // CurrentFastBlock retrieves the head fast block from the local chain. 211 CurrentFastBlock() *types.Block 212 213 // FastSyncCommitHead directly commits the head block to a certain entity. 214 FastSyncCommitHead(common.Hash) error 215 216 // InsertChain inserts a batch of blocks into the local chain. 217 InsertChain(types.Blocks) (int, error) 218 219 // InsertReceiptChain inserts a batch of receipts into the local chain. 220 InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error) 221 222 // Snapshots returns the blockchain snapshot tree to paused it during sync. 223 Snapshots() *snapshot.Tree 224 } 225 226 type DownloadOption func(downloader *Downloader) *Downloader 227 228 type IDiffPeer interface { 229 RequestDiffLayers([]common.Hash) error 230 } 231 232 type IPeerSet interface { 233 GetDiffPeer(string) IDiffPeer 234 } 235 236 func EnableDiffFetchOp(peers IPeerSet) DownloadOption { 237 return func(dl *Downloader) *Downloader { 238 var hook = func(results []*fetchResult, stop chan struct{}) { 239 if dl.getMode() == FullSync { 240 go func() { 241 ticker := time.NewTicker(diffFetchTick) 242 defer ticker.Stop() 243 for _, r := range results { 244 Wait: 245 for { 246 select { 247 case <-stop: 248 return 249 case <-ticker.C: 250 if dl.blockchain.CurrentHeader().Number.Int64()+int64(diffFetchLimit) > r.Header.Number.Int64() { 251 break Wait 252 } 253 } 254 } 255 if ep := peers.GetDiffPeer(r.pid); ep != nil { 256 // It turns out a diff layer is 5x larger than block, we just request one diffLayer each time 257 err := ep.RequestDiffLayers([]common.Hash{r.Header.Hash()}) 258 if err != nil { 259 return 260 } 261 } 262 } 263 }() 264 } 265 } 266 dl.chainInsertHook = hook 267 return dl 268 } 269 } 270 271 // New creates a new downloader to fetch hashes and blocks from remote peers. 272 func New(checkpoint uint64, stateDb ethdb.Database, stateBloom *trie.SyncBloom, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn, options ...DownloadOption) *Downloader { 273 if lightchain == nil { 274 lightchain = chain 275 } 276 dl := &Downloader{ 277 stateDB: stateDb, 278 stateBloom: stateBloom, 279 mux: mux, 280 checkpoint: checkpoint, 281 queue: newQueue(blockCacheMaxItems, blockCacheInitialItems), 282 peers: newPeerSet(), 283 rttEstimate: uint64(rttMaxEstimate), 284 rttConfidence: uint64(1000000), 285 blockchain: chain, 286 lightchain: lightchain, 287 dropPeer: dropPeer, 288 headerCh: make(chan dataPack, 1), 289 bodyCh: make(chan dataPack, 1), 290 receiptCh: make(chan dataPack, 1), 291 bodyWakeCh: make(chan bool, 1), 292 receiptWakeCh: make(chan bool, 1), 293 headerProcCh: make(chan []*types.Header, 1), 294 quitCh: make(chan struct{}), 295 stateCh: make(chan dataPack), 296 SnapSyncer: snap.NewSyncer(stateDb), 297 stateSyncStart: make(chan *stateSync), 298 syncStatsState: stateSyncStats{ 299 processed: rawdb.ReadFastTrieProgress(stateDb), 300 }, 301 trackStateReq: make(chan *stateReq), 302 } 303 for _, option := range options { 304 if dl != nil { 305 dl = option(dl) 306 } 307 } 308 go dl.qosTuner() 309 go dl.stateFetcher() 310 return dl 311 } 312 313 // Progress retrieves the synchronisation boundaries, specifically the origin 314 // block where synchronisation started at (may have failed/suspended); the block 315 // or header sync is currently at; and the latest known block which the sync targets. 316 // 317 // In addition, during the state download phase of fast synchronisation the number 318 // of processed and the total number of known states are also returned. Otherwise 319 // these are zero. 320 func (d *Downloader) Progress() ethereum.SyncProgress { 321 // Lock the current stats and return the progress 322 d.syncStatsLock.RLock() 323 defer d.syncStatsLock.RUnlock() 324 325 current := uint64(0) 326 mode := d.getMode() 327 switch { 328 case d.blockchain != nil && mode == FullSync: 329 current = d.blockchain.CurrentBlock().NumberU64() 330 case d.blockchain != nil && mode == FastSync: 331 current = d.blockchain.CurrentFastBlock().NumberU64() 332 case d.lightchain != nil: 333 current = d.lightchain.CurrentHeader().Number.Uint64() 334 default: 335 log.Error("Unknown downloader chain/mode combo", "light", d.lightchain != nil, "full", d.blockchain != nil, "mode", mode) 336 } 337 return ethereum.SyncProgress{ 338 StartingBlock: d.syncStatsChainOrigin, 339 CurrentBlock: current, 340 HighestBlock: d.syncStatsChainHeight, 341 PulledStates: d.syncStatsState.processed, 342 KnownStates: d.syncStatsState.processed + d.syncStatsState.pending, 343 } 344 } 345 346 // Synchronising returns whether the downloader is currently retrieving blocks. 347 func (d *Downloader) Synchronising() bool { 348 return atomic.LoadInt32(&d.synchronising) > 0 349 } 350 351 // RegisterPeer injects a new download peer into the set of block source to be 352 // used for fetching hashes and blocks from. 353 func (d *Downloader) RegisterPeer(id string, version uint, peer Peer) error { 354 var logger log.Logger 355 if len(id) < 16 { 356 // Tests use short IDs, don't choke on them 357 logger = log.New("peer", id) 358 } else { 359 logger = log.New("peer", id[:8]) 360 } 361 logger.Trace("Registering sync peer") 362 if err := d.peers.Register(newPeerConnection(id, version, peer, logger)); err != nil { 363 logger.Error("Failed to register sync peer", "err", err) 364 return err 365 } 366 d.qosReduceConfidence() 367 368 return nil 369 } 370 371 // RegisterLightPeer injects a light client peer, wrapping it so it appears as a regular peer. 372 func (d *Downloader) RegisterLightPeer(id string, version uint, peer LightPeer) error { 373 return d.RegisterPeer(id, version, &lightPeerWrapper{peer}) 374 } 375 376 // UnregisterPeer remove a peer from the known list, preventing any action from 377 // the specified peer. An effort is also made to return any pending fetches into 378 // the queue. 379 func (d *Downloader) UnregisterPeer(id string) error { 380 // Unregister the peer from the active peer set and revoke any fetch tasks 381 var logger log.Logger 382 if len(id) < 16 { 383 // Tests use short IDs, don't choke on them 384 logger = log.New("peer", id) 385 } else { 386 logger = log.New("peer", id[:8]) 387 } 388 logger.Trace("Unregistering sync peer") 389 if err := d.peers.Unregister(id); err != nil { 390 logger.Error("Failed to unregister sync peer", "err", err) 391 return err 392 } 393 d.queue.Revoke(id) 394 395 return nil 396 } 397 398 // Synchronise tries to sync up our local block chain with a remote peer, both 399 // adding various sanity checks as well as wrapping it with various log entries. 400 func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error { 401 err := d.synchronise(id, head, td, mode) 402 403 switch err { 404 case nil, errBusy, errCanceled: 405 return err 406 } 407 if errors.Is(err, errInvalidChain) || errors.Is(err, errBadPeer) || errors.Is(err, errTimeout) || 408 errors.Is(err, errStallingPeer) || errors.Is(err, errUnsyncedPeer) || errors.Is(err, errEmptyHeaderSet) || 409 errors.Is(err, errPeersUnavailable) || errors.Is(err, errTooOld) || errors.Is(err, errInvalidAncestor) { 410 log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err) 411 if d.dropPeer == nil { 412 // The dropPeer method is nil when `--copydb` is used for a local copy. 413 // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored 414 log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id) 415 } else { 416 d.dropPeer(id) 417 } 418 return err 419 } 420 log.Warn("Synchronisation failed, retrying", "err", err) 421 return err 422 } 423 424 // synchronise will select the peer and use it for synchronising. If an empty string is given 425 // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the 426 // checks fail an error will be returned. This method is synchronous 427 func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error { 428 // Mock out the synchronisation if testing 429 if d.synchroniseMock != nil { 430 return d.synchroniseMock(id, hash) 431 } 432 // Make sure only one goroutine is ever allowed past this point at once 433 if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) { 434 return errBusy 435 } 436 defer atomic.StoreInt32(&d.synchronising, 0) 437 438 // Post a user notification of the sync (only once per session) 439 if atomic.CompareAndSwapInt32(&d.notified, 0, 1) { 440 log.Info("Block synchronisation started") 441 } 442 // If we are already full syncing, but have a fast-sync bloom filter laying 443 // around, make sure it doesn't use memory any more. This is a special case 444 // when the user attempts to fast sync a new empty network. 445 if mode == FullSync && d.stateBloom != nil { 446 d.stateBloom.Close() 447 } 448 // If snap sync was requested, create the snap scheduler and switch to fast 449 // sync mode. Long term we could drop fast sync or merge the two together, 450 // but until snap becomes prevalent, we should support both. TODO(karalabe). 451 if mode == SnapSync { 452 if !d.snapSync { 453 // Snap sync uses the snapshot namespace to store potentially flakey data until 454 // sync completely heals and finishes. Pause snapshot maintenance in the mean 455 // time to prevent access. 456 if snapshots := d.blockchain.Snapshots(); snapshots != nil { // Only nil in tests 457 snapshots.Disable() 458 } 459 log.Warn("Enabling snapshot sync prototype") 460 d.snapSync = true 461 } 462 mode = FastSync 463 } 464 // Reset the queue, peer set and wake channels to clean any internal leftover state 465 d.queue.Reset(blockCacheMaxItems, blockCacheInitialItems) 466 d.peers.Reset() 467 468 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 469 select { 470 case <-ch: 471 default: 472 } 473 } 474 for _, ch := range []chan dataPack{d.headerCh, d.bodyCh, d.receiptCh} { 475 for empty := false; !empty; { 476 select { 477 case <-ch: 478 default: 479 empty = true 480 } 481 } 482 } 483 for empty := false; !empty; { 484 select { 485 case <-d.headerProcCh: 486 default: 487 empty = true 488 } 489 } 490 // Create cancel channel for aborting mid-flight and mark the master peer 491 d.cancelLock.Lock() 492 d.cancelCh = make(chan struct{}) 493 d.cancelPeer = id 494 d.cancelLock.Unlock() 495 496 defer d.Cancel() // No matter what, we can't leave the cancel channel open 497 498 // Atomically set the requested sync mode 499 atomic.StoreUint32(&d.mode, uint32(mode)) 500 501 // Retrieve the origin peer and initiate the downloading process 502 p := d.peers.Peer(id) 503 if p == nil { 504 return errUnknownPeer 505 } 506 return d.syncWithPeer(p, hash, td) 507 } 508 509 func (d *Downloader) getMode() SyncMode { 510 return SyncMode(atomic.LoadUint32(&d.mode)) 511 } 512 513 // syncWithPeer starts a block synchronization based on the hash chain from the 514 // specified peer and head hash. 515 func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.Int) (err error) { 516 d.mux.Post(StartEvent{}) 517 defer func() { 518 // reset on error 519 if err != nil { 520 d.mux.Post(FailedEvent{err}) 521 } else { 522 latest := d.lightchain.CurrentHeader() 523 d.mux.Post(DoneEvent{latest}) 524 } 525 }() 526 if p.version < eth.ETH65 { 527 return fmt.Errorf("%w: advertized %d < required %d", errTooOld, p.version, eth.ETH65) 528 } 529 mode := d.getMode() 530 531 log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", mode) 532 defer func(start time.Time) { 533 log.Debug("Synchronisation terminated", "elapsed", common.PrettyDuration(time.Since(start))) 534 }(time.Now()) 535 536 // Look up the sync boundaries: the common ancestor and the target block 537 latest, pivot, err := d.fetchHead(p) 538 if err != nil { 539 return err 540 } 541 if mode == FastSync && pivot == nil { 542 // If no pivot block was returned, the head is below the min full block 543 // threshold (i.e. new chian). In that case we won't really fast sync 544 // anyway, but still need a valid pivot block to avoid some code hitting 545 // nil panics on an access. 546 pivot = d.blockchain.CurrentBlock().Header() 547 } 548 height := latest.Number.Uint64() 549 550 origin, err := d.findAncestor(p, latest) 551 if err != nil { 552 return err 553 } 554 d.syncStatsLock.Lock() 555 if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin { 556 d.syncStatsChainOrigin = origin 557 } 558 d.syncStatsChainHeight = height 559 d.syncStatsLock.Unlock() 560 561 // Ensure our origin point is below any fast sync pivot point 562 if mode == FastSync { 563 if height <= uint64(fsMinFullBlocks) { 564 origin = 0 565 } else { 566 pivotNumber := pivot.Number.Uint64() 567 if pivotNumber <= origin { 568 origin = pivotNumber - 1 569 } 570 // Write out the pivot into the database so a rollback beyond it will 571 // reenable fast sync 572 rawdb.WriteLastPivotNumber(d.stateDB, pivotNumber) 573 } 574 } 575 d.committed = 1 576 if mode == FastSync && pivot.Number.Uint64() != 0 { 577 d.committed = 0 578 } 579 if mode == FastSync { 580 // Set the ancient data limitation. 581 // If we are running fast sync, all block data older than ancientLimit will be 582 // written to the ancient store. More recent data will be written to the active 583 // database and will wait for the freezer to migrate. 584 // 585 // If there is a checkpoint available, then calculate the ancientLimit through 586 // that. Otherwise calculate the ancient limit through the advertised height 587 // of the remote peer. 588 // 589 // The reason for picking checkpoint first is that a malicious peer can give us 590 // a fake (very high) height, forcing the ancient limit to also be very high. 591 // The peer would start to feed us valid blocks until head, resulting in all of 592 // the blocks might be written into the ancient store. A following mini-reorg 593 // could cause issues. 594 if d.checkpoint != 0 && d.checkpoint > fullMaxForkAncestry+1 { 595 d.ancientLimit = d.checkpoint 596 } else if height > fullMaxForkAncestry+1 { 597 d.ancientLimit = height - fullMaxForkAncestry - 1 598 } else { 599 d.ancientLimit = 0 600 } 601 frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here. 602 itemAmountInAncient, _ := d.stateDB.ItemAmountInAncient() 603 // If a part of blockchain data has already been written into active store, 604 // disable the ancient style insertion explicitly. 605 if origin >= frozen && itemAmountInAncient != 0 { 606 d.ancientLimit = 0 607 log.Info("Disabling direct-ancient mode", "origin", origin, "ancient", frozen-1) 608 } else if d.ancientLimit > 0 { 609 log.Debug("Enabling direct-ancient mode", "ancient", d.ancientLimit) 610 } 611 // Rewind the ancient store and blockchain if reorg happens. 612 if origin+1 < frozen { 613 if err := d.lightchain.SetHead(origin + 1); err != nil { 614 return err 615 } 616 } 617 } 618 // Initiate the sync using a concurrent header and content retrieval algorithm 619 d.queue.Prepare(origin+1, mode) 620 if d.syncInitHook != nil { 621 d.syncInitHook(origin, height) 622 } 623 fetchers := []func() error{ 624 func() error { return d.fetchHeaders(p, origin+1) }, // Headers are always retrieved 625 func() error { return d.fetchBodies(origin + 1) }, // Bodies are retrieved during normal and fast sync 626 func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync 627 func() error { return d.processHeaders(origin+1, td) }, 628 } 629 if mode == FastSync { 630 d.pivotLock.Lock() 631 d.pivotHeader = pivot 632 d.pivotLock.Unlock() 633 634 fetchers = append(fetchers, func() error { return d.processFastSyncContent() }) 635 } else if mode == FullSync { 636 fetchers = append(fetchers, d.processFullSyncContent) 637 } 638 return d.spawnSync(fetchers) 639 } 640 641 // spawnSync runs d.process and all given fetcher functions to completion in 642 // separate goroutines, returning the first error that appears. 643 func (d *Downloader) spawnSync(fetchers []func() error) error { 644 errc := make(chan error, len(fetchers)) 645 d.cancelWg.Add(len(fetchers)) 646 for _, fn := range fetchers { 647 fn := fn 648 go func() { defer d.cancelWg.Done(); errc <- fn() }() 649 } 650 // Wait for the first error, then terminate the others. 651 var err error 652 for i := 0; i < len(fetchers); i++ { 653 if i == len(fetchers)-1 { 654 // Close the queue when all fetchers have exited. 655 // This will cause the block processor to end when 656 // it has processed the queue. 657 d.queue.Close() 658 } 659 if err = <-errc; err != nil && err != errCanceled { 660 break 661 } 662 } 663 d.queue.Close() 664 d.Cancel() 665 return err 666 } 667 668 // cancel aborts all of the operations and resets the queue. However, cancel does 669 // not wait for the running download goroutines to finish. This method should be 670 // used when cancelling the downloads from inside the downloader. 671 func (d *Downloader) cancel() { 672 // Close the current cancel channel 673 d.cancelLock.Lock() 674 defer d.cancelLock.Unlock() 675 676 if d.cancelCh != nil { 677 select { 678 case <-d.cancelCh: 679 // Channel was already closed 680 default: 681 close(d.cancelCh) 682 } 683 } 684 } 685 686 // Cancel aborts all of the operations and waits for all download goroutines to 687 // finish before returning. 688 func (d *Downloader) Cancel() { 689 d.cancel() 690 d.cancelWg.Wait() 691 } 692 693 // Terminate interrupts the downloader, canceling all pending operations. 694 // The downloader cannot be reused after calling Terminate. 695 func (d *Downloader) Terminate() { 696 // Close the termination channel (make sure double close is allowed) 697 d.quitLock.Lock() 698 select { 699 case <-d.quitCh: 700 default: 701 close(d.quitCh) 702 } 703 if d.stateBloom != nil { 704 d.stateBloom.Close() 705 } 706 d.quitLock.Unlock() 707 708 // Cancel any pending download requests 709 d.Cancel() 710 } 711 712 // fetchHead retrieves the head header and prior pivot block (if available) from 713 // a remote peer. 714 func (d *Downloader) fetchHead(p *peerConnection) (head *types.Header, pivot *types.Header, err error) { 715 p.log.Debug("Retrieving remote chain head") 716 mode := d.getMode() 717 718 // Request the advertised remote head block and wait for the response 719 latest, _ := p.peer.Head() 720 fetch := 1 721 if mode == FastSync { 722 fetch = 2 // head + pivot headers 723 } 724 go p.peer.RequestHeadersByHash(latest, fetch, fsMinFullBlocks-1, true) 725 726 ttl := d.requestTTL() 727 timeout := time.After(ttl) 728 for { 729 select { 730 case <-d.cancelCh: 731 return nil, nil, errCanceled 732 733 case packet := <-d.headerCh: 734 // Discard anything not from the origin peer 735 if packet.PeerId() != p.id { 736 log.Debug("Received headers from incorrect peer", "peer", packet.PeerId()) 737 break 738 } 739 // Make sure the peer gave us at least one and at most the requested headers 740 headers := packet.(*headerPack).headers 741 if len(headers) == 0 || len(headers) > fetch { 742 return nil, nil, fmt.Errorf("%w: returned headers %d != requested %d", errBadPeer, len(headers), fetch) 743 } 744 // The first header needs to be the head, validate against the checkpoint 745 // and request. If only 1 header was returned, make sure there's no pivot 746 // or there was not one requested. 747 head := headers[0] 748 if (mode == FastSync || mode == LightSync) && head.Number.Uint64() < d.checkpoint { 749 return nil, nil, fmt.Errorf("%w: remote head %d below checkpoint %d", errUnsyncedPeer, head.Number, d.checkpoint) 750 } 751 if len(headers) == 1 { 752 if mode == FastSync && head.Number.Uint64() > uint64(fsMinFullBlocks) { 753 return nil, nil, fmt.Errorf("%w: no pivot included along head header", errBadPeer) 754 } 755 p.log.Debug("Remote head identified, no pivot", "number", head.Number, "hash", head.Hash()) 756 return head, nil, nil 757 } 758 // At this point we have 2 headers in total and the first is the 759 // validated head of the chian. Check the pivot number and return, 760 pivot := headers[1] 761 if pivot.Number.Uint64() != head.Number.Uint64()-uint64(fsMinFullBlocks) { 762 return nil, nil, fmt.Errorf("%w: remote pivot %d != requested %d", errInvalidChain, pivot.Number, head.Number.Uint64()-uint64(fsMinFullBlocks)) 763 } 764 return head, pivot, nil 765 766 case <-timeout: 767 p.log.Debug("Waiting for head header timed out", "elapsed", ttl) 768 return nil, nil, errTimeout 769 770 case <-d.bodyCh: 771 case <-d.receiptCh: 772 // Out of bounds delivery, ignore 773 } 774 } 775 } 776 777 // calculateRequestSpan calculates what headers to request from a peer when trying to determine the 778 // common ancestor. 779 // It returns parameters to be used for peer.RequestHeadersByNumber: 780 // from - starting block number 781 // count - number of headers to request 782 // skip - number of headers to skip 783 // and also returns 'max', the last block which is expected to be returned by the remote peers, 784 // given the (from,count,skip) 785 func calculateRequestSpan(remoteHeight, localHeight uint64) (int64, int, int, uint64) { 786 var ( 787 from int 788 count int 789 MaxCount = MaxHeaderFetch / 16 790 ) 791 // requestHead is the highest block that we will ask for. If requestHead is not offset, 792 // the highest block that we will get is 16 blocks back from head, which means we 793 // will fetch 14 or 15 blocks unnecessarily in the case the height difference 794 // between us and the peer is 1-2 blocks, which is most common 795 requestHead := int(remoteHeight) - 1 796 if requestHead < 0 { 797 requestHead = 0 798 } 799 // requestBottom is the lowest block we want included in the query 800 // Ideally, we want to include the one just below our own head 801 requestBottom := int(localHeight - 1) 802 if requestBottom < 0 { 803 requestBottom = 0 804 } 805 totalSpan := requestHead - requestBottom 806 span := 1 + totalSpan/MaxCount 807 if span < 2 { 808 span = 2 809 } 810 if span > 16 { 811 span = 16 812 } 813 814 count = 1 + totalSpan/span 815 if count > MaxCount { 816 count = MaxCount 817 } 818 if count < 2 { 819 count = 2 820 } 821 from = requestHead - (count-1)*span 822 if from < 0 { 823 from = 0 824 } 825 max := from + (count-1)*span 826 return int64(from), count, span - 1, uint64(max) 827 } 828 829 // findAncestor tries to locate the common ancestor link of the local chain and 830 // a remote peers blockchain. In the general case when our node was in sync and 831 // on the correct chain, checking the top N links should already get us a match. 832 // In the rare scenario when we ended up on a long reorganisation (i.e. none of 833 // the head links match), we do a binary search to find the common ancestor. 834 func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header) (uint64, error) { 835 // Figure out the valid ancestor range to prevent rewrite attacks 836 var ( 837 floor = int64(-1) 838 localHeight uint64 839 remoteHeight = remoteHeader.Number.Uint64() 840 ) 841 mode := d.getMode() 842 switch mode { 843 case FullSync: 844 localHeight = d.blockchain.CurrentBlock().NumberU64() 845 case FastSync: 846 localHeight = d.blockchain.CurrentFastBlock().NumberU64() 847 default: 848 localHeight = d.lightchain.CurrentHeader().Number.Uint64() 849 } 850 p.log.Debug("Looking for common ancestor", "local", localHeight, "remote", remoteHeight) 851 852 // Recap floor value for binary search 853 maxForkAncestry := fullMaxForkAncestry 854 if d.getMode() == LightSync { 855 maxForkAncestry = lightMaxForkAncestry 856 } 857 if localHeight >= maxForkAncestry { 858 // We're above the max reorg threshold, find the earliest fork point 859 floor = int64(localHeight - maxForkAncestry) 860 } 861 // If we're doing a light sync, ensure the floor doesn't go below the CHT, as 862 // all headers before that point will be missing. 863 if mode == LightSync { 864 // If we don't know the current CHT position, find it 865 if d.genesis == 0 { 866 header := d.lightchain.CurrentHeader() 867 for header != nil { 868 d.genesis = header.Number.Uint64() 869 if floor >= int64(d.genesis)-1 { 870 break 871 } 872 header = d.lightchain.GetHeaderByHash(header.ParentHash) 873 } 874 } 875 // We already know the "genesis" block number, cap floor to that 876 if floor < int64(d.genesis)-1 { 877 floor = int64(d.genesis) - 1 878 } 879 } 880 881 ancestor, err := d.findAncestorSpanSearch(p, mode, remoteHeight, localHeight, floor) 882 if err == nil { 883 return ancestor, nil 884 } 885 // The returned error was not nil. 886 // If the error returned does not reflect that a common ancestor was not found, return it. 887 // If the error reflects that a common ancestor was not found, continue to binary search, 888 // where the error value will be reassigned. 889 if !errors.Is(err, errNoAncestorFound) { 890 return 0, err 891 } 892 893 ancestor, err = d.findAncestorBinarySearch(p, mode, remoteHeight, floor) 894 if err != nil { 895 return 0, err 896 } 897 return ancestor, nil 898 } 899 900 func (d *Downloader) findAncestorSpanSearch(p *peerConnection, mode SyncMode, remoteHeight, localHeight uint64, floor int64) (commonAncestor uint64, err error) { 901 from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight) 902 903 p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip) 904 go p.peer.RequestHeadersByNumber(uint64(from), count, skip, false) 905 906 // Wait for the remote response to the head fetch 907 number, hash := uint64(0), common.Hash{} 908 909 ttl := d.requestTTL() 910 timeout := time.After(ttl) 911 912 for finished := false; !finished; { 913 select { 914 case <-d.cancelCh: 915 return 0, errCanceled 916 917 case packet := <-d.headerCh: 918 // Discard anything not from the origin peer 919 if packet.PeerId() != p.id { 920 log.Debug("Received headers from incorrect peer", "peer", packet.PeerId()) 921 break 922 } 923 // Make sure the peer actually gave something valid 924 headers := packet.(*headerPack).headers 925 if len(headers) == 0 { 926 p.log.Warn("Empty head header set") 927 return 0, errEmptyHeaderSet 928 } 929 // Make sure the peer's reply conforms to the request 930 for i, header := range headers { 931 expectNumber := from + int64(i)*int64(skip+1) 932 if number := header.Number.Int64(); number != expectNumber { 933 p.log.Warn("Head headers broke chain ordering", "index", i, "requested", expectNumber, "received", number) 934 return 0, fmt.Errorf("%w: %v", errInvalidChain, errors.New("head headers broke chain ordering")) 935 } 936 } 937 // Check if a common ancestor was found 938 finished = true 939 for i := len(headers) - 1; i >= 0; i-- { 940 // Skip any headers that underflow/overflow our requested set 941 if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > max { 942 continue 943 } 944 // Otherwise check if we already know the header or not 945 h := headers[i].Hash() 946 n := headers[i].Number.Uint64() 947 948 var known bool 949 switch mode { 950 case FullSync: 951 known = d.blockchain.HasBlock(h, n) 952 case FastSync: 953 known = d.blockchain.HasFastBlock(h, n) 954 default: 955 known = d.lightchain.HasHeader(h, n) 956 } 957 if known { 958 number, hash = n, h 959 break 960 } 961 } 962 963 case <-timeout: 964 p.log.Debug("Waiting for head header timed out", "elapsed", ttl) 965 return 0, errTimeout 966 967 case <-d.bodyCh: 968 case <-d.receiptCh: 969 // Out of bounds delivery, ignore 970 } 971 } 972 // If the head fetch already found an ancestor, return 973 if hash != (common.Hash{}) { 974 if int64(number) <= floor { 975 p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor) 976 return 0, errInvalidAncestor 977 } 978 p.log.Debug("Found common ancestor", "number", number, "hash", hash) 979 return number, nil 980 } 981 return 0, errNoAncestorFound 982 } 983 984 func (d *Downloader) findAncestorBinarySearch(p *peerConnection, mode SyncMode, remoteHeight uint64, floor int64) (commonAncestor uint64, err error) { 985 hash := common.Hash{} 986 987 // Ancestor not found, we need to binary search over our chain 988 start, end := uint64(0), remoteHeight 989 if floor > 0 { 990 start = uint64(floor) 991 } 992 p.log.Trace("Binary searching for common ancestor", "start", start, "end", end) 993 994 for start+1 < end { 995 // Split our chain interval in two, and request the hash to cross check 996 check := (start + end) / 2 997 998 ttl := d.requestTTL() 999 timeout := time.After(ttl) 1000 1001 go p.peer.RequestHeadersByNumber(check, 1, 0, false) 1002 1003 // Wait until a reply arrives to this request 1004 for arrived := false; !arrived; { 1005 select { 1006 case <-d.cancelCh: 1007 return 0, errCanceled 1008 1009 case packet := <-d.headerCh: 1010 // Discard anything not from the origin peer 1011 if packet.PeerId() != p.id { 1012 log.Debug("Received headers from incorrect peer", "peer", packet.PeerId()) 1013 break 1014 } 1015 // Make sure the peer actually gave something valid 1016 headers := packet.(*headerPack).headers 1017 if len(headers) != 1 { 1018 p.log.Warn("Multiple headers for single request", "headers", len(headers)) 1019 return 0, fmt.Errorf("%w: multiple headers (%d) for single request", errBadPeer, len(headers)) 1020 } 1021 arrived = true 1022 1023 // Modify the search interval based on the response 1024 h := headers[0].Hash() 1025 n := headers[0].Number.Uint64() 1026 1027 var known bool 1028 switch mode { 1029 case FullSync: 1030 known = d.blockchain.HasBlock(h, n) 1031 case FastSync: 1032 known = d.blockchain.HasFastBlock(h, n) 1033 default: 1034 known = d.lightchain.HasHeader(h, n) 1035 } 1036 if !known { 1037 end = check 1038 break 1039 } 1040 header := d.lightchain.GetHeaderByHash(h) // Independent of sync mode, header surely exists 1041 if header == nil { 1042 p.log.Error("header not found", "hash", h, "request", check) 1043 return 0, fmt.Errorf("%w: header no found (%s)", errBadPeer, h) 1044 } 1045 if header.Number.Uint64() != check { 1046 p.log.Warn("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check) 1047 return 0, fmt.Errorf("%w: non-requested header (%d)", errBadPeer, header.Number) 1048 } 1049 start = check 1050 hash = h 1051 1052 case <-timeout: 1053 p.log.Debug("Waiting for search header timed out", "elapsed", ttl) 1054 return 0, errTimeout 1055 1056 case <-d.bodyCh: 1057 case <-d.receiptCh: 1058 // Out of bounds delivery, ignore 1059 } 1060 } 1061 } 1062 // Ensure valid ancestry and return 1063 if int64(start) <= floor { 1064 p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor) 1065 return 0, errInvalidAncestor 1066 } 1067 p.log.Debug("Found common ancestor", "number", start, "hash", hash) 1068 return start, nil 1069 } 1070 1071 // fetchHeaders keeps retrieving headers concurrently from the number 1072 // requested, until no more are returned, potentially throttling on the way. To 1073 // facilitate concurrency but still protect against malicious nodes sending bad 1074 // headers, we construct a header chain skeleton using the "origin" peer we are 1075 // syncing with, and fill in the missing headers using anyone else. Headers from 1076 // other peers are only accepted if they map cleanly to the skeleton. If no one 1077 // can fill in the skeleton - not even the origin peer - it's assumed invalid and 1078 // the origin is dropped. 1079 func (d *Downloader) fetchHeaders(p *peerConnection, from uint64) error { 1080 p.log.Debug("Directing header downloads", "origin", from) 1081 defer p.log.Debug("Header download terminated") 1082 1083 // Create a timeout timer, and the associated header fetcher 1084 skeleton := true // Skeleton assembly phase or finishing up 1085 pivoting := false // Whether the next request is pivot verification 1086 request := time.Now() // time of the last skeleton fetch request 1087 timeout := time.NewTimer(0) // timer to dump a non-responsive active peer 1088 <-timeout.C // timeout channel should be initially empty 1089 defer timeout.Stop() 1090 1091 var ttl time.Duration 1092 getHeaders := func(from uint64) { 1093 request = time.Now() 1094 1095 ttl = d.requestTTL() 1096 timeout.Reset(ttl) 1097 1098 if skeleton { 1099 p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from) 1100 go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false) 1101 } else { 1102 p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from) 1103 go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false) 1104 } 1105 } 1106 getNextPivot := func() { 1107 pivoting = true 1108 request = time.Now() 1109 1110 ttl = d.requestTTL() 1111 timeout.Reset(ttl) 1112 1113 d.pivotLock.RLock() 1114 pivot := d.pivotHeader.Number.Uint64() 1115 d.pivotLock.RUnlock() 1116 1117 p.log.Trace("Fetching next pivot header", "number", pivot+uint64(fsMinFullBlocks)) 1118 go p.peer.RequestHeadersByNumber(pivot+uint64(fsMinFullBlocks), 2, fsMinFullBlocks-9, false) // move +64 when it's 2x64-8 deep 1119 } 1120 // Start pulling the header chain skeleton until all is done 1121 ancestor := from 1122 getHeaders(from) 1123 1124 mode := d.getMode() 1125 for { 1126 select { 1127 case <-d.cancelCh: 1128 return errCanceled 1129 1130 case packet := <-d.headerCh: 1131 // Make sure the active peer is giving us the skeleton headers 1132 if packet.PeerId() != p.id { 1133 log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId()) 1134 break 1135 } 1136 headerReqTimer.UpdateSince(request) 1137 timeout.Stop() 1138 1139 // If the pivot is being checked, move if it became stale and run the real retrieval 1140 var pivot uint64 1141 1142 d.pivotLock.RLock() 1143 if d.pivotHeader != nil { 1144 pivot = d.pivotHeader.Number.Uint64() 1145 } 1146 d.pivotLock.RUnlock() 1147 1148 if pivoting { 1149 if packet.Items() == 2 { 1150 // Retrieve the headers and do some sanity checks, just in case 1151 headers := packet.(*headerPack).headers 1152 1153 if have, want := headers[0].Number.Uint64(), pivot+uint64(fsMinFullBlocks); have != want { 1154 log.Warn("Peer sent invalid next pivot", "have", have, "want", want) 1155 return fmt.Errorf("%w: next pivot number %d != requested %d", errInvalidChain, have, want) 1156 } 1157 if have, want := headers[1].Number.Uint64(), pivot+2*uint64(fsMinFullBlocks)-8; have != want { 1158 log.Warn("Peer sent invalid pivot confirmer", "have", have, "want", want) 1159 return fmt.Errorf("%w: next pivot confirmer number %d != requested %d", errInvalidChain, have, want) 1160 } 1161 log.Warn("Pivot seemingly stale, moving", "old", pivot, "new", headers[0].Number) 1162 pivot = headers[0].Number.Uint64() 1163 1164 d.pivotLock.Lock() 1165 d.pivotHeader = headers[0] 1166 d.pivotLock.Unlock() 1167 1168 // Write out the pivot into the database so a rollback beyond 1169 // it will reenable fast sync and update the state root that 1170 // the state syncer will be downloading. 1171 rawdb.WriteLastPivotNumber(d.stateDB, pivot) 1172 } 1173 pivoting = false 1174 getHeaders(from) 1175 continue 1176 } 1177 // If the skeleton's finished, pull any remaining head headers directly from the origin 1178 if skeleton && packet.Items() == 0 { 1179 skeleton = false 1180 getHeaders(from) 1181 continue 1182 } 1183 // If no more headers are inbound, notify the content fetchers and return 1184 if packet.Items() == 0 { 1185 // Don't abort header fetches while the pivot is downloading 1186 if atomic.LoadInt32(&d.committed) == 0 && pivot <= from { 1187 p.log.Debug("No headers, waiting for pivot commit") 1188 select { 1189 case <-time.After(fsHeaderContCheck): 1190 getHeaders(from) 1191 continue 1192 case <-d.cancelCh: 1193 return errCanceled 1194 } 1195 } 1196 // Pivot done (or not in fast sync) and no more headers, terminate the process 1197 p.log.Debug("No more headers available") 1198 select { 1199 case d.headerProcCh <- nil: 1200 return nil 1201 case <-d.cancelCh: 1202 return errCanceled 1203 } 1204 } 1205 headers := packet.(*headerPack).headers 1206 1207 // If we received a skeleton batch, resolve internals concurrently 1208 if skeleton { 1209 filled, proced, err := d.fillHeaderSkeleton(from, headers) 1210 if err != nil { 1211 p.log.Debug("Skeleton chain invalid", "err", err) 1212 return fmt.Errorf("%w: %v", errInvalidChain, err) 1213 } 1214 headers = filled[proced:] 1215 from += uint64(proced) 1216 } else { 1217 // If we're closing in on the chain head, but haven't yet reached it, delay 1218 // the last few headers so mini reorgs on the head don't cause invalid hash 1219 // chain errors. 1220 if n := len(headers); n > 0 { 1221 // Retrieve the current head we're at 1222 var head uint64 1223 if mode == LightSync { 1224 head = d.lightchain.CurrentHeader().Number.Uint64() 1225 } else { 1226 head = d.blockchain.CurrentFastBlock().NumberU64() 1227 if full := d.blockchain.CurrentBlock().NumberU64(); head < full { 1228 head = full 1229 } 1230 } 1231 // If the head is below the common ancestor, we're actually deduplicating 1232 // already existing chain segments, so use the ancestor as the fake head. 1233 // Otherwise we might end up delaying header deliveries pointlessly. 1234 if head < ancestor { 1235 head = ancestor 1236 } 1237 // If the head is way older than this batch, delay the last few headers 1238 if head+uint64(reorgProtThreshold) < headers[n-1].Number.Uint64() { 1239 delay := reorgProtHeaderDelay 1240 if delay > n { 1241 delay = n 1242 } 1243 headers = headers[:n-delay] 1244 } 1245 } 1246 } 1247 // Insert all the new headers and fetch the next batch 1248 if len(headers) > 0 { 1249 p.log.Trace("Scheduling new headers", "count", len(headers), "from", from) 1250 select { 1251 case d.headerProcCh <- headers: 1252 case <-d.cancelCh: 1253 return errCanceled 1254 } 1255 from += uint64(len(headers)) 1256 1257 // If we're still skeleton filling fast sync, check pivot staleness 1258 // before continuing to the next skeleton filling 1259 if skeleton && pivot > 0 { 1260 getNextPivot() 1261 } else { 1262 getHeaders(from) 1263 } 1264 } else { 1265 // No headers delivered, or all of them being delayed, sleep a bit and retry 1266 p.log.Trace("All headers delayed, waiting") 1267 select { 1268 case <-time.After(fsHeaderContCheck): 1269 getHeaders(from) 1270 continue 1271 case <-d.cancelCh: 1272 return errCanceled 1273 } 1274 } 1275 1276 case <-timeout.C: 1277 if d.dropPeer == nil { 1278 // The dropPeer method is nil when `--copydb` is used for a local copy. 1279 // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored 1280 p.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", p.id) 1281 break 1282 } 1283 // Header retrieval timed out, consider the peer bad and drop 1284 p.log.Debug("Header request timed out", "elapsed", ttl) 1285 headerTimeoutMeter.Mark(1) 1286 d.dropPeer(p.id) 1287 1288 // Finish the sync gracefully instead of dumping the gathered data though 1289 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 1290 select { 1291 case ch <- false: 1292 case <-d.cancelCh: 1293 } 1294 } 1295 select { 1296 case d.headerProcCh <- nil: 1297 case <-d.cancelCh: 1298 } 1299 return fmt.Errorf("%w: header request timed out", errBadPeer) 1300 } 1301 } 1302 } 1303 1304 // fillHeaderSkeleton concurrently retrieves headers from all our available peers 1305 // and maps them to the provided skeleton header chain. 1306 // 1307 // Any partial results from the beginning of the skeleton is (if possible) forwarded 1308 // immediately to the header processor to keep the rest of the pipeline full even 1309 // in the case of header stalls. 1310 // 1311 // The method returns the entire filled skeleton and also the number of headers 1312 // already forwarded for processing. 1313 func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) { 1314 log.Debug("Filling up skeleton", "from", from) 1315 d.queue.ScheduleSkeleton(from, skeleton) 1316 1317 var ( 1318 deliver = func(packet dataPack) (int, error) { 1319 pack := packet.(*headerPack) 1320 return d.queue.DeliverHeaders(pack.peerID, pack.headers, d.headerProcCh) 1321 } 1322 expire = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) } 1323 reserve = func(p *peerConnection, count int) (*fetchRequest, bool, bool) { 1324 return d.queue.ReserveHeaders(p, count), false, false 1325 } 1326 fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) } 1327 capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) } 1328 setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) { 1329 p.SetHeadersIdle(accepted, deliveryTime) 1330 } 1331 ) 1332 err := d.fetchParts(d.headerCh, deliver, d.queue.headerContCh, expire, 1333 d.queue.PendingHeaders, d.queue.InFlightHeaders, reserve, 1334 nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers") 1335 1336 log.Debug("Skeleton fill terminated", "err", err) 1337 1338 filled, proced := d.queue.RetrieveHeaders() 1339 return filled, proced, err 1340 } 1341 1342 // fetchBodies iteratively downloads the scheduled block bodies, taking any 1343 // available peers, reserving a chunk of blocks for each, waiting for delivery 1344 // and also periodically checking for timeouts. 1345 func (d *Downloader) fetchBodies(from uint64) error { 1346 log.Debug("Downloading block bodies", "origin", from) 1347 1348 var ( 1349 deliver = func(packet dataPack) (int, error) { 1350 pack := packet.(*bodyPack) 1351 return d.queue.DeliverBodies(pack.peerID, pack.transactions, pack.uncles) 1352 } 1353 expire = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) } 1354 fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) } 1355 capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) } 1356 setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) { p.SetBodiesIdle(accepted, deliveryTime) } 1357 ) 1358 err := d.fetchParts(d.bodyCh, deliver, d.bodyWakeCh, expire, 1359 d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ReserveBodies, 1360 d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies") 1361 1362 log.Debug("Block body download terminated", "err", err) 1363 return err 1364 } 1365 1366 // fetchReceipts iteratively downloads the scheduled block receipts, taking any 1367 // available peers, reserving a chunk of receipts for each, waiting for delivery 1368 // and also periodically checking for timeouts. 1369 func (d *Downloader) fetchReceipts(from uint64) error { 1370 log.Debug("Downloading transaction receipts", "origin", from) 1371 1372 var ( 1373 deliver = func(packet dataPack) (int, error) { 1374 pack := packet.(*receiptPack) 1375 return d.queue.DeliverReceipts(pack.peerID, pack.receipts) 1376 } 1377 expire = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) } 1378 fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) } 1379 capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) } 1380 setIdle = func(p *peerConnection, accepted int, deliveryTime time.Time) { 1381 p.SetReceiptsIdle(accepted, deliveryTime) 1382 } 1383 ) 1384 err := d.fetchParts(d.receiptCh, deliver, d.receiptWakeCh, expire, 1385 d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ReserveReceipts, 1386 d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts") 1387 1388 log.Debug("Transaction receipt download terminated", "err", err) 1389 return err 1390 } 1391 1392 // fetchParts iteratively downloads scheduled block parts, taking any available 1393 // peers, reserving a chunk of fetch requests for each, waiting for delivery and 1394 // also periodically checking for timeouts. 1395 // 1396 // As the scheduling/timeout logic mostly is the same for all downloaded data 1397 // types, this method is used by each for data gathering and is instrumented with 1398 // various callbacks to handle the slight differences between processing them. 1399 // 1400 // The instrumentation parameters: 1401 // - errCancel: error type to return if the fetch operation is cancelled (mostly makes logging nicer) 1402 // - deliveryCh: channel from which to retrieve downloaded data packets (merged from all concurrent peers) 1403 // - deliver: processing callback to deliver data packets into type specific download queues (usually within `queue`) 1404 // - wakeCh: notification channel for waking the fetcher when new tasks are available (or sync completed) 1405 // - expire: task callback method to abort requests that took too long and return the faulty peers (traffic shaping) 1406 // - pending: task callback for the number of requests still needing download (detect completion/non-completability) 1407 // - inFlight: task callback for the number of in-progress requests (wait for all active downloads to finish) 1408 // - throttle: task callback to check if the processing queue is full and activate throttling (bound memory use) 1409 // - reserve: task callback to reserve new download tasks to a particular peer (also signals partial completions) 1410 // - fetchHook: tester callback to notify of new tasks being initiated (allows testing the scheduling logic) 1411 // - fetch: network callback to actually send a particular download request to a physical remote peer 1412 // - cancel: task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer) 1413 // - capacity: network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping) 1414 // - idle: network callback to retrieve the currently (type specific) idle peers that can be assigned tasks 1415 // - setIdle: network callback to set a peer back to idle and update its estimated capacity (traffic shaping) 1416 // - kind: textual label of the type being downloaded to display in log messages 1417 func (d *Downloader) fetchParts(deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool, 1418 expire func() map[string]int, pending func() int, inFlight func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, bool), 1419 fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int, 1420 idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int, time.Time), kind string) error { 1421 1422 // Create a ticker to detect expired retrieval tasks 1423 ticker := time.NewTicker(100 * time.Millisecond) 1424 defer ticker.Stop() 1425 1426 update := make(chan struct{}, 1) 1427 1428 // Prepare the queue and fetch block parts until the block header fetcher's done 1429 finished := false 1430 for { 1431 select { 1432 case <-d.cancelCh: 1433 return errCanceled 1434 1435 case packet := <-deliveryCh: 1436 deliveryTime := time.Now() 1437 // If the peer was previously banned and failed to deliver its pack 1438 // in a reasonable time frame, ignore its message. 1439 if peer := d.peers.Peer(packet.PeerId()); peer != nil { 1440 // Deliver the received chunk of data and check chain validity 1441 accepted, err := deliver(packet) 1442 if errors.Is(err, errInvalidChain) { 1443 return err 1444 } 1445 // Unless a peer delivered something completely else than requested (usually 1446 // caused by a timed out request which came through in the end), set it to 1447 // idle. If the delivery's stale, the peer should have already been idled. 1448 if !errors.Is(err, errStaleDelivery) { 1449 setIdle(peer, accepted, deliveryTime) 1450 } 1451 // Issue a log to the user to see what's going on 1452 switch { 1453 case err == nil && packet.Items() == 0: 1454 peer.log.Trace("Requested data not delivered", "type", kind) 1455 case err == nil: 1456 peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats()) 1457 default: 1458 peer.log.Debug("Failed to deliver retrieved data", "type", kind, "err", err) 1459 } 1460 } 1461 // Blocks assembled, try to update the progress 1462 select { 1463 case update <- struct{}{}: 1464 default: 1465 } 1466 1467 case cont := <-wakeCh: 1468 // The header fetcher sent a continuation flag, check if it's done 1469 if !cont { 1470 finished = true 1471 } 1472 // Headers arrive, try to update the progress 1473 select { 1474 case update <- struct{}{}: 1475 default: 1476 } 1477 1478 case <-ticker.C: 1479 // Sanity check update the progress 1480 select { 1481 case update <- struct{}{}: 1482 default: 1483 } 1484 1485 case <-update: 1486 // Short circuit if we lost all our peers 1487 if d.peers.Len() == 0 { 1488 return errNoPeers 1489 } 1490 // Check for fetch request timeouts and demote the responsible peers 1491 for pid, fails := range expire() { 1492 if peer := d.peers.Peer(pid); peer != nil { 1493 // If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps 1494 // ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times 1495 // out that sync wise we need to get rid of the peer. 1496 // 1497 // The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth 1498 // and latency of a peer separately, which requires pushing the measures capacity a bit and seeing 1499 // how response times reacts, to it always requests one more than the minimum (i.e. min 2). 1500 if fails > 2 { 1501 peer.log.Trace("Data delivery timed out", "type", kind) 1502 setIdle(peer, 0, time.Now()) 1503 } else { 1504 peer.log.Debug("Stalling delivery, dropping", "type", kind) 1505 1506 if d.dropPeer == nil { 1507 // The dropPeer method is nil when `--copydb` is used for a local copy. 1508 // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored 1509 peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", pid) 1510 } else { 1511 d.dropPeer(pid) 1512 1513 // If this peer was the master peer, abort sync immediately 1514 d.cancelLock.RLock() 1515 master := pid == d.cancelPeer 1516 d.cancelLock.RUnlock() 1517 1518 if master { 1519 d.cancel() 1520 return errTimeout 1521 } 1522 } 1523 } 1524 } 1525 } 1526 // If there's nothing more to fetch, wait or terminate 1527 if pending() == 0 { 1528 if !inFlight() && finished { 1529 log.Debug("Data fetching completed", "type", kind) 1530 return nil 1531 } 1532 break 1533 } 1534 // Send a download request to all idle peers, until throttled 1535 progressed, throttled, running := false, false, inFlight() 1536 idles, total := idle() 1537 pendCount := pending() 1538 for _, peer := range idles { 1539 // Short circuit if throttling activated 1540 if throttled { 1541 break 1542 } 1543 // Short circuit if there is no more available task. 1544 if pendCount = pending(); pendCount == 0 { 1545 break 1546 } 1547 // Reserve a chunk of fetches for a peer. A nil can mean either that 1548 // no more headers are available, or that the peer is known not to 1549 // have them. 1550 request, progress, throttle := reserve(peer, capacity(peer)) 1551 if progress { 1552 progressed = true 1553 } 1554 if throttle { 1555 throttled = true 1556 throttleCounter.Inc(1) 1557 } 1558 if request == nil { 1559 continue 1560 } 1561 if request.From > 0 { 1562 peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From) 1563 } else { 1564 peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number) 1565 } 1566 // Fetch the chunk and make sure any errors return the hashes to the queue 1567 if fetchHook != nil { 1568 fetchHook(request.Headers) 1569 } 1570 if err := fetch(peer, request); err != nil { 1571 // Although we could try and make an attempt to fix this, this error really 1572 // means that we've double allocated a fetch task to a peer. If that is the 1573 // case, the internal state of the downloader and the queue is very wrong so 1574 // better hard crash and note the error instead of silently accumulating into 1575 // a much bigger issue. 1576 panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind)) 1577 } 1578 running = true 1579 } 1580 // Make sure that we have peers available for fetching. If all peers have been tried 1581 // and all failed throw an error 1582 if !progressed && !throttled && !running && len(idles) == total && pendCount > 0 { 1583 return errPeersUnavailable 1584 } 1585 } 1586 } 1587 } 1588 1589 // processHeaders takes batches of retrieved headers from an input channel and 1590 // keeps processing and scheduling them into the header chain and downloader's 1591 // queue until the stream ends or a failure occurs. 1592 func (d *Downloader) processHeaders(origin uint64, td *big.Int) error { 1593 // Keep a count of uncertain headers to roll back 1594 var ( 1595 rollback uint64 // Zero means no rollback (fine as you can't unroll the genesis) 1596 rollbackErr error 1597 mode = d.getMode() 1598 ) 1599 defer func() { 1600 if rollback > 0 { 1601 lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0 1602 if mode != LightSync { 1603 lastFastBlock = d.blockchain.CurrentFastBlock().Number() 1604 lastBlock = d.blockchain.CurrentBlock().Number() 1605 } 1606 if err := d.lightchain.SetHead(rollback - 1); err != nil { // -1 to target the parent of the first uncertain block 1607 // We're already unwinding the stack, only print the error to make it more visible 1608 log.Error("Failed to roll back chain segment", "head", rollback-1, "err", err) 1609 } 1610 curFastBlock, curBlock := common.Big0, common.Big0 1611 if mode != LightSync { 1612 curFastBlock = d.blockchain.CurrentFastBlock().Number() 1613 curBlock = d.blockchain.CurrentBlock().Number() 1614 } 1615 log.Warn("Rolled back chain segment", 1616 "header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number), 1617 "fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock), 1618 "block", fmt.Sprintf("%d->%d", lastBlock, curBlock), "reason", rollbackErr) 1619 } 1620 }() 1621 // Wait for batches of headers to process 1622 gotHeaders := false 1623 1624 for { 1625 select { 1626 case <-d.cancelCh: 1627 rollbackErr = errCanceled 1628 return errCanceled 1629 1630 case headers := <-d.headerProcCh: 1631 // Terminate header processing if we synced up 1632 if len(headers) == 0 { 1633 // Notify everyone that headers are fully processed 1634 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 1635 select { 1636 case ch <- false: 1637 case <-d.cancelCh: 1638 } 1639 } 1640 // If no headers were retrieved at all, the peer violated its TD promise that it had a 1641 // better chain compared to ours. The only exception is if its promised blocks were 1642 // already imported by other means (e.g. fetcher): 1643 // 1644 // R <remote peer>, L <local node>: Both at block 10 1645 // R: Mine block 11, and propagate it to L 1646 // L: Queue block 11 for import 1647 // L: Notice that R's head and TD increased compared to ours, start sync 1648 // L: Import of block 11 finishes 1649 // L: Sync begins, and finds common ancestor at 11 1650 // L: Request new headers up from 11 (R's TD was higher, it must have something) 1651 // R: Nothing to give 1652 if mode != LightSync { 1653 head := d.blockchain.CurrentBlock() 1654 if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 { 1655 return errStallingPeer 1656 } 1657 } 1658 // If fast or light syncing, ensure promised headers are indeed delivered. This is 1659 // needed to detect scenarios where an attacker feeds a bad pivot and then bails out 1660 // of delivering the post-pivot blocks that would flag the invalid content. 1661 // 1662 // This check cannot be executed "as is" for full imports, since blocks may still be 1663 // queued for processing when the header download completes. However, as long as the 1664 // peer gave us something useful, we're already happy/progressed (above check). 1665 if mode == FastSync || mode == LightSync { 1666 head := d.lightchain.CurrentHeader() 1667 if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 { 1668 return errStallingPeer 1669 } 1670 } 1671 // Disable any rollback and return 1672 rollback = 0 1673 return nil 1674 } 1675 // Otherwise split the chunk of headers into batches and process them 1676 gotHeaders = true 1677 for len(headers) > 0 { 1678 // Terminate if something failed in between processing chunks 1679 select { 1680 case <-d.cancelCh: 1681 rollbackErr = errCanceled 1682 return errCanceled 1683 default: 1684 } 1685 // Select the next chunk of headers to import 1686 limit := maxHeadersProcess 1687 if limit > len(headers) { 1688 limit = len(headers) 1689 } 1690 chunk := headers[:limit] 1691 1692 // In case of header only syncing, validate the chunk immediately 1693 if mode == FastSync || mode == LightSync { 1694 // If we're importing pure headers, verify based on their recentness 1695 var pivot uint64 1696 1697 d.pivotLock.RLock() 1698 if d.pivotHeader != nil { 1699 pivot = d.pivotHeader.Number.Uint64() 1700 } 1701 d.pivotLock.RUnlock() 1702 1703 frequency := fsHeaderCheckFrequency 1704 if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot { 1705 frequency = 1 1706 } 1707 if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil { 1708 rollbackErr = err 1709 1710 // If some headers were inserted, track them as uncertain 1711 if (mode == FastSync || frequency > 1) && n > 0 && rollback == 0 { 1712 rollback = chunk[0].Number.Uint64() 1713 } 1714 log.Warn("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "parent", chunk[n].ParentHash, "err", err) 1715 return fmt.Errorf("%w: %v", errInvalidChain, err) 1716 } 1717 // All verifications passed, track all headers within the alloted limits 1718 if mode == FastSync { 1719 head := chunk[len(chunk)-1].Number.Uint64() 1720 if head-rollback > uint64(fsHeaderSafetyNet) { 1721 rollback = head - uint64(fsHeaderSafetyNet) 1722 } else { 1723 rollback = 1 1724 } 1725 } 1726 } 1727 // Unless we're doing light chains, schedule the headers for associated content retrieval 1728 if mode == FullSync || mode == FastSync { 1729 // If we've reached the allowed number of pending headers, stall a bit 1730 for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders { 1731 select { 1732 case <-d.cancelCh: 1733 rollbackErr = errCanceled 1734 return errCanceled 1735 case <-time.After(time.Second): 1736 } 1737 } 1738 // Otherwise insert the headers for content retrieval 1739 inserts := d.queue.Schedule(chunk, origin) 1740 if len(inserts) != len(chunk) { 1741 rollbackErr = fmt.Errorf("stale headers: len inserts %v len(chunk) %v", len(inserts), len(chunk)) 1742 return fmt.Errorf("%w: stale headers", errBadPeer) 1743 } 1744 } 1745 headers = headers[limit:] 1746 origin += uint64(limit) 1747 } 1748 // Update the highest block number we know if a higher one is found. 1749 d.syncStatsLock.Lock() 1750 if d.syncStatsChainHeight < origin { 1751 d.syncStatsChainHeight = origin - 1 1752 } 1753 d.syncStatsLock.Unlock() 1754 1755 // Signal the content downloaders of the availablility of new tasks 1756 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 1757 select { 1758 case ch <- true: 1759 default: 1760 } 1761 } 1762 } 1763 } 1764 } 1765 1766 // processFullSyncContent takes fetch results from the queue and imports them into the chain. 1767 func (d *Downloader) processFullSyncContent() error { 1768 for { 1769 results := d.queue.Results(true) 1770 if len(results) == 0 { 1771 return nil 1772 } 1773 stop := make(chan struct{}) 1774 if d.chainInsertHook != nil { 1775 d.chainInsertHook(results, stop) 1776 } 1777 if err := d.importBlockResults(results); err != nil { 1778 close(stop) 1779 return err 1780 } 1781 close(stop) 1782 } 1783 } 1784 1785 func (d *Downloader) importBlockResults(results []*fetchResult) error { 1786 // Check for any early termination requests 1787 if len(results) == 0 { 1788 return nil 1789 } 1790 select { 1791 case <-d.quitCh: 1792 return errCancelContentProcessing 1793 default: 1794 } 1795 // Retrieve the a batch of results to import 1796 first, last := results[0].Header, results[len(results)-1].Header 1797 log.Debug("Inserting downloaded chain", "items", len(results), 1798 "firstnum", first.Number, "firsthash", first.Hash(), 1799 "lastnum", last.Number, "lasthash", last.Hash(), 1800 ) 1801 blocks := make([]*types.Block, len(results)) 1802 for i, result := range results { 1803 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1804 } 1805 if index, err := d.blockchain.InsertChain(blocks); err != nil { 1806 if index < len(results) { 1807 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1808 } else { 1809 // The InsertChain method in blockchain.go will sometimes return an out-of-bounds index, 1810 // when it needs to preprocess blocks to import a sidechain. 1811 // The importer will put together a new list of blocks to import, which is a superset 1812 // of the blocks delivered from the downloader, and the indexing will be off. 1813 log.Debug("Downloaded item processing failed on sidechain import", "index", index, "err", err) 1814 } 1815 return fmt.Errorf("%w: %v", errInvalidChain, err) 1816 } 1817 return nil 1818 } 1819 1820 // processFastSyncContent takes fetch results from the queue and writes them to the 1821 // database. It also controls the synchronisation of state nodes of the pivot block. 1822 func (d *Downloader) processFastSyncContent() error { 1823 // Start syncing state of the reported head block. This should get us most of 1824 // the state of the pivot block. 1825 d.pivotLock.RLock() 1826 sync := d.syncState(d.pivotHeader.Root) 1827 d.pivotLock.RUnlock() 1828 1829 defer func() { 1830 // The `sync` object is replaced every time the pivot moves. We need to 1831 // defer close the very last active one, hence the lazy evaluation vs. 1832 // calling defer sync.Cancel() !!! 1833 sync.Cancel() 1834 }() 1835 1836 closeOnErr := func(s *stateSync) { 1837 if err := s.Wait(); err != nil && err != errCancelStateFetch && err != errCanceled && err != snap.ErrCancelled { 1838 d.queue.Close() // wake up Results 1839 } 1840 } 1841 go closeOnErr(sync) 1842 1843 // To cater for moving pivot points, track the pivot block and subsequently 1844 // accumulated download results separately. 1845 var ( 1846 oldPivot *fetchResult // Locked in pivot block, might change eventually 1847 oldTail []*fetchResult // Downloaded content after the pivot 1848 ) 1849 for { 1850 // Wait for the next batch of downloaded data to be available, and if the pivot 1851 // block became stale, move the goalpost 1852 results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness 1853 if len(results) == 0 { 1854 // If pivot sync is done, stop 1855 if oldPivot == nil { 1856 return sync.Cancel() 1857 } 1858 // If sync failed, stop 1859 select { 1860 case <-d.cancelCh: 1861 sync.Cancel() 1862 return errCanceled 1863 default: 1864 } 1865 } 1866 if d.chainInsertHook != nil { 1867 d.chainInsertHook(results, nil) 1868 } 1869 // If we haven't downloaded the pivot block yet, check pivot staleness 1870 // notifications from the header downloader 1871 d.pivotLock.RLock() 1872 pivot := d.pivotHeader 1873 d.pivotLock.RUnlock() 1874 1875 if oldPivot == nil { 1876 if pivot.Root != sync.root { 1877 sync.Cancel() 1878 sync = d.syncState(pivot.Root) 1879 1880 go closeOnErr(sync) 1881 } 1882 } else { 1883 results = append(append([]*fetchResult{oldPivot}, oldTail...), results...) 1884 } 1885 // Split around the pivot block and process the two sides via fast/full sync 1886 if atomic.LoadInt32(&d.committed) == 0 { 1887 latest := results[len(results)-1].Header 1888 // If the height is above the pivot block by 2 sets, it means the pivot 1889 // become stale in the network and it was garbage collected, move to a 1890 // new pivot. 1891 // 1892 // Note, we have `reorgProtHeaderDelay` number of blocks withheld, Those 1893 // need to be taken into account, otherwise we're detecting the pivot move 1894 // late and will drop peers due to unavailable state!!! 1895 if height := latest.Number.Uint64(); height >= pivot.Number.Uint64()+2*uint64(fsMinFullBlocks)-uint64(reorgProtHeaderDelay) { 1896 log.Warn("Pivot became stale, moving", "old", pivot.Number.Uint64(), "new", height-uint64(fsMinFullBlocks)+uint64(reorgProtHeaderDelay)) 1897 pivot = results[len(results)-1-fsMinFullBlocks+reorgProtHeaderDelay].Header // must exist as lower old pivot is uncommitted 1898 1899 d.pivotLock.Lock() 1900 d.pivotHeader = pivot 1901 d.pivotLock.Unlock() 1902 1903 // Write out the pivot into the database so a rollback beyond it will 1904 // reenable fast sync 1905 rawdb.WriteLastPivotNumber(d.stateDB, pivot.Number.Uint64()) 1906 } 1907 } 1908 P, beforeP, afterP := splitAroundPivot(pivot.Number.Uint64(), results) 1909 if err := d.commitFastSyncData(beforeP, sync); err != nil { 1910 return err 1911 } 1912 if P != nil { 1913 // If new pivot block found, cancel old state retrieval and restart 1914 if oldPivot != P { 1915 sync.Cancel() 1916 sync = d.syncState(P.Header.Root) 1917 1918 go closeOnErr(sync) 1919 oldPivot = P 1920 } 1921 // Wait for completion, occasionally checking for pivot staleness 1922 select { 1923 case <-sync.done: 1924 if sync.err != nil { 1925 return sync.err 1926 } 1927 if err := d.commitPivotBlock(P); err != nil { 1928 return err 1929 } 1930 oldPivot = nil 1931 1932 case <-time.After(time.Second): 1933 oldTail = afterP 1934 continue 1935 } 1936 } 1937 // Fast sync done, pivot commit done, full import 1938 if err := d.importBlockResults(afterP); err != nil { 1939 return err 1940 } 1941 } 1942 } 1943 1944 func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) { 1945 if len(results) == 0 { 1946 return nil, nil, nil 1947 } 1948 if lastNum := results[len(results)-1].Header.Number.Uint64(); lastNum < pivot { 1949 // the pivot is somewhere in the future 1950 return nil, results, nil 1951 } 1952 // This can also be optimized, but only happens very seldom 1953 for _, result := range results { 1954 num := result.Header.Number.Uint64() 1955 switch { 1956 case num < pivot: 1957 before = append(before, result) 1958 case num == pivot: 1959 p = result 1960 default: 1961 after = append(after, result) 1962 } 1963 } 1964 return p, before, after 1965 } 1966 1967 func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error { 1968 // Check for any early termination requests 1969 if len(results) == 0 { 1970 return nil 1971 } 1972 select { 1973 case <-d.quitCh: 1974 return errCancelContentProcessing 1975 case <-stateSync.done: 1976 if err := stateSync.Wait(); err != nil { 1977 return err 1978 } 1979 default: 1980 } 1981 // Retrieve the a batch of results to import 1982 first, last := results[0].Header, results[len(results)-1].Header 1983 log.Debug("Inserting fast-sync blocks", "items", len(results), 1984 "firstnum", first.Number, "firsthash", first.Hash(), 1985 "lastnumn", last.Number, "lasthash", last.Hash(), 1986 ) 1987 blocks := make([]*types.Block, len(results)) 1988 receipts := make([]types.Receipts, len(results)) 1989 for i, result := range results { 1990 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1991 receipts[i] = result.Receipts 1992 } 1993 if index, err := d.blockchain.InsertReceiptChain(blocks, receipts, d.ancientLimit); err != nil { 1994 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1995 return fmt.Errorf("%w: %v", errInvalidChain, err) 1996 } 1997 return nil 1998 } 1999 2000 func (d *Downloader) commitPivotBlock(result *fetchResult) error { 2001 block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 2002 log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash()) 2003 2004 // Commit the pivot block as the new head, will require full sync from here on 2005 if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}, d.ancientLimit); err != nil { 2006 return err 2007 } 2008 if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil { 2009 return err 2010 } 2011 atomic.StoreInt32(&d.committed, 1) 2012 2013 // If we had a bloom filter for the state sync, deallocate it now. Note, we only 2014 // deallocate internally, but keep the empty wrapper. This ensures that if we do 2015 // a rollback after committing the pivot and restarting fast sync, we don't end 2016 // up using a nil bloom. Empty bloom is fine, it just returns that it does not 2017 // have the info we need, so reach down to the database instead. 2018 if d.stateBloom != nil { 2019 d.stateBloom.Close() 2020 } 2021 return nil 2022 } 2023 2024 // DeliverHeaders injects a new batch of block headers received from a remote 2025 // node into the download schedule. 2026 func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) error { 2027 return d.deliver(d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter) 2028 } 2029 2030 // DeliverBodies injects a new batch of block bodies received from a remote node. 2031 func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) error { 2032 return d.deliver(d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter) 2033 } 2034 2035 // DeliverReceipts injects a new batch of receipts received from a remote node. 2036 func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) error { 2037 return d.deliver(d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter) 2038 } 2039 2040 // DeliverNodeData injects a new batch of node state data received from a remote node. 2041 func (d *Downloader) DeliverNodeData(id string, data [][]byte) error { 2042 return d.deliver(d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter) 2043 } 2044 2045 // DeliverSnapPacket is invoked from a peer's message handler when it transmits a 2046 // data packet for the local node to consume. 2047 func (d *Downloader) DeliverSnapPacket(peer *snap.Peer, packet snap.Packet) error { 2048 switch packet := packet.(type) { 2049 case *snap.AccountRangePacket: 2050 hashes, accounts, err := packet.Unpack() 2051 if err != nil { 2052 return err 2053 } 2054 return d.SnapSyncer.OnAccounts(peer, packet.ID, hashes, accounts, packet.Proof) 2055 2056 case *snap.StorageRangesPacket: 2057 hashset, slotset := packet.Unpack() 2058 return d.SnapSyncer.OnStorage(peer, packet.ID, hashset, slotset, packet.Proof) 2059 2060 case *snap.ByteCodesPacket: 2061 return d.SnapSyncer.OnByteCodes(peer, packet.ID, packet.Codes) 2062 2063 case *snap.TrieNodesPacket: 2064 return d.SnapSyncer.OnTrieNodes(peer, packet.ID, packet.Nodes) 2065 2066 default: 2067 return fmt.Errorf("unexpected snap packet type: %T", packet) 2068 } 2069 } 2070 2071 // deliver injects a new batch of data received from a remote node. 2072 func (d *Downloader) deliver(destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) { 2073 // Update the delivery metrics for both good and failed deliveries 2074 inMeter.Mark(int64(packet.Items())) 2075 defer func() { 2076 if err != nil { 2077 dropMeter.Mark(int64(packet.Items())) 2078 } 2079 }() 2080 // Deliver or abort if the sync is canceled while queuing 2081 d.cancelLock.RLock() 2082 cancel := d.cancelCh 2083 d.cancelLock.RUnlock() 2084 if cancel == nil { 2085 return errNoSyncActive 2086 } 2087 select { 2088 case destCh <- packet: 2089 return nil 2090 case <-cancel: 2091 return errNoSyncActive 2092 } 2093 } 2094 2095 // qosTuner is the quality of service tuning loop that occasionally gathers the 2096 // peer latency statistics and updates the estimated request round trip time. 2097 func (d *Downloader) qosTuner() { 2098 for { 2099 // Retrieve the current median RTT and integrate into the previoust target RTT 2100 rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT())) 2101 atomic.StoreUint64(&d.rttEstimate, uint64(rtt)) 2102 2103 // A new RTT cycle passed, increase our confidence in the estimated RTT 2104 conf := atomic.LoadUint64(&d.rttConfidence) 2105 conf = conf + (1000000-conf)/2 2106 atomic.StoreUint64(&d.rttConfidence, conf) 2107 2108 // Log the new QoS values and sleep until the next RTT 2109 log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL()) 2110 select { 2111 case <-d.quitCh: 2112 return 2113 case <-time.After(rtt): 2114 } 2115 } 2116 } 2117 2118 // qosReduceConfidence is meant to be called when a new peer joins the downloader's 2119 // peer set, needing to reduce the confidence we have in out QoS estimates. 2120 func (d *Downloader) qosReduceConfidence() { 2121 // If we have a single peer, confidence is always 1 2122 peers := uint64(d.peers.Len()) 2123 if peers == 0 { 2124 // Ensure peer connectivity races don't catch us off guard 2125 return 2126 } 2127 if peers == 1 { 2128 atomic.StoreUint64(&d.rttConfidence, 1000000) 2129 return 2130 } 2131 // If we have a ton of peers, don't drop confidence) 2132 if peers >= uint64(qosConfidenceCap) { 2133 return 2134 } 2135 // Otherwise drop the confidence factor 2136 conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers 2137 if float64(conf)/1000000 < rttMinConfidence { 2138 conf = uint64(rttMinConfidence * 1000000) 2139 } 2140 atomic.StoreUint64(&d.rttConfidence, conf) 2141 2142 rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate)) 2143 log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL()) 2144 } 2145 2146 // requestRTT returns the current target round trip time for a download request 2147 // to complete in. 2148 // 2149 // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that 2150 // the downloader tries to adapt queries to the RTT, so multiple RTT values can 2151 // be adapted to, but smaller ones are preferred (stabler download stream). 2152 func (d *Downloader) requestRTT() time.Duration { 2153 return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10 2154 } 2155 2156 // requestTTL returns the current timeout allowance for a single download request 2157 // to finish under. 2158 func (d *Downloader) requestTTL() time.Duration { 2159 var ( 2160 rtt = time.Duration(atomic.LoadUint64(&d.rttEstimate)) 2161 conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0 2162 ) 2163 ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf) 2164 if ttl > ttlLimit { 2165 ttl = ttlLimit 2166 } 2167 return ttl 2168 }