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