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