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