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