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