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