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