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