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