github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/qct/downloader/downloader.go (about) 1 // Package downloader contains the manual full chain synchronisation. 2 package downloader 3 4 import ( 5 "errors" 6 "fmt" 7 "math/big" 8 "sync" 9 "sync/atomic" 10 "time" 11 12 quickchain "github.com/quickchainproject/quickchain" 13 "github.com/quickchainproject/quickchain/common" 14 "github.com/quickchainproject/quickchain/core" 15 "github.com/quickchainproject/quickchain/core/types" 16 "github.com/quickchainproject/quickchain/event" 17 "github.com/quickchainproject/quickchain/qctdb" 18 "github.com/quickchainproject/quickchain/log" 19 "github.com/quickchainproject/quickchain/metrics" 20 "github.com/quickchainproject/quickchain/params" 21 ) 22 23 var ( 24 MaxHashFetch = 512 // Amount of hashes to be fetched per retrieval request 25 MaxBlockFetch = 128 // Amount of blocks to be fetched per retrieval request 26 MaxHeaderFetch = 192 // Amount of block headers to be fetched per retrieval request 27 MaxSkeletonSize = 128 // Number of header fetches to need for a skeleton assembly 28 MaxBodyFetch = 128 // Amount of block bodies to be fetched per retrieval request 29 MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request 30 MaxStateFetch = 384 // Amount of node state values to allow fetching per request 31 32 MaxForkAncestry = 3 * params.EpochDuration // Maximum chain reorganisation 33 rttMinEstimate = 2 * time.Second // Minimum round-trip time to target for download requests 34 rttMaxEstimate = 20 * time.Second // Maximum round-trip time to target for download requests 35 rttMinConfidence = 0.1 // Worse confidence factor in our estimated RTT value 36 ttlScaling = 3 // Constant scaling factor for RTT -> TTL conversion 37 ttlLimit = time.Minute // Maximum TTL allowance to prevent reaching crazy timeouts 38 39 qosTuningPeers = 5 // Number of peers to tune based on (best peers) 40 qosConfidenceCap = 10 // Number of peers above which not to modify RTT confidence 41 qosTuningImpact = 0.25 // Impact that a new tuning target has on the previous value 42 43 maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection) 44 maxHeadersProcess = 2048 // Number of header download results to import at once into the chain 45 maxResultsProcess = 2048 // Number of content download results to import at once into the chain 46 47 fsHeaderCheckFrequency = 100 // Verification frequency of the downloaded headers during fast sync 48 fsHeaderSafetyNet = 2048 // Number of headers to discard in case a chain violation is detected 49 fsHeaderForceVerify = 24 // Number of headers to verify before and after the pivot to accept it 50 fsHeaderContCheck = 3 * time.Second // Time interval to check for header continuations during state download 51 fsMinFullBlocks = 64 // Number of blocks to retrieve fully even in fast sync 52 ) 53 54 var ( 55 errBusy = errors.New("busy") 56 errUnknownPeer = errors.New("peer is unknown or unhealthy") 57 errBadPeer = errors.New("action from bad peer ignored") 58 errStallingPeer = errors.New("peer is stalling") 59 errNoPeers = errors.New("no peers to keep download active") 60 errTimeout = errors.New("timeout") 61 errEmptyHeaderSet = errors.New("empty header set by peer") 62 errPeersUnavailable = errors.New("no peers available or all tried for download") 63 errInvalidAncestor = errors.New("retrieved ancestor is invalid") 64 errInvalidChain = errors.New("retrieved hash chain is invalid") 65 errInvalidBlock = errors.New("retrieved block is invalid") 66 errInvalidBody = errors.New("retrieved block body is invalid") 67 errInvalidReceipt = errors.New("retrieved receipt is invalid") 68 errCancelBlockFetch = errors.New("block download canceled (requested)") 69 errCancelHeaderFetch = errors.New("block header download canceled (requested)") 70 errCancelBodyFetch = errors.New("block body download canceled (requested)") 71 errCancelReceiptFetch = errors.New("receipt download canceled (requested)") 72 errCancelStateFetch = errors.New("state data download canceled (requested)") 73 errCancelHeaderProcessing = errors.New("header processing canceled (requested)") 74 errCancelContentProcessing = errors.New("content processing canceled (requested)") 75 errNoSyncActive = errors.New("no sync active") 76 errTooOld = errors.New("peer doesn't speak recent enough protocol version (need version >= 62)") 77 ) 78 79 type Downloader struct { 80 mode SyncMode // Synchronisation mode defining the strategy used (per sync cycle) 81 mux *event.TypeMux // Event multiplexer to announce sync operation events 82 83 queue *queue // Scheduler for selecting the hashes to download 84 peers *peerSet // Set of active peers from which download can proceed 85 stateDB qctdb.Database 86 87 rttEstimate uint64 // Round trip time to target for download requests 88 rttConfidence uint64 // Confidence in the estimated RTT (unit: millionths to allow atomic ops) 89 90 // Statistics 91 syncStatsChainOrigin uint64 // Origin block number where syncing started at 92 syncStatsChainHeight uint64 // Highest block number known when syncing started 93 syncStatsState stateSyncStats 94 syncStatsLock sync.RWMutex // Lock protecting the sync stats fields 95 96 lightchain LightChain 97 blockchain BlockChain 98 99 // Callbacks 100 dropPeer peerDropFn // Drops a peer for misbehaving 101 102 // Status 103 synchroniseMock func(id string, hash common.Hash) error // Replacement for synchronise during testing 104 synchronising int32 105 notified int32 106 committed int32 107 108 // Channels 109 headerCh chan dataPack // [eth/62] Channel receiving inbound block headers 110 bodyCh chan dataPack // [eth/62] Channel receiving inbound block bodies 111 receiptCh chan dataPack // [eth/63] Channel receiving inbound receipts 112 bodyWakeCh chan bool // [eth/62] Channel to signal the block body fetcher of new tasks 113 receiptWakeCh chan bool // [eth/63] Channel to signal the receipt fetcher of new tasks 114 headerProcCh chan []*types.Header // [eth/62] Channel to feed the header processor new tasks 115 116 // for stateFetcher 117 stateSyncStart chan *stateSync 118 trackStateReq chan *stateReq 119 stateCh chan dataPack // [eth/63] Channel receiving inbound node state data 120 121 // Cancellation and termination 122 cancelPeer string // Identifier of the peer currently being used as the master (cancel on drop) 123 cancelCh chan struct{} // Channel to cancel mid-flight syncs 124 cancelLock sync.RWMutex // Lock to protect the cancel channel and peer in delivers 125 cancelWg sync.WaitGroup // Make sure all fetcher goroutines have exited. 126 127 quitCh chan struct{} // Quit channel to signal termination 128 quitLock sync.RWMutex // Lock to prevent double closes 129 130 // Testing hooks 131 syncInitHook func(uint64, uint64) // Method to call upon initiating a new sync run 132 bodyFetchHook func([]*types.Header) // Method to call upon starting a block body fetch 133 receiptFetchHook func([]*types.Header) // Method to call upon starting a receipt fetch 134 chainInsertHook func([]*fetchResult) // Method to call upon inserting a chain of blocks (possibly in multiple invocations) 135 } 136 137 // LightChain encapsulates functions required to synchronise a light chain. 138 type LightChain interface { 139 // HasHeader verifies a header's presence in the local chain. 140 HasHeader(common.Hash, uint64) bool 141 142 // GetHeaderByHash retrieves a header from the local chain. 143 GetHeaderByHash(common.Hash) *types.Header 144 145 // CurrentHeader retrieves the head header from the local chain. 146 CurrentHeader() *types.Header 147 148 // GetTd returns the total difficulty of a local block. 149 GetTd(common.Hash, uint64) *big.Int 150 151 // InsertHeaderChain inserts a batch of headers into the local chain. 152 InsertHeaderChain([]*types.Header, int) (int, error) 153 154 // Rollback removes a few recently added elements from the local chain. 155 Rollback([]common.Hash) 156 } 157 158 // BlockChain encapsulates functions required to sync a (full or fast) blockchain. 159 type BlockChain interface { 160 LightChain 161 162 // HasBlock verifies a block's presence in the local chain. 163 HasBlock(common.Hash, uint64) bool 164 165 // GetBlockByHash retrieves a block from the local chain. 166 GetBlockByHash(common.Hash) *types.Block 167 168 // CurrentBlock retrieves the head block from the local chain. 169 CurrentBlock() *types.Block 170 171 // CurrentFastBlock retrieves the head fast block from the local chain. 172 CurrentFastBlock() *types.Block 173 174 // FastSyncCommitHead directly commits the head block to a certain entity. 175 FastSyncCommitHead(common.Hash) error 176 177 // InsertChain inserts a batch of blocks into the local chain. 178 InsertChain(types.Blocks) (int, error) 179 180 // InsertReceiptChain inserts a batch of receipts into the local chain. 181 InsertReceiptChain(types.Blocks, []types.Receipts) (int, error) 182 } 183 184 // New creates a new downloader to fetch hashes and blocks from remote peers. 185 func New(mode SyncMode, stateDb qctdb.Database, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn) *Downloader { 186 if lightchain == nil { 187 lightchain = chain 188 } 189 190 dl := &Downloader{ 191 mode: mode, 192 stateDB: stateDb, 193 mux: mux, 194 queue: newQueue(), 195 peers: newPeerSet(), 196 rttEstimate: uint64(rttMaxEstimate), 197 rttConfidence: uint64(1000000), 198 blockchain: chain, 199 lightchain: lightchain, 200 dropPeer: dropPeer, 201 headerCh: make(chan dataPack, 1), 202 bodyCh: make(chan dataPack, 1), 203 receiptCh: make(chan dataPack, 1), 204 bodyWakeCh: make(chan bool, 1), 205 receiptWakeCh: make(chan bool, 1), 206 headerProcCh: make(chan []*types.Header, 1), 207 quitCh: make(chan struct{}), 208 stateCh: make(chan dataPack), 209 stateSyncStart: make(chan *stateSync), 210 syncStatsState: stateSyncStats{ 211 processed: core.GetTrieSyncProgress(stateDb), 212 }, 213 trackStateReq: make(chan *stateReq), 214 } 215 go dl.qosTuner() 216 go dl.stateFetcher() 217 return dl 218 } 219 220 // Progress retrieves the synchronisation boundaries, specifically the origin 221 // block where synchronisation started at (may have failed/suspended); the block 222 // or header sync is currently at; and the latest known block which the sync targets. 223 // 224 // In addition, during the state download phase of fast synchronisation the number 225 // of processed and the total number of known states are also returned. Otherwise 226 // these are zero. 227 func (d *Downloader) Progress() quickchain.SyncProgress { 228 // Lock the current stats and return the progress 229 d.syncStatsLock.RLock() 230 defer d.syncStatsLock.RUnlock() 231 232 current := uint64(0) 233 switch d.mode { 234 case FullSync: 235 current = d.blockchain.CurrentBlock().NumberU64() 236 case FastSync: 237 current = d.blockchain.CurrentFastBlock().NumberU64() 238 case LightSync: 239 current = d.lightchain.CurrentHeader().Number.Uint64() 240 } 241 return quickchain.SyncProgress{ 242 StartingBlock: d.syncStatsChainOrigin, 243 CurrentBlock: current, 244 HighestBlock: d.syncStatsChainHeight, 245 PulledStates: d.syncStatsState.processed, 246 KnownStates: d.syncStatsState.processed + d.syncStatsState.pending, 247 } 248 } 249 250 // Synchronising returns whether the downloader is currently retrieving blocks. 251 func (d *Downloader) Synchronising() bool { 252 return atomic.LoadInt32(&d.synchronising) > 0 253 } 254 255 // RegisterPeer injects a new download peer into the set of block source to be 256 // used for fetching hashes and blocks from. 257 func (d *Downloader) RegisterPeer(id string, version int, peer Peer) error { 258 logger := log.New("peer", id) 259 logger.Trace("Registering sync peer") 260 if err := d.peers.Register(newPeerConnection(id, version, peer, logger)); err != nil { 261 logger.Error("Failed to register sync peer", "err", err) 262 return err 263 } 264 d.qosReduceConfidence() 265 266 return nil 267 } 268 269 // RegisterLightPeer injects a light client peer, wrapping it so it appears as a regular peer. 270 func (d *Downloader) RegisterLightPeer(id string, version int, peer LightPeer) error { 271 return d.RegisterPeer(id, version, &lightPeerWrapper{peer}) 272 } 273 274 // UnregisterPeer remove a peer from the known list, preventing any action from 275 // the specified peer. An effort is also made to return any pending fetches into 276 // the queue. 277 func (d *Downloader) UnregisterPeer(id string) error { 278 // Unregister the peer from the active peer set and revoke any fetch tasks 279 logger := log.New("peer", id) 280 logger.Trace("Unregistering sync peer") 281 if err := d.peers.Unregister(id); err != nil { 282 logger.Error("Failed to unregister sync peer", "err", err) 283 return err 284 } 285 d.queue.Revoke(id) 286 287 // If this peer was the master peer, abort sync immediately 288 d.cancelLock.RLock() 289 master := id == d.cancelPeer 290 d.cancelLock.RUnlock() 291 292 if master { 293 d.cancel() 294 } 295 return nil 296 } 297 298 // Synchronise tries to sync up our local block chain with a remote peer, both 299 // adding various sanity checks as well as wrapping it with various log entries. 300 func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error { 301 err := d.synchronise(id, head, td, mode) 302 switch err { 303 case nil: 304 case errBusy: 305 306 case errTimeout, errBadPeer, errStallingPeer, 307 errEmptyHeaderSet, errPeersUnavailable, errTooOld, 308 errInvalidAncestor, errInvalidChain: 309 log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err) 310 if d.dropPeer == nil { 311 // The dropPeer method is nil when `--copydb` is used for a local copy. 312 // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored 313 log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id) 314 } else { 315 d.dropPeer(id) 316 } 317 default: 318 log.Warn("Synchronisation failed, retrying", "err", err) 319 } 320 return err 321 } 322 323 // synchronise will select the peer and use it for synchronising. If an empty string is given 324 // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the 325 // checks fail an error will be returned. This method is synchronous 326 func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error { 327 // Mock out the synchronisation if testing 328 if d.synchroniseMock != nil { 329 return d.synchroniseMock(id, hash) 330 } 331 // Make sure only one goroutine is ever allowed past this point at once 332 if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) { 333 return errBusy 334 } 335 defer atomic.StoreInt32(&d.synchronising, 0) 336 337 // Post a user notification of the sync (only once per session) 338 if atomic.CompareAndSwapInt32(&d.notified, 0, 1) { 339 log.Info("Block synchronisation started") 340 } 341 // Reset the queue, peer set and wake channels to clean any internal leftover state 342 d.queue.Reset() 343 d.peers.Reset() 344 345 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 346 select { 347 case <-ch: 348 default: 349 } 350 } 351 for _, ch := range []chan dataPack{d.headerCh, d.bodyCh, d.receiptCh} { 352 for empty := false; !empty; { 353 select { 354 case <-ch: 355 default: 356 empty = true 357 } 358 } 359 } 360 for empty := false; !empty; { 361 select { 362 case <-d.headerProcCh: 363 default: 364 empty = true 365 } 366 } 367 // Create cancel channel for aborting mid-flight and mark the master peer 368 d.cancelLock.Lock() 369 d.cancelCh = make(chan struct{}) 370 d.cancelPeer = id 371 d.cancelLock.Unlock() 372 373 defer d.Cancel() // No matter what, we can't leave the cancel channel open 374 375 // Set the requested sync mode, unless it's forbidden 376 d.mode = mode 377 378 // Retrieve the origin peer and initiate the downloading process 379 p := d.peers.Peer(id) 380 if p == nil { 381 return errUnknownPeer 382 } 383 return d.syncWithPeer(p, hash, td) 384 } 385 386 // syncWithPeer starts a block synchronization based on the hash chain from the 387 // specified peer and head hash. 388 func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.Int) (err error) { 389 d.mux.Post(StartEvent{}) 390 defer func() { 391 // reset on error 392 if err != nil { 393 d.mux.Post(FailedEvent{err}) 394 } else { 395 d.mux.Post(DoneEvent{}) 396 } 397 }() 398 if p.version < 62 { 399 return errTooOld 400 } 401 402 log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", d.mode) 403 defer func(start time.Time) { 404 log.Debug("Synchronisation terminated", "elapsed", time.Since(start)) 405 }(time.Now()) 406 407 // Look up the sync boundaries: the common ancestor and the target block 408 latest, err := d.fetchHeight(p) 409 if err != nil { 410 return err 411 } 412 height := latest.Number.Uint64() 413 414 origin, err := d.findAncestor(p, height) 415 if err != nil { 416 return err 417 } 418 d.syncStatsLock.Lock() 419 if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin { 420 d.syncStatsChainOrigin = origin 421 } 422 d.syncStatsChainHeight = height 423 d.syncStatsLock.Unlock() 424 425 // Ensure our origin point is below any fast sync pivot point 426 pivot := uint64(0) 427 if d.mode == FastSync { 428 if height <= uint64(fsMinFullBlocks) { 429 origin = 0 430 } else { 431 pivot = height - uint64(fsMinFullBlocks) 432 if pivot <= origin { 433 origin = pivot - 1 434 } 435 } 436 } 437 d.committed = 1 438 if d.mode == FastSync && pivot != 0 { 439 d.committed = 0 440 } 441 // Initiate the sync using a concurrent header and content retrieval algorithm 442 d.queue.Prepare(origin+1, d.mode) 443 if d.syncInitHook != nil { 444 d.syncInitHook(origin, height) 445 } 446 447 fetchers := []func() error{ 448 func() error { return d.fetchHeaders(p, origin+1, pivot) }, // Headers are always retrieved 449 func() error { return d.fetchBodies(origin + 1) }, // Bodies are retrieved during normal and fast sync 450 func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync 451 func() error { return d.processHeaders(origin+1, pivot, td) }, 452 } 453 if d.mode == FastSync { 454 fetchers = append(fetchers, func() error { return d.processFastSyncContent(latest) }) 455 } else if d.mode == FullSync { 456 fetchers = append(fetchers, d.processFullSyncContent) 457 } 458 return d.spawnSync(fetchers) 459 } 460 461 // spawnSync runs d.process and all given fetcher functions to completion in 462 // separate goroutines, returning the first error that appears. 463 func (d *Downloader) spawnSync(fetchers []func() error) error { 464 errc := make(chan error, len(fetchers)) 465 d.cancelWg.Add(len(fetchers)) 466 for _, fn := range fetchers { 467 fn := fn 468 go func() { defer d.cancelWg.Done(); errc <- fn() }() 469 } 470 // Wait for the first error, then terminate the others. 471 var err error 472 for i := 0; i < len(fetchers); i++ { 473 if i == len(fetchers)-1 { 474 // Close the queue when all fetchers have exited. 475 // This will cause the block processor to end when 476 // it has processed the queue. 477 d.queue.Close() 478 } 479 if err = <-errc; err != nil { 480 break 481 } 482 } 483 d.queue.Close() 484 d.Cancel() 485 return err 486 } 487 488 // cancel aborts all of the operations and resets the queue. However, cancel does 489 // not wait for the running download goroutines to finish. This method should be 490 // used when cancelling the downloads from inside the downloader. 491 func (d *Downloader) cancel() { 492 // Close the current cancel channel 493 d.cancelLock.Lock() 494 if d.cancelCh != nil { 495 select { 496 case <-d.cancelCh: 497 // Channel was already closed 498 default: 499 close(d.cancelCh) 500 } 501 } 502 d.cancelLock.Unlock() 503 } 504 505 // Cancel aborts all of the operations and waits for all download goroutines to 506 // finish before returning. 507 func (d *Downloader) Cancel() { 508 d.cancel() 509 d.cancelWg.Wait() 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 returns 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 1291 // Update the highest block number we know if a higher one is found. 1292 d.syncStatsLock.Lock() 1293 if d.syncStatsChainHeight < origin { 1294 d.syncStatsChainHeight = origin - 1 1295 } 1296 d.syncStatsLock.Unlock() 1297 1298 // Signal the content downloaders of the availablility of new tasks 1299 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 1300 select { 1301 case ch <- true: 1302 default: 1303 } 1304 } 1305 } 1306 } 1307 } 1308 1309 // processFullSyncContent takes fetch results from the queue and imports them into the chain. 1310 func (d *Downloader) processFullSyncContent() error { 1311 for { 1312 results := d.queue.Results(true) 1313 if len(results) == 0 { 1314 return nil 1315 } 1316 if d.chainInsertHook != nil { 1317 d.chainInsertHook(results) 1318 } 1319 if err := d.importBlockResults(results); err != nil { 1320 return err 1321 } 1322 } 1323 } 1324 1325 func (d *Downloader) importBlockResults(results []*fetchResult) error { 1326 // Check for any early termination requests 1327 if len(results) == 0 { 1328 return nil 1329 } 1330 select { 1331 case <-d.quitCh: 1332 return errCancelContentProcessing 1333 default: 1334 } 1335 // Retrieve the a batch of results to import 1336 first, last := results[0].Header, results[len(results)-1].Header 1337 log.Debug("Inserting downloaded chain", "items", len(results), 1338 "firstnum", first.Number, "firsthash", first.Hash(), 1339 "lastnum", last.Number, "lasthash", last.Hash(), 1340 ) 1341 blocks := make([]*types.Block, len(results)) 1342 for i, result := range results { 1343 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1344 } 1345 if index, err := d.blockchain.InsertChain(blocks); err != nil { 1346 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1347 return errInvalidChain 1348 } 1349 return nil 1350 } 1351 1352 // processFastSyncContent takes fetch results from the queue and writes them to the 1353 // database. It also controls the synchronisation of state nodes of the pivot block. 1354 func (d *Downloader) processFastSyncContent(latest *types.Header) error { 1355 // Start syncing state of the reported head block. This should get us most of 1356 // the state of the pivot block. 1357 stateSync := d.syncState(latest.Root) 1358 defer stateSync.Cancel() 1359 go func() { 1360 if err := stateSync.Wait(); err != nil && err != errCancelStateFetch { 1361 d.queue.Close() // wake up WaitResults 1362 } 1363 }() 1364 // Figure out the ideal pivot block. Note, that this goalpost may move if the 1365 // sync takes long enough for the chain head to move significantly. 1366 pivot := uint64(0) 1367 if height := latest.Number.Uint64(); height > uint64(fsMinFullBlocks) { 1368 pivot = height - uint64(fsMinFullBlocks) 1369 } 1370 // To cater for moving pivot points, track the pivot block and subsequently 1371 // accumulated download results separately. 1372 var ( 1373 oldPivot *fetchResult // Locked in pivot block, might change eventually 1374 oldTail []*fetchResult // Downloaded content after the pivot 1375 ) 1376 for { 1377 // Wait for the next batch of downloaded data to be available, and if the pivot 1378 // block became stale, move the goalpost 1379 results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness 1380 if len(results) == 0 { 1381 // If pivot sync is done, stop 1382 if oldPivot == nil { 1383 return stateSync.Cancel() 1384 } 1385 // If sync failed, stop 1386 select { 1387 case <-d.cancelCh: 1388 return stateSync.Cancel() 1389 default: 1390 } 1391 } 1392 if d.chainInsertHook != nil { 1393 d.chainInsertHook(results) 1394 } 1395 if oldPivot != nil { 1396 results = append(append([]*fetchResult{oldPivot}, oldTail...), results...) 1397 } 1398 // Split around the pivot block and process the two sides via fast/full sync 1399 if atomic.LoadInt32(&d.committed) == 0 { 1400 latest = results[len(results)-1].Header 1401 if height := latest.Number.Uint64(); height > pivot+2*uint64(fsMinFullBlocks) { 1402 log.Warn("Pivot became stale, moving", "old", pivot, "new", height-uint64(fsMinFullBlocks)) 1403 pivot = height - uint64(fsMinFullBlocks) 1404 } 1405 } 1406 P, beforeP, afterP := splitAroundPivot(pivot, results) 1407 if err := d.commitFastSyncData(beforeP, stateSync); err != nil { 1408 return err 1409 } 1410 if P != nil { 1411 // If new pivot block found, cancel old state retrieval and restart 1412 if oldPivot != P { 1413 stateSync.Cancel() 1414 1415 stateSync = d.syncState(P.Header.Root) 1416 defer stateSync.Cancel() 1417 go func() { 1418 if err := stateSync.Wait(); err != nil && err != errCancelStateFetch { 1419 d.queue.Close() // wake up WaitResults 1420 } 1421 }() 1422 oldPivot = P 1423 } 1424 // Wait for completion, occasionally checking for pivot staleness 1425 select { 1426 case <-stateSync.done: 1427 if stateSync.err != nil { 1428 return stateSync.err 1429 } 1430 if err := d.commitPivotBlock(P); err != nil { 1431 return err 1432 } 1433 oldPivot = nil 1434 1435 case <-time.After(time.Second): 1436 oldTail = afterP 1437 continue 1438 } 1439 } 1440 // Fast sync done, pivot commit done, full import 1441 if err := d.importBlockResults(afterP); err != nil { 1442 return err 1443 } 1444 } 1445 } 1446 1447 func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) { 1448 for _, result := range results { 1449 num := result.Header.Number.Uint64() 1450 switch { 1451 case num < pivot: 1452 before = append(before, result) 1453 case num == pivot: 1454 p = result 1455 default: 1456 after = append(after, result) 1457 } 1458 } 1459 return p, before, after 1460 } 1461 1462 func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error { 1463 // Check for any early termination requests 1464 if len(results) == 0 { 1465 return nil 1466 } 1467 select { 1468 case <-d.quitCh: 1469 return errCancelContentProcessing 1470 case <-stateSync.done: 1471 if err := stateSync.Wait(); err != nil { 1472 return err 1473 } 1474 default: 1475 } 1476 // Retrieve the a batch of results to import 1477 first, last := results[0].Header, results[len(results)-1].Header 1478 log.Debug("Inserting fast-sync blocks", "items", len(results), 1479 "firstnum", first.Number, "firsthash", first.Hash(), 1480 "lastnumn", last.Number, "lasthash", last.Hash(), 1481 ) 1482 blocks := make([]*types.Block, len(results)) 1483 receipts := make([]types.Receipts, len(results)) 1484 for i, result := range results { 1485 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1486 receipts[i] = result.Receipts 1487 } 1488 if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil { 1489 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1490 return errInvalidChain 1491 } 1492 return nil 1493 } 1494 1495 func (d *Downloader) commitPivotBlock(result *fetchResult) error { 1496 block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1497 log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash()) 1498 1499 if err := d.syncDposContextState(block.Header().DposContext); err != nil { 1500 return err 1501 } 1502 1503 if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}); err != nil { 1504 return err 1505 } 1506 if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil { 1507 return err 1508 } 1509 atomic.StoreInt32(&d.committed, 1) 1510 return nil 1511 } 1512 1513 // Todo: sync dpos context in concurrent 1514 func (d *Downloader) syncDposContextState(context *types.DposContextProto) error { 1515 roots := []common.Hash{ 1516 context.CandidateHash, 1517 context.DelegateHash, 1518 context.VoteHash, 1519 context.EpochHash, 1520 context.MintCntHash, 1521 } 1522 for _, root := range roots { 1523 if err := d.syncState(root).Wait(); err != nil { 1524 return err 1525 } 1526 } 1527 return nil 1528 } 1529 1530 // DeliverHeaders injects a new batch of block headers received from a remote 1531 // node into the download schedule. 1532 func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) { 1533 return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter) 1534 } 1535 1536 // DeliverBodies injects a new batch of block bodies received from a remote node. 1537 func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) { 1538 return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter) 1539 } 1540 1541 // DeliverReceipts injects a new batch of receipts received from a remote node. 1542 func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) { 1543 return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter) 1544 } 1545 1546 // DeliverNodeData injects a new batch of node state data received from a remote node. 1547 func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) { 1548 return d.deliver(id, d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter) 1549 } 1550 1551 // deliver injects a new batch of data received from a remote node. 1552 func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) { 1553 // Update the delivery metrics for both good and failed deliveries 1554 inMeter.Mark(int64(packet.Items())) 1555 defer func() { 1556 if err != nil { 1557 dropMeter.Mark(int64(packet.Items())) 1558 } 1559 }() 1560 // Deliver or abort if the sync is canceled while queuing 1561 d.cancelLock.RLock() 1562 cancel := d.cancelCh 1563 d.cancelLock.RUnlock() 1564 if cancel == nil { 1565 return errNoSyncActive 1566 } 1567 select { 1568 case destCh <- packet: 1569 return nil 1570 case <-cancel: 1571 return errNoSyncActive 1572 } 1573 } 1574 1575 // qosTuner is the quality of service tuning loop that occasionally gathers the 1576 // peer latency statistics and updates the estimated request round trip time. 1577 func (d *Downloader) qosTuner() { 1578 for { 1579 // Retrieve the current median RTT and integrate into the previoust target RTT 1580 rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT())) 1581 atomic.StoreUint64(&d.rttEstimate, uint64(rtt)) 1582 1583 // A new RTT cycle passed, increase our confidence in the estimated RTT 1584 conf := atomic.LoadUint64(&d.rttConfidence) 1585 conf = conf + (1000000-conf)/2 1586 atomic.StoreUint64(&d.rttConfidence, conf) 1587 1588 // Log the new QoS values and sleep until the next RTT 1589 log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL()) 1590 select { 1591 case <-d.quitCh: 1592 return 1593 case <-time.After(rtt): 1594 } 1595 } 1596 } 1597 1598 // qosReduceConfidence is meant to be called when a new peer joins the downloader's 1599 // peer set, needing to reduce the confidence we have in out QoS estimates. 1600 func (d *Downloader) qosReduceConfidence() { 1601 // If we have a single peer, confidence is always 1 1602 peers := uint64(d.peers.Len()) 1603 if peers == 0 { 1604 // Ensure peer connectivity races don't catch us off guard 1605 return 1606 } 1607 if peers == 1 { 1608 atomic.StoreUint64(&d.rttConfidence, 1000000) 1609 return 1610 } 1611 // If we have a ton of peers, don't drop confidence) 1612 if peers >= uint64(qosConfidenceCap) { 1613 return 1614 } 1615 // Otherwise drop the confidence factor 1616 conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers 1617 if float64(conf)/1000000 < rttMinConfidence { 1618 conf = uint64(rttMinConfidence * 1000000) 1619 } 1620 atomic.StoreUint64(&d.rttConfidence, conf) 1621 1622 rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate)) 1623 log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL()) 1624 } 1625 1626 // requestRTT returns the current target round trip time for a download request 1627 // to complete in. 1628 // 1629 // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that 1630 // the downloader tries to adapt queries to the RTT, so multiple RTT values can 1631 // be adapted to, but smaller ones are preferred (stabler download stream). 1632 func (d *Downloader) requestRTT() time.Duration { 1633 return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10 1634 } 1635 1636 // requestTTL returns the current timeout allowance for a single download request 1637 // to finish under. 1638 func (d *Downloader) requestTTL() time.Duration { 1639 var ( 1640 rtt = time.Duration(atomic.LoadUint64(&d.rttEstimate)) 1641 conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0 1642 ) 1643 ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf) 1644 if ttl > ttlLimit { 1645 ttl = ttlLimit 1646 } 1647 return ttl 1648 }