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