github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/eth/downloader/downloader.go (about) 1 // Copyright 2015 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum 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 "github.com/SmartMeshFoundation/Spectrum" 31 "github.com/SmartMeshFoundation/Spectrum/common" 32 "github.com/SmartMeshFoundation/Spectrum/core/types" 33 "github.com/SmartMeshFoundation/Spectrum/ethdb" 34 "github.com/SmartMeshFoundation/Spectrum/event" 35 "github.com/SmartMeshFoundation/Spectrum/log" 36 "github.com/SmartMeshFoundation/Spectrum/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 ethdb.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.Header, int) (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 ethdb.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() ethereum.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 ethereum.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 its 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("Block synchronisation started") 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 fmt.Println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") 433 fmt.Println("@ORIGIN: origin=", origin, "height=", height, "peerid=", p.id) 434 d.syncStatsLock.Lock() 435 if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin { 436 d.syncStatsChainOrigin = origin 437 } 438 d.syncStatsChainHeight = height 439 d.syncStatsLock.Unlock() 440 fmt.Println("@ORIGIN: d.syncStatsChainHeight=", d.syncStatsChainHeight, "current=", d.blockchain.CurrentHeader().Number.Int64()) 441 fmt.Println("@ORIGIN: Latest.Root =", latest.Root.Hex()) 442 fmt.Println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") 443 // Initiate the sync using a concurrent header and content retrieval algorithm 444 pivot := uint64(0) 445 switch d.mode { 446 case LightSync: 447 pivot = height 448 case FastSync: 449 // Calculate the new fast/slow sync pivot point 450 if d.fsPivotLock == nil { 451 pivotOffset, err := rand.Int(rand.Reader, big.NewInt(int64(fsPivotInterval))) 452 if err != nil { 453 panic(fmt.Sprintf("Failed to access crypto random source: %v", err)) 454 } 455 if height > uint64(fsMinFullBlocks)+pivotOffset.Uint64() { 456 pivot = height - uint64(fsMinFullBlocks) - pivotOffset.Uint64() 457 } 458 } else { 459 // Pivot point locked in, use this and do not pick a new one! 460 pivot = d.fsPivotLock.Number.Uint64() 461 } 462 // If the point is below the origin, move origin back to ensure state download 463 if pivot < origin { 464 if pivot > 0 { 465 origin = pivot - 1 466 } else { 467 origin = 0 468 } 469 } 470 log.Debug("Fast syncing until pivot block", "pivot", pivot) 471 } 472 d.queue.Prepare(origin+1, d.mode, pivot, latest) 473 if d.syncInitHook != nil { 474 d.syncInitHook(origin, height) 475 } 476 477 fetchers := []func() error{ 478 func() error { 479 e := d.fetchHeaders(p, origin+1) 480 return e 481 }, // Headers are always retrieved 482 func() error { 483 e := d.fetchBodies(origin + 1) 484 return e 485 }, // Bodies are retrieved during normal and fast sync 486 func() error { 487 e := d.fetchReceipts(origin + 1) 488 return e 489 }, // Receipts are retrieved during fast sync 490 func() error { 491 e := d.processHeaders(origin+1, td) 492 return e 493 }, 494 } 495 if d.mode == FastSync { 496 fmt.Println("FastSync️") 497 fetchers = append(fetchers, func() error { 498 e := d.processFastSyncContent(latest) 499 return e 500 }) 501 } else if d.mode == FullSync { 502 fmt.Println("FullSync") 503 fetchers = append(fetchers, d.processFullSyncContent) 504 } 505 err = d.spawnSync(fetchers) 506 if err != nil && d.mode == FastSync && d.fsPivotLock != nil { 507 // If sync failed in the critical section, bump the fail counter. 508 atomic.AddUint32(&d.fsPivotFails, 1) 509 } 510 //fmt.Println("downloader.syncWithPeer:", err, hash.Hex()) 511 return err 512 } 513 514 // spawnSync runs d.process and all given fetcher functions to completion in 515 // separate goroutines, returning the first error that appears. 516 func (d *Downloader) spawnSync(fetchers []func() error) error { 517 var wg sync.WaitGroup 518 errc := make(chan error, len(fetchers)) 519 wg.Add(len(fetchers)) 520 for _, fn := range fetchers { 521 fn := fn 522 go func() { defer wg.Done(); errc <- fn() }() 523 } 524 // Wait for the first error, then terminate the others. 525 var err error 526 for i := 0; i < len(fetchers); i++ { 527 if i == len(fetchers)-1 { 528 // Close the queue when all fetchers have exited. 529 // This will cause the block processor to end when 530 // it has processed the queue. 531 d.queue.Close() 532 } 533 if err = <-errc; err != nil { 534 break 535 } 536 } 537 d.queue.Close() 538 d.Cancel() 539 wg.Wait() 540 return err 541 } 542 543 // Cancel cancels all of the operations and resets the queue. It returns true 544 // if the cancel operation was completed. 545 func (d *Downloader) Cancel() { 546 // Close the current cancel channel 547 d.cancelLock.Lock() 548 if d.cancelCh != nil { 549 select { 550 case <-d.cancelCh: 551 // Channel was already closed 552 default: 553 close(d.cancelCh) 554 } 555 } 556 d.cancelLock.Unlock() 557 } 558 559 // Terminate interrupts the downloader, canceling all pending operations. 560 // The downloader cannot be reused after calling Terminate. 561 func (d *Downloader) Terminate() { 562 // Close the termination channel (make sure double close is allowed) 563 d.quitLock.Lock() 564 select { 565 case <-d.quitCh: 566 default: 567 close(d.quitCh) 568 } 569 d.quitLock.Unlock() 570 571 // Cancel any pending download requests 572 d.Cancel() 573 } 574 575 // fetchHeight retrieves the head header of the remote peer to aid in estimating 576 // the total time a pending synchronisation would take. 577 func (d *Downloader) fetchHeight(p *peerConnection) (*types.Header, error) { 578 p.log.Debug("Retrieving remote chain height") 579 580 // Request the advertised remote head block and wait for the response 581 head, _ := p.peer.Head() 582 go p.peer.RequestHeadersByHash(head, 1, 0, false) 583 584 ttl := d.requestTTL() 585 timeout := time.After(ttl) 586 for { 587 select { 588 case <-d.cancelCh: 589 return nil, errCancelBlockFetch 590 591 case packet := <-d.headerCh: 592 // Discard anything not from the origin peer 593 if packet.PeerId() != p.id { 594 log.Debug("Received headers from incorrect peer", "peer", packet.PeerId()) 595 break 596 } 597 // Make sure the peer actually gave something valid 598 headers := packet.(*headerPack).headers 599 if len(headers) != 1 { 600 p.log.Debug("Multiple headers for single request", "headers", len(headers)) 601 return nil, errBadPeer 602 } 603 head := headers[0] 604 p.log.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash()) 605 return head, nil 606 607 case <-timeout: 608 p.log.Debug("Waiting for head header timed out", "elapsed", ttl) 609 return nil, errTimeout 610 611 case <-d.bodyCh: 612 case <-d.receiptCh: 613 // Out of bounds delivery, ignore 614 } 615 } 616 } 617 618 // findAncestor tries to locate the common ancestor link of the local chain and 619 // a remote peers blockchain. In the general case when our node was in sync and 620 // on the correct chain, checking the top N links should already get us a match. 621 // In the rare scenario when we ended up on a long reorganisation (i.e. none of 622 // the head links match), we do a binary search to find the common ancestor. 623 func (d *Downloader) findAncestor(p *peerConnection, height uint64) (uint64, error) { 624 // Figure out the valid ancestor range to prevent rewrite attacks 625 floor, ceil := int64(-1), d.lightchain.CurrentHeader().Number.Uint64() 626 627 p.log.Debug("Looking for common ancestor", "local", ceil, "remote", height) 628 if d.mode == FullSync { 629 ceil = d.blockchain.CurrentBlock().NumberU64() 630 } else if d.mode == FastSync { 631 ceil = d.blockchain.CurrentFastBlock().NumberU64() 632 } 633 if ceil >= MaxForkAncestry { 634 floor = int64(ceil - MaxForkAncestry) 635 } 636 log.Debug(fmt.Sprintf("[ downloader ] ==> findAncestor() ceil=%d, maxforkancestry=%d, floor=%d ", ceil, MaxForkAncestry, floor)) 637 // Request the topmost blocks to short circuit binary ancestor lookup 638 head := ceil 639 if head > height { 640 head = height 641 } 642 from := int64(head) - int64(MaxHeaderFetch) 643 if from < 0 { 644 from = 0 645 } 646 // Span out with 15 block gaps into the future to catch bad head reports 647 limit := 2 * MaxHeaderFetch / 16 648 count := 1 + int((int64(ceil)-from)/16) 649 if count > limit { 650 count = limit 651 } 652 go p.peer.RequestHeadersByNumber(uint64(from), count, 15, false) 653 654 // Wait for the remote response to the head fetch 655 number, hash := uint64(0), common.Hash{} 656 657 ttl := d.requestTTL() 658 timeout := time.After(ttl) 659 660 for finished := false; !finished; { 661 select { 662 case <-d.cancelCh: 663 return 0, errCancelHeaderFetch 664 665 case packet := <-d.headerCh: 666 // Discard anything not from the origin peer 667 if packet.PeerId() != p.id { 668 log.Debug("Received headers from incorrect peer", "peer", packet.PeerId()) 669 break 670 } 671 // Make sure the peer actually gave something valid 672 headers := packet.(*headerPack).headers 673 if len(headers) == 0 { 674 p.log.Warn("Empty head header set") 675 return 0, errEmptyHeaderSet 676 } 677 // Make sure the peer's reply conforms to the request 678 for i := 0; i < len(headers); i++ { 679 if number := headers[i].Number.Int64(); number != from+int64(i)*16 { 680 p.log.Warn("Head headers broke chain ordering", "index", i, "requested", from+int64(i)*16, "received", number) 681 return 0, errInvalidChain 682 } 683 } 684 // Check if a common ancestor was found 685 finished = true 686 for i := len(headers) - 1; i >= 0; i-- { 687 // Skip any headers that underflow/overflow our requested set 688 if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > ceil { 689 continue 690 } 691 // Otherwise check if we already know the header or not 692 if (d.mode == FullSync && d.blockchain.HasBlockAndState(headers[i].Hash())) || (d.mode != FullSync && d.lightchain.HasHeader(headers[i].Hash(), headers[i].Number.Uint64())) { 693 number, hash = headers[i].Number.Uint64(), headers[i].Hash() 694 695 // If every header is known, even future ones, the peer straight out lied about its head 696 if number > height && i == limit-1 { 697 p.log.Warn("Lied about chain head", "reported", height, "found", number) 698 return 0, errStallingPeer 699 } 700 break 701 } 702 } 703 704 case <-timeout: 705 p.log.Debug("Waiting for head header timed out", "elapsed", ttl) 706 return 0, errTimeout 707 708 case <-d.bodyCh: 709 case <-d.receiptCh: 710 // Out of bounds delivery, ignore 711 } 712 } 713 // If the head fetch already found an ancestor, return 714 if !common.EmptyHash(hash) { 715 if int64(number) <= floor { 716 p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor) 717 return 0, errInvalidAncestor 718 } 719 p.log.Debug("Found common ancestor", "number", number, "hash", hash) 720 return number, nil 721 } 722 // Ancestor not found, we need to binary search over our chain 723 start, end := uint64(0), head 724 if floor > 0 { 725 start = uint64(floor) 726 } 727 for start+1 < end { 728 log.Info(fmt.Sprintf("[ downloader ] ==> findAncestor() %d --> %d ", start, end)) 729 // Split our chain interval in two, and request the hash to cross check 730 check := (start + end) / 2 731 732 ttl := d.requestTTL() 733 timeout := time.After(ttl) 734 735 go p.peer.RequestHeadersByNumber(check, 1, 0, false) 736 737 // Wait until a reply arrives to this request 738 for arrived := false; !arrived; { 739 select { 740 case <-d.cancelCh: 741 return 0, errCancelHeaderFetch 742 743 case packer := <-d.headerCh: 744 // Discard anything not from the origin peer 745 if packer.PeerId() != p.id { 746 log.Debug("Received headers from incorrect peer", "peer", packer.PeerId()) 747 break 748 } 749 // Make sure the peer actually gave something valid 750 headers := packer.(*headerPack).headers 751 if len(headers) != 1 { 752 p.log.Debug("Multiple headers for single request", "headers", len(headers)) 753 return 0, errBadPeer 754 } 755 arrived = true 756 757 // Modify the search interval based on the response 758 if (d.mode == FullSync && !d.blockchain.HasBlockAndState(headers[0].Hash())) || 759 (d.mode != FullSync && !d.lightchain.HasHeader(headers[0].Hash(), headers[0].Number.Uint64())) { 760 end = check 761 log.Debug(fmt.Sprintf("[ downloader ] ==> findAncestor() matched block found, floor = %v , set start = %v , end = %v", floor, start, end)) 762 break 763 } 764 header := d.lightchain.GetHeaderByHash(headers[0].Hash()) // Independent of sync mode, header surely exists 765 if header.Number.Uint64() != check { 766 p.log.Debug("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check) 767 return 0, errBadPeer 768 } 769 770 start = check 771 log.Info(fmt.Sprintf("[ downloader ] ==> findAncestor() matched block not found, set end = %v", end)) 772 773 case <-timeout: 774 p.log.Debug("Waiting for search header timed out", "elapsed", ttl) 775 return 0, errTimeout 776 777 case <-d.bodyCh: 778 case <-d.receiptCh: 779 // Out of bounds delivery, ignore 780 } 781 } 782 } 783 // Ensure valid ancestry and return 784 if int64(start) <= floor { 785 p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor) 786 return 0, errInvalidAncestor 787 } 788 p.log.Debug("Found common ancestor", "number", start, "hash", hash) 789 return start, nil 790 } 791 792 // fetchHeaders keeps retrieving headers concurrently from the number 793 // requested, until no more are returned, potentially throttling on the way. To 794 // facilitate concurrency but still protect against malicious nodes sending bad 795 // headers, we construct a header chain skeleton using the "origin" peer we are 796 // syncing with, and fill in the missing headers using anyone else. Headers from 797 // other peers are only accepted if they map cleanly to the skeleton. If no one 798 // can fill in the skeleton - not even the origin peer - it's assumed invalid and 799 // the origin is dropped. 800 func (d *Downloader) fetchHeaders(p *peerConnection, from uint64) error { 801 p.log.Debug("Directing header downloads", "origin", from) 802 defer p.log.Debug("Header download terminated") 803 804 // Create a timeout timer, and the associated header fetcher 805 skeleton := true // Skeleton assembly phase or finishing up 806 request := time.Now() // time of the last skeleton fetch request 807 timeout := time.NewTimer(0) // timer to dump a non-responsive active peer 808 <-timeout.C // timeout channel should be initially empty 809 defer timeout.Stop() 810 811 var ttl time.Duration 812 getHeaders := func(from uint64) { 813 request = time.Now() 814 815 ttl = d.requestTTL() 816 timeout.Reset(ttl) 817 818 if skeleton { 819 p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from) 820 go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false) 821 } else { 822 p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from) 823 go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false) 824 } 825 } 826 // Start pulling the header chain skeleton until all is done 827 getHeaders(from) 828 829 for { 830 select { 831 case <-d.cancelCh: 832 return errCancelHeaderFetch 833 834 case packet := <-d.headerCh: 835 // Make sure the active peer is giving us the skeleton headers 836 if packet.PeerId() != p.id { 837 log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId()) 838 break 839 } 840 headerReqTimer.UpdateSince(request) 841 timeout.Stop() 842 843 // If the skeleton's finished, pull any remaining head headers directly from the origin 844 if packet.Items() == 0 && skeleton { 845 skeleton = false 846 getHeaders(from) 847 continue 848 } 849 // If no more headers are inbound, notify the content fetchers and return 850 if packet.Items() == 0 { 851 p.log.Debug("No more headers available") 852 select { 853 case d.headerProcCh <- nil: 854 return nil 855 case <-d.cancelCh: 856 return errCancelHeaderFetch 857 } 858 } 859 headers := packet.(*headerPack).headers 860 861 // If we received a skeleton batch, resolve internals concurrently 862 if skeleton { 863 filled, proced, err := d.fillHeaderSkeleton(from, headers) 864 if err != nil { 865 p.log.Debug("Skeleton chain invalid", "err", err) 866 return errInvalidChain 867 } 868 headers = filled[proced:] 869 from += uint64(proced) 870 } 871 // Insert all the new headers and fetch the next batch 872 if len(headers) > 0 { 873 p.log.Trace("Scheduling new headers", "count", len(headers), "from", from) 874 select { 875 case d.headerProcCh <- headers: 876 case <-d.cancelCh: 877 return errCancelHeaderFetch 878 } 879 from += uint64(len(headers)) 880 } 881 getHeaders(from) 882 883 case <-timeout.C: 884 // Header retrieval timed out, consider the peer bad and drop 885 p.log.Debug("Header request timed out", "elapsed", ttl) 886 headerTimeoutMeter.Mark(1) 887 d.dropPeer(p.id) 888 889 // Finish the sync gracefully instead of dumping the gathered data though 890 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 891 select { 892 case ch <- false: 893 case <-d.cancelCh: 894 } 895 } 896 select { 897 case d.headerProcCh <- nil: 898 case <-d.cancelCh: 899 } 900 return errBadPeer 901 } 902 } 903 } 904 905 // fillHeaderSkeleton concurrently retrieves headers from all our available peers 906 // and maps them to the provided skeleton header chain. 907 // 908 // Any partial results from the beginning of the skeleton is (if possible) forwarded 909 // immediately to the header processor to keep the rest of the pipeline full even 910 // in the case of header stalls. 911 // 912 // The method returs the entire filled skeleton and also the number of headers 913 // already forwarded for processing. 914 func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) { 915 log.Debug("Filling up skeleton", "from", from) 916 d.queue.ScheduleSkeleton(from, skeleton) 917 918 var ( 919 deliver = func(packet dataPack) (int, error) { 920 pack := packet.(*headerPack) 921 return d.queue.DeliverHeaders(pack.peerId, pack.headers, d.headerProcCh) 922 } 923 expire = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) } 924 throttle = func() bool { return false } 925 reserve = func(p *peerConnection, count int) (*fetchRequest, bool, error) { 926 return d.queue.ReserveHeaders(p, count), false, nil 927 } 928 fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) } 929 capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) } 930 setIdle = func(p *peerConnection, accepted int) { p.SetHeadersIdle(accepted) } 931 ) 932 err := d.fetchParts(errCancelHeaderFetch, d.headerCh, deliver, d.queue.headerContCh, expire, 933 d.queue.PendingHeaders, d.queue.InFlightHeaders, throttle, reserve, 934 nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers") 935 936 log.Debug("Skeleton fill terminated", "err", err) 937 938 filled, proced := d.queue.RetrieveHeaders() 939 return filled, proced, err 940 } 941 942 // fetchBodies iteratively downloads the scheduled block bodies, taking any 943 // available peers, reserving a chunk of blocks for each, waiting for delivery 944 // and also periodically checking for timeouts. 945 func (d *Downloader) fetchBodies(from uint64) error { 946 log.Debug("Downloading block bodies", "origin", from) 947 948 var ( 949 deliver = func(packet dataPack) (int, error) { 950 pack := packet.(*bodyPack) 951 return d.queue.DeliverBodies(pack.peerId, pack.transactions, pack.uncles) 952 } 953 expire = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) } 954 fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) } 955 capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) } 956 setIdle = func(p *peerConnection, accepted int) { p.SetBodiesIdle(accepted) } 957 ) 958 err := d.fetchParts(errCancelBodyFetch, d.bodyCh, deliver, d.bodyWakeCh, expire, 959 d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ShouldThrottleBlocks, d.queue.ReserveBodies, 960 d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies") 961 962 log.Debug("Block body download terminated", "err", err) 963 return err 964 } 965 966 // fetchReceipts iteratively downloads the scheduled block receipts, taking any 967 // available peers, reserving a chunk of receipts for each, waiting for delivery 968 // and also periodically checking for timeouts. 969 func (d *Downloader) fetchReceipts(from uint64) error { 970 log.Debug("Downloading transaction receipts", "origin", from) 971 972 var ( 973 deliver = func(packet dataPack) (int, error) { 974 pack := packet.(*receiptPack) 975 return d.queue.DeliverReceipts(pack.peerId, pack.receipts) 976 } 977 expire = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) } 978 fetch = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) } 979 capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) } 980 setIdle = func(p *peerConnection, accepted int) { p.SetReceiptsIdle(accepted) } 981 ) 982 err := d.fetchParts(errCancelReceiptFetch, d.receiptCh, deliver, d.receiptWakeCh, expire, 983 d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ShouldThrottleReceipts, d.queue.ReserveReceipts, 984 d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts") 985 986 log.Debug("Transaction receipt download terminated", "err", err) 987 return err 988 } 989 990 // fetchParts iteratively downloads scheduled block parts, taking any available 991 // peers, reserving a chunk of fetch requests for each, waiting for delivery and 992 // also periodically checking for timeouts. 993 // 994 // As the scheduling/timeout logic mostly is the same for all downloaded data 995 // types, this method is used by each for data gathering and is instrumented with 996 // various callbacks to handle the slight differences between processing them. 997 // 998 // The instrumentation parameters: 999 // - errCancel: error type to return if the fetch operation is cancelled (mostly makes logging nicer) 1000 // - deliveryCh: channel from which to retrieve downloaded data packets (merged from all concurrent peers) 1001 // - deliver: processing callback to deliver data packets into type specific download queues (usually within `queue`) 1002 // - wakeCh: notification channel for waking the fetcher when new tasks are available (or sync completed) 1003 // - expire: task callback method to abort requests that took too long and return the faulty peers (traffic shaping) 1004 // - pending: task callback for the number of requests still needing download (detect completion/non-completability) 1005 // - inFlight: task callback for the number of in-progress requests (wait for all active downloads to finish) 1006 // - throttle: task callback to check if the processing queue is full and activate throttling (bound memory use) 1007 // - reserve: task callback to reserve new download tasks to a particular peer (also signals partial completions) 1008 // - fetchHook: tester callback to notify of new tasks being initiated (allows testing the scheduling logic) 1009 // - fetch: network callback to actually send a particular download request to a physical remote peer 1010 // - cancel: task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer) 1011 // - capacity: network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping) 1012 // - idle: network callback to retrieve the currently (type specific) idle peers that can be assigned tasks 1013 // - setIdle: network callback to set a peer back to idle and update its estimated capacity (traffic shaping) 1014 // - kind: textual label of the type being downloaded to display in log mesages 1015 func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool, 1016 expire func() map[string]int, pending func() int, inFlight func() bool, throttle func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, error), 1017 fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int, 1018 idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int), kind string) error { 1019 1020 // Create a ticker to detect expired retrieval tasks 1021 ticker := time.NewTicker(100 * time.Millisecond) 1022 defer ticker.Stop() 1023 1024 update := make(chan struct{}, 1) 1025 1026 // Prepare the queue and fetch block parts until the block header fetcher's done 1027 finished := false 1028 for { 1029 select { 1030 case <-d.cancelCh: 1031 return errCancel 1032 1033 case packet := <-deliveryCh: 1034 // If the peer was previously banned and failed to deliver its pack 1035 // in a reasonable time frame, ignore its message. 1036 if peer := d.peers.Peer(packet.PeerId()); peer != nil { 1037 // Deliver the received chunk of data and check chain validity 1038 accepted, err := deliver(packet) 1039 if err == errInvalidChain { 1040 return err 1041 } 1042 // Unless a peer delivered something completely else than requested (usually 1043 // caused by a timed out request which came through in the end), set it to 1044 // idle. If the delivery's stale, the peer should have already been idled. 1045 if err != errStaleDelivery { 1046 setIdle(peer, accepted) 1047 } 1048 // Issue a log to the user to see what's going on 1049 switch { 1050 case err == nil && packet.Items() == 0: 1051 peer.log.Trace("Requested data not delivered", "type", kind) 1052 case err == nil: 1053 peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats()) 1054 default: 1055 peer.log.Trace("Failed to deliver retrieved data", "type", kind, "err", err) 1056 } 1057 } 1058 // Blocks assembled, try to update the progress 1059 select { 1060 case update <- struct{}{}: 1061 default: 1062 } 1063 1064 case cont := <-wakeCh: 1065 // The header fetcher sent a continuation flag, check if it's done 1066 if !cont { 1067 finished = true 1068 } 1069 // Headers arrive, try to update the progress 1070 select { 1071 case update <- struct{}{}: 1072 default: 1073 } 1074 1075 case <-ticker.C: 1076 // Sanity check update the progress 1077 select { 1078 case update <- struct{}{}: 1079 default: 1080 } 1081 1082 case <-update: 1083 // Short circuit if we lost all our peers 1084 if d.peers.Len() == 0 { 1085 return errNoPeers 1086 } 1087 // Check for fetch request timeouts and demote the responsible peers 1088 for pid, fails := range expire() { 1089 if peer := d.peers.Peer(pid); peer != nil { 1090 // If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps 1091 // ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times 1092 // out that sync wise we need to get rid of the peer. 1093 // 1094 // The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth 1095 // and latency of a peer separately, which requires pushing the measures capacity a bit and seeing 1096 // how response times reacts, to it always requests one more than the minimum (i.e. min 2). 1097 if fails > 2 { 1098 peer.log.Trace("Data delivery timed out", "type", kind) 1099 setIdle(peer, 0) 1100 } else { 1101 peer.log.Debug("Stalling delivery, dropping", "type", kind) 1102 d.dropPeer(pid) 1103 } 1104 } 1105 } 1106 // If there's nothing more to fetch, wait or terminate 1107 if pending() == 0 { 1108 if !inFlight() && finished { 1109 log.Debug("Data fetching completed", "type", kind) 1110 return nil 1111 } 1112 break 1113 } 1114 // Send a download request to all idle peers, until throttled 1115 progressed, throttled, running := false, false, inFlight() 1116 idles, total := idle() 1117 1118 for _, peer := range idles { 1119 // Short circuit if throttling activated 1120 if throttle() { 1121 throttled = true 1122 break 1123 } 1124 // Short circuit if there is no more available task. 1125 if pending() == 0 { 1126 break 1127 } 1128 // Reserve a chunk of fetches for a peer. A nil can mean either that 1129 // no more headers are available, or that the peer is known not to 1130 // have them. 1131 request, progress, err := reserve(peer, capacity(peer)) 1132 if err != nil { 1133 return err 1134 } 1135 if progress { 1136 progressed = true 1137 } 1138 if request == nil { 1139 continue 1140 } 1141 if request.From > 0 { 1142 peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From) 1143 } else if len(request.Headers) > 0 { 1144 peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number) 1145 } else { 1146 peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Hashes)) 1147 } 1148 // Fetch the chunk and make sure any errors return the hashes to the queue 1149 if fetchHook != nil { 1150 fetchHook(request.Headers) 1151 } 1152 if err := fetch(peer, request); err != nil { 1153 // Although we could try and make an attempt to fix this, this error really 1154 // means that we've double allocated a fetch task to a peer. If that is the 1155 // case, the internal state of the downloader and the queue is very wrong so 1156 // better hard crash and note the error instead of silently accumulating into 1157 // a much bigger issue. 1158 panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind)) 1159 } 1160 running = true 1161 } 1162 // Make sure that we have peers available for fetching. If all peers have been tried 1163 // and all failed throw an error 1164 if !progressed && !throttled && !running && len(idles) == total && pending() > 0 { 1165 return errPeersUnavailable 1166 } 1167 } 1168 } 1169 } 1170 1171 // processHeaders takes batches of retrieved headers from an input channel and 1172 // keeps processing and scheduling them into the header chain and downloader's 1173 // queue until the stream ends or a failure occurs. 1174 func (d *Downloader) processHeaders(origin uint64, td *big.Int) error { 1175 // Calculate the pivoting point for switching from fast to slow sync 1176 pivot := d.queue.FastSyncPivot() 1177 1178 // Keep a count of uncertain headers to roll back 1179 rollback := []*types.Header{} 1180 defer func() { 1181 if len(rollback) > 0 { 1182 // Flatten the headers and roll them back 1183 hashes := make([]common.Hash, len(rollback)) 1184 for i, header := range rollback { 1185 hashes[i] = header.Hash() 1186 } 1187 lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0 1188 if d.mode != LightSync { 1189 lastFastBlock = d.blockchain.CurrentFastBlock().Number() 1190 lastBlock = d.blockchain.CurrentBlock().Number() 1191 } 1192 d.lightchain.Rollback(hashes) 1193 curFastBlock, curBlock := common.Big0, common.Big0 1194 if d.mode != LightSync { 1195 curFastBlock = d.blockchain.CurrentFastBlock().Number() 1196 curBlock = d.blockchain.CurrentBlock().Number() 1197 } 1198 log.Warn("Rolled back headers", "count", len(hashes), 1199 "header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number), 1200 "fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock), 1201 "block", fmt.Sprintf("%d->%d", lastBlock, curBlock)) 1202 1203 // If we're already past the pivot point, this could be an attack, thread carefully 1204 if rollback[len(rollback)-1].Number.Uint64() > pivot { 1205 // If we didn't ever fail, lock in the pivot header (must! not! change!) 1206 if atomic.LoadUint32(&d.fsPivotFails) == 0 { 1207 for _, header := range rollback { 1208 if header.Number.Uint64() == pivot { 1209 log.Warn("Fast-sync pivot locked in", "number", pivot, "hash", header.Hash()) 1210 d.fsPivotLock = header 1211 } 1212 } 1213 } 1214 } 1215 } 1216 }() 1217 1218 // Wait for batches of headers to process 1219 gotHeaders := false 1220 1221 for { 1222 select { 1223 case <-d.cancelCh: 1224 return errCancelHeaderProcessing 1225 1226 case headers := <-d.headerProcCh: 1227 // Terminate header processing if we synced up 1228 if len(headers) == 0 { 1229 // Notify everyone that headers are fully processed 1230 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 1231 select { 1232 case ch <- false: 1233 case <-d.cancelCh: 1234 } 1235 } 1236 // If no headers were retrieved at all, the peer violated its TD promise that it had a 1237 // better chain compared to ours. The only exception is if its promised blocks were 1238 // already imported by other means (e.g. fecher): 1239 // 1240 // R <remote peer>, L <local node>: Both at block 10 1241 // R: Mine block 11, and propagate it to L 1242 // L: Queue block 11 for import 1243 // L: Notice that R's head and TD increased compared to ours, start sync 1244 // L: Import of block 11 finishes 1245 // L: Sync begins, and finds common ancestor at 11 1246 // L: Request new headers up from 11 (R's TD was higher, it must have something) 1247 // R: Nothing to give 1248 if d.mode != LightSync { 1249 if !gotHeaders && td.Cmp(d.blockchain.GetTdByHash(d.blockchain.CurrentBlock().Hash())) > 0 { 1250 return errStallingPeer 1251 } 1252 } 1253 // If fast or light syncing, ensure promised headers are indeed delivered. This is 1254 // needed to detect scenarios where an attacker feeds a bad pivot and then bails out 1255 // of delivering the post-pivot blocks that would flag the invalid content. 1256 // 1257 // This check cannot be executed "as is" for full imports, since blocks may still be 1258 // queued for processing when the header download completes. However, as long as the 1259 // peer gave us something useful, we're already happy/progressed (above check). 1260 if d.mode == FastSync || d.mode == LightSync { 1261 if td.Cmp(d.lightchain.GetTdByHash(d.lightchain.CurrentHeader().Hash())) > 0 { 1262 return errStallingPeer 1263 } 1264 } 1265 // Disable any rollback and return 1266 rollback = nil 1267 return nil 1268 } 1269 // Otherwise split the chunk of headers into batches and process them 1270 gotHeaders = true 1271 1272 for len(headers) > 0 { 1273 // Terminate if something failed in between processing chunks 1274 select { 1275 case <-d.cancelCh: 1276 return errCancelHeaderProcessing 1277 default: 1278 } 1279 // Select the next chunk of headers to import 1280 limit := maxHeadersProcess 1281 if limit > len(headers) { 1282 limit = len(headers) 1283 } 1284 chunk := headers[:limit] 1285 1286 // In case of header only syncing, validate the chunk immediately 1287 if d.mode == FastSync || d.mode == LightSync { 1288 // Collect the yet unknown headers to mark them as uncertain 1289 unknown := make([]*types.Header, 0, len(headers)) 1290 for _, header := range chunk { 1291 if !d.lightchain.HasHeader(header.Hash(), header.Number.Uint64()) { 1292 unknown = append(unknown, header) 1293 } 1294 } 1295 // If we're importing pure headers, verify based on their recentness 1296 frequency := fsHeaderCheckFrequency 1297 if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot { 1298 frequency = 1 1299 } 1300 if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil { 1301 // If some headers were inserted, add them too to the rollback list 1302 if n > 0 { 1303 rollback = append(rollback, chunk[:n]...) 1304 } 1305 log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "err", err) 1306 return errInvalidChain 1307 } 1308 // All verifications passed, store newly found uncertain headers 1309 rollback = append(rollback, unknown...) 1310 if len(rollback) > fsHeaderSafetyNet { 1311 rollback = append(rollback[:0], rollback[len(rollback)-fsHeaderSafetyNet:]...) 1312 } 1313 } 1314 // If we're fast syncing and just pulled in the pivot, make sure it's the one locked in 1315 if d.mode == FastSync && d.fsPivotLock != nil && chunk[0].Number.Uint64() <= pivot && chunk[len(chunk)-1].Number.Uint64() >= pivot { 1316 if pivot := chunk[int(pivot-chunk[0].Number.Uint64())]; pivot.Hash() != d.fsPivotLock.Hash() { 1317 log.Warn("Pivot doesn't match locked in one", "remoteNumber", pivot.Number, "remoteHash", pivot.Hash(), "localNumber", d.fsPivotLock.Number, "localHash", d.fsPivotLock.Hash()) 1318 return errInvalidChain 1319 } 1320 } 1321 // Unless we're doing light chains, schedule the headers for associated content retrieval 1322 if d.mode == FullSync || d.mode == FastSync { 1323 // If we've reached the allowed number of pending headers, stall a bit 1324 for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders { 1325 select { 1326 case <-d.cancelCh: 1327 return errCancelHeaderProcessing 1328 case <-time.After(time.Second): 1329 } 1330 } 1331 // Otherwise insert the headers for content retrieval 1332 inserts := d.queue.Schedule(chunk, origin) 1333 if len(inserts) != len(chunk) { 1334 log.Debug("Stale headers") 1335 return errBadPeer 1336 } 1337 } 1338 headers = headers[limit:] 1339 origin += uint64(limit) 1340 } 1341 // Signal the content downloaders of the availablility of new tasks 1342 for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} { 1343 select { 1344 case ch <- true: 1345 default: 1346 } 1347 } 1348 } 1349 } 1350 } 1351 1352 // processFullSyncContent takes fetch results from the queue and imports them into the chain. 1353 func (d *Downloader) processFullSyncContent() error { 1354 for { 1355 results := d.queue.WaitResults() 1356 if len(results) == 0 { 1357 return nil 1358 } 1359 if d.chainInsertHook != nil { 1360 d.chainInsertHook(results) 1361 } 1362 if err := d.importBlockResults(results); err != nil { 1363 return err 1364 } 1365 } 1366 } 1367 1368 func (d *Downloader) importBlockResults(results []*fetchResult) error { 1369 for len(results) != 0 { 1370 // Check for any termination requests. This makes clean shutdown faster. 1371 select { 1372 case <-d.quitCh: 1373 return errCancelContentProcessing 1374 default: 1375 } 1376 // Retrieve the a batch of results to import 1377 items := int(math.Min(float64(len(results)), float64(maxResultsProcess))) 1378 first, last := results[0].Header, results[items-1].Header 1379 log.Debug("Inserting downloaded chain", "items", len(results), 1380 "firstnum", first.Number, "firsthash", first.Hash(), 1381 "lastnum", last.Number, "lasthash", last.Hash(), 1382 ) 1383 blocks := make([]*types.Block, items) 1384 for i, result := range results[:items] { 1385 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1386 } 1387 if index, err := d.blockchain.InsertChain(blocks); err != nil { 1388 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1389 return errInvalidChain 1390 } 1391 ss, ee := blocks[0].NumberU64(), blocks[len(blocks)-1].NumberU64() 1392 log.Info(fmt.Sprintf("[downloader] --> count=%d, range=(%d-%d).", (ee - ss), ss, ee)) 1393 1394 // Shift the results to the next batch 1395 results = results[items:] 1396 } 1397 return nil 1398 } 1399 1400 // processFastSyncContent takes fetch results from the queue and writes them to the 1401 // database. It also controls the synchronisation of state nodes of the pivot block. 1402 func (d *Downloader) processFastSyncContent(latest *types.Header) error { 1403 // Start syncing state of the reported head block. 1404 // This should get us most of the state of the pivot block. 1405 stateSync := d.syncState(latest.Root) 1406 defer stateSync.Cancel() 1407 go func() { 1408 if err := stateSync.Wait(); err != nil { 1409 d.queue.Close() // wake up WaitResults 1410 } 1411 }() 1412 1413 pivot := d.queue.FastSyncPivot() 1414 for { 1415 results := d.queue.WaitResults() 1416 if len(results) == 0 { 1417 return stateSync.Cancel() 1418 } 1419 if d.chainInsertHook != nil { 1420 d.chainInsertHook(results) 1421 } 1422 P, beforeP, afterP := splitAroundPivot(pivot, results) 1423 if err := d.commitFastSyncData(beforeP, stateSync); err != nil { 1424 return err 1425 } 1426 if P != nil { 1427 stateSync.Cancel() 1428 if err := d.commitPivotBlock(P); err != nil { 1429 return err 1430 } 1431 } 1432 if err := d.importBlockResults(afterP); err != nil { 1433 return err 1434 } 1435 } 1436 } 1437 1438 func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) { 1439 for _, result := range results { 1440 num := result.Header.Number.Uint64() 1441 switch { 1442 case num < pivot: 1443 before = append(before, result) 1444 case num == pivot: 1445 p = result 1446 default: 1447 after = append(after, result) 1448 } 1449 } 1450 return p, before, after 1451 } 1452 1453 func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error { 1454 for len(results) != 0 { 1455 // Check for any termination requests. 1456 select { 1457 case <-d.quitCh: 1458 return errCancelContentProcessing 1459 case <-stateSync.done: 1460 if err := stateSync.Wait(); err != nil { 1461 return err 1462 } 1463 default: 1464 } 1465 // Retrieve the a batch of results to import 1466 items := int(math.Min(float64(len(results)), float64(maxResultsProcess))) 1467 first, last := results[0].Header, results[items-1].Header 1468 log.Debug("Inserting fast-sync blocks", "items", len(results), 1469 "firstnum", first.Number, "firsthash", first.Hash(), 1470 "lastnumn", last.Number, "lasthash", last.Hash(), 1471 ) 1472 blocks := make([]*types.Block, items) 1473 receipts := make([]types.Receipts, items) 1474 for i, result := range results[:items] { 1475 blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1476 receipts[i] = result.Receipts 1477 } 1478 if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil { 1479 log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err) 1480 return errInvalidChain 1481 } 1482 ss := blocks[0].NumberU64() 1483 ee := blocks[len(blocks)-1].NumberU64() 1484 tt := ee - ss 1485 log.Info(fmt.Sprintf("[downloader-fast] --> total=%d, range=(%d-%d). ", tt, ss, ee)) 1486 // Shift the results to the next batch 1487 results = results[items:] 1488 } 1489 return nil 1490 } 1491 1492 func (d *Downloader) commitPivotBlock(result *fetchResult) error { 1493 log.Info("<<commitPivotBlock>>", "num", result.Header.Number.Int64(), "Root", result.Header.Root.Hex()) 1494 b := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles) 1495 // Sync the pivot block state. This should complete reasonably quickly because 1496 // we've already synced up to the reported head block state earlier. 1497 if err := d.syncState(b.Root()).Wait(); err != nil { 1498 return err 1499 } 1500 log.Info("Committing fast sync pivot as new head", "number", b.Number(), "hash", b.Hash()) 1501 if _, err := d.blockchain.InsertReceiptChain([]*types.Block{b}, []types.Receipts{result.Receipts}); err != nil { 1502 return err 1503 } 1504 1505 return d.blockchain.FastSyncCommitHead(b.Hash()) 1506 } 1507 1508 // DeliverHeaders injects a new batch of block headers received from a remote 1509 // node into the download schedule. 1510 func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) { 1511 return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter) 1512 } 1513 1514 // DeliverBodies injects a new batch of block bodies received from a remote node. 1515 func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) { 1516 return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter) 1517 } 1518 1519 // DeliverReceipts injects a new batch of receipts received from a remote node. 1520 func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) { 1521 return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter) 1522 } 1523 1524 // DeliverNodeData injects a new batch of node state data received from a remote node. 1525 func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) { 1526 return d.deliver(id, d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter) 1527 } 1528 1529 // deliver injects a new batch of data received from a remote node. 1530 func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) { 1531 // Update the delivery metrics for both good and failed deliveries 1532 inMeter.Mark(int64(packet.Items())) 1533 defer func() { 1534 if err != nil { 1535 dropMeter.Mark(int64(packet.Items())) 1536 } 1537 }() 1538 // Deliver or abort if the sync is canceled while queuing 1539 d.cancelLock.RLock() 1540 cancel := d.cancelCh 1541 d.cancelLock.RUnlock() 1542 if cancel == nil { 1543 return errNoSyncActive 1544 } 1545 select { 1546 case destCh <- packet: 1547 return nil 1548 case <-cancel: 1549 return errNoSyncActive 1550 } 1551 } 1552 1553 // qosTuner is the quality of service tuning loop that occasionally gathers the 1554 // peer latency statistics and updates the estimated request round trip time. 1555 func (d *Downloader) qosTuner() { 1556 for { 1557 // Retrieve the current median RTT and integrate into the previoust target RTT 1558 rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT())) 1559 atomic.StoreUint64(&d.rttEstimate, uint64(rtt)) 1560 1561 // A new RTT cycle passed, increase our confidence in the estimated RTT 1562 conf := atomic.LoadUint64(&d.rttConfidence) 1563 conf = conf + (1000000-conf)/2 1564 atomic.StoreUint64(&d.rttConfidence, conf) 1565 1566 // Log the new QoS values and sleep until the next RTT 1567 log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL()) 1568 select { 1569 case <-d.quitCh: 1570 return 1571 case <-time.After(rtt): 1572 } 1573 } 1574 } 1575 1576 // qosReduceConfidence is meant to be called when a new peer joins the downloader's 1577 // peer set, needing to reduce the confidence we have in out QoS estimates. 1578 func (d *Downloader) qosReduceConfidence() { 1579 // If we have a single peer, confidence is always 1 1580 peers := uint64(d.peers.Len()) 1581 if peers == 0 { 1582 // Ensure peer connectivity races don't catch us off guard 1583 return 1584 } 1585 if peers == 1 { 1586 atomic.StoreUint64(&d.rttConfidence, 1000000) 1587 return 1588 } 1589 // If we have a ton of peers, don't drop confidence) 1590 if peers >= uint64(qosConfidenceCap) { 1591 return 1592 } 1593 // Otherwise drop the confidence factor 1594 conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers 1595 if float64(conf)/1000000 < rttMinConfidence { 1596 conf = uint64(rttMinConfidence * 1000000) 1597 } 1598 atomic.StoreUint64(&d.rttConfidence, conf) 1599 1600 rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate)) 1601 log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL()) 1602 } 1603 1604 // requestRTT returns the current target round trip time for a download request 1605 // to complete in. 1606 // 1607 // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that 1608 // the downloader tries to adapt queries to the RTT, so multiple RTT values can 1609 // be adapted to, but smaller ones are preffered (stabler download stream). 1610 func (d *Downloader) requestRTT() time.Duration { 1611 return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10 1612 } 1613 1614 // requestTTL returns the current timeout allowance for a single download request 1615 // to finish under. 1616 func (d *Downloader) requestTTL() time.Duration { 1617 var ( 1618 rtt = time.Duration(atomic.LoadUint64(&d.rttEstimate)) 1619 conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0 1620 ) 1621 ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf) 1622 if ttl > ttlLimit { 1623 ttl = ttlLimit 1624 } 1625 return ttl 1626 }