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