github.com/phillinzzz/newBsc@v1.1.6/eth/downloader/downloader.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package downloader contains the manual full chain synchronisation.
    18  package downloader
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"sync"
    25  	"sync/atomic"
    26  	"time"
    27  
    28  	"github.com/phillinzzz/newBsc"
    29  	"github.com/phillinzzz/newBsc/common"
    30  	"github.com/phillinzzz/newBsc/core/rawdb"
    31  	"github.com/phillinzzz/newBsc/core/state/snapshot"
    32  	"github.com/phillinzzz/newBsc/core/types"
    33  	"github.com/phillinzzz/newBsc/eth/protocols/eth"
    34  	"github.com/phillinzzz/newBsc/eth/protocols/snap"
    35  	"github.com/phillinzzz/newBsc/ethdb"
    36  	"github.com/phillinzzz/newBsc/event"
    37  	"github.com/phillinzzz/newBsc/log"
    38  	"github.com/phillinzzz/newBsc/metrics"
    39  	"github.com/phillinzzz/newBsc/params"
    40  	"github.com/phillinzzz/newBsc/trie"
    41  )
    42  
    43  var (
    44  	MaxBlockFetch   = 128 // Amount of blocks to be fetched per retrieval request
    45  	MaxHeaderFetch  = 192 // Amount of block headers to be fetched per retrieval request
    46  	MaxSkeletonSize = 128 // Number of header fetches to need for a skeleton assembly
    47  	MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request
    48  	MaxStateFetch   = 384 // Amount of node state values to allow fetching per request
    49  
    50  	rttMinEstimate   = 2 * time.Second  // Minimum round-trip time to target for download requests
    51  	rttMaxEstimate   = 20 * time.Second // Maximum round-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  	fullMaxForkAncestry  uint64 = params.FullImmutabilityThreshold  // Maximum chain reorganisation (locally redeclared so tests can reduce it)
    64  	lightMaxForkAncestry uint64 = params.LightImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it)
    65  
    66  	reorgProtThreshold   = 48 // Threshold number of recent blocks to disable mini reorg protection
    67  	reorgProtHeaderDelay = 2  // Number of headers to delay delivering to cover mini reorgs
    68  
    69  	fsHeaderCheckFrequency = 100             // Verification frequency of the downloaded headers during fast sync
    70  	fsHeaderSafetyNet      = 2048            // Number of headers to discard in case a chain violation is detected
    71  	fsHeaderForceVerify    = 24              // Number of headers to verify before and after the pivot to accept it
    72  	fsHeaderContCheck      = 3 * time.Second // Time interval to check for header continuations during state download
    73  	fsMinFullBlocks        = 64              // Number of blocks to retrieve fully even in fast sync
    74  )
    75  
    76  var (
    77  	errBusy                    = errors.New("busy")
    78  	errUnknownPeer             = errors.New("peer is unknown or unhealthy")
    79  	errBadPeer                 = errors.New("action from bad peer ignored")
    80  	errStallingPeer            = errors.New("peer is stalling")
    81  	errUnsyncedPeer            = errors.New("unsynced peer")
    82  	errNoPeers                 = errors.New("no peers to keep download active")
    83  	errTimeout                 = errors.New("timeout")
    84  	errEmptyHeaderSet          = errors.New("empty header set by peer")
    85  	errPeersUnavailable        = errors.New("no peers available or all tried for download")
    86  	errInvalidAncestor         = errors.New("retrieved ancestor is invalid")
    87  	errInvalidChain            = errors.New("retrieved hash chain is invalid")
    88  	errInvalidBody             = errors.New("retrieved block body is invalid")
    89  	errInvalidReceipt          = errors.New("retrieved receipt is invalid")
    90  	errCancelStateFetch        = errors.New("state data download canceled (requested)")
    91  	errCancelContentProcessing = errors.New("content processing canceled (requested)")
    92  	errCanceled                = errors.New("syncing canceled (requested)")
    93  	errNoSyncActive            = errors.New("no sync active")
    94  	errTooOld                  = errors.New("peer's protocol version too old")
    95  	errNoAncestorFound         = errors.New("no common ancestor found")
    96  )
    97  
    98  type Downloader struct {
    99  	// WARNING: The `rttEstimate` and `rttConfidence` fields are accessed atomically.
   100  	// On 32 bit platforms, only 64-bit aligned fields can be atomic. The struct is
   101  	// guaranteed to be so aligned, so take advantage of that. For more information,
   102  	// see https://golang.org/pkg/sync/atomic/#pkg-note-BUG.
   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  	mode uint32         // Synchronisation mode defining the strategy used (per sync cycle), use d.getMode() to get the SyncMode
   107  	mux  *event.TypeMux // Event multiplexer to announce sync operation events
   108  
   109  	checkpoint uint64   // Checkpoint block number to enforce head against (e.g. fast sync)
   110  	genesis    uint64   // Genesis block number to limit sync to (e.g. light client CHT)
   111  	queue      *queue   // Scheduler for selecting the hashes to download
   112  	peers      *peerSet // Set of active peers from which download can proceed
   113  
   114  	stateDB    ethdb.Database  // Database to state sync into (and deduplicate via)
   115  	stateBloom *trie.SyncBloom // Bloom filter for fast trie node and contract code existence checks
   116  
   117  	// Statistics
   118  	syncStatsChainOrigin uint64 // Origin block number where syncing started at
   119  	syncStatsChainHeight uint64 // Highest block number known when syncing started
   120  	syncStatsState       stateSyncStats
   121  	syncStatsLock        sync.RWMutex // Lock protecting the sync stats fields
   122  
   123  	lightchain LightChain
   124  	blockchain BlockChain
   125  
   126  	// Callbacks
   127  	dropPeer peerDropFn // Drops a peer for misbehaving
   128  
   129  	// Status
   130  	synchroniseMock func(id string, hash common.Hash) error // Replacement for synchronise during testing
   131  	synchronising   int32
   132  	notified        int32
   133  	committed       int32
   134  	ancientLimit    uint64 // The maximum block number which can be regarded as ancient data.
   135  
   136  	// Channels
   137  	headerCh      chan dataPack        // Channel receiving inbound block headers
   138  	bodyCh        chan dataPack        // Channel receiving inbound block bodies
   139  	receiptCh     chan dataPack        // Channel receiving inbound receipts
   140  	bodyWakeCh    chan bool            // Channel to signal the block body fetcher of new tasks
   141  	receiptWakeCh chan bool            // Channel to signal the receipt fetcher of new tasks
   142  	headerProcCh  chan []*types.Header // Channel to feed the header processor new tasks
   143  
   144  	// State sync
   145  	pivotHeader *types.Header // Pivot block header to dynamically push the syncing state root
   146  	pivotLock   sync.RWMutex  // Lock protecting pivot header reads from updates
   147  
   148  	snapSync       bool         // Whether to run state sync over the snap protocol
   149  	SnapSyncer     *snap.Syncer // TODO(karalabe): make private! hack for now
   150  	stateSyncStart chan *stateSync
   151  	trackStateReq  chan *stateReq
   152  	stateCh        chan dataPack // Channel receiving inbound node state data
   153  
   154  	// Cancellation and termination
   155  	cancelPeer string         // Identifier of the peer currently being used as the master (cancel on drop)
   156  	cancelCh   chan struct{}  // Channel to cancel mid-flight syncs
   157  	cancelLock sync.RWMutex   // Lock to protect the cancel channel and peer in delivers
   158  	cancelWg   sync.WaitGroup // Make sure all fetcher goroutines have exited.
   159  
   160  	quitCh   chan struct{} // Quit channel to signal termination
   161  	quitLock sync.Mutex    // Lock to prevent double closes
   162  
   163  	// Testing hooks
   164  	syncInitHook     func(uint64, uint64)                  // Method to call upon initiating a new sync run
   165  	bodyFetchHook    func([]*types.Header, ...interface{}) // Method to call upon starting a block body fetch
   166  	receiptFetchHook func([]*types.Header, ...interface{}) // Method to call upon starting a receipt fetch
   167  	chainInsertHook  func([]*fetchResult)                  // Method to call upon inserting a chain of blocks (possibly in multiple invocations)
   168  }
   169  
   170  // LightChain encapsulates functions required to synchronise a light chain.
   171  type LightChain interface {
   172  	// HasHeader verifies a header's presence in the local chain.
   173  	HasHeader(common.Hash, uint64) bool
   174  
   175  	// GetHeaderByHash retrieves a header from the local chain.
   176  	GetHeaderByHash(common.Hash) *types.Header
   177  
   178  	// CurrentHeader retrieves the head header from the local chain.
   179  	CurrentHeader() *types.Header
   180  
   181  	// GetTd returns the total difficulty of a local block.
   182  	GetTd(common.Hash, uint64) *big.Int
   183  
   184  	// InsertHeaderChain inserts a batch of headers into the local chain.
   185  	InsertHeaderChain([]*types.Header, int) (int, error)
   186  
   187  	// SetHead rewinds the local chain to a new head.
   188  	SetHead(uint64) error
   189  }
   190  
   191  // BlockChain encapsulates functions required to sync a (full or fast) blockchain.
   192  type BlockChain interface {
   193  	LightChain
   194  
   195  	// HasBlock verifies a block's presence in the local chain.
   196  	HasBlock(common.Hash, uint64) bool
   197  
   198  	// HasFastBlock verifies a fast block's presence in the local chain.
   199  	HasFastBlock(common.Hash, uint64) bool
   200  
   201  	// GetBlockByHash retrieves a block from the local chain.
   202  	GetBlockByHash(common.Hash) *types.Block
   203  
   204  	// CurrentBlock retrieves the head block from the local chain.
   205  	CurrentBlock() *types.Block
   206  
   207  	// CurrentFastBlock retrieves the head fast block from the local chain.
   208  	CurrentFastBlock() *types.Block
   209  
   210  	// FastSyncCommitHead directly commits the head block to a certain entity.
   211  	FastSyncCommitHead(common.Hash) error
   212  
   213  	// InsertChain inserts a batch of blocks into the local chain.
   214  	InsertChain(types.Blocks) (int, error)
   215  
   216  	// InsertReceiptChain inserts a batch of receipts into the local chain.
   217  	InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error)
   218  
   219  	// Snapshots returns the blockchain snapshot tree to paused it during sync.
   220  	Snapshots() *snapshot.Tree
   221  }
   222  
   223  type DownloadOption func(downloader *Downloader) *Downloader
   224  
   225  type IDiffPeer interface {
   226  	RequestDiffLayers([]common.Hash) error
   227  }
   228  
   229  type IPeerSet interface {
   230  	GetDiffPeer(string) IDiffPeer
   231  }
   232  
   233  func EnableDiffFetchOp(peers IPeerSet) DownloadOption {
   234  	return func(dl *Downloader) *Downloader {
   235  		var hook = func(headers []*types.Header, args ...interface{}) {
   236  			if len(args) < 2 {
   237  				return
   238  			}
   239  			peerID, ok := args[1].(string)
   240  			if !ok {
   241  				return
   242  			}
   243  			mode, ok := args[0].(SyncMode)
   244  			if !ok {
   245  				return
   246  			}
   247  			if ep := peers.GetDiffPeer(peerID); mode == FullSync && ep != nil {
   248  				hashes := make([]common.Hash, 0, len(headers))
   249  				for _, header := range headers {
   250  					hashes = append(hashes, header.Hash())
   251  				}
   252  				ep.RequestDiffLayers(hashes)
   253  			}
   254  		}
   255  		dl.bodyFetchHook = hook
   256  		return dl
   257  	}
   258  }
   259  
   260  // New creates a new downloader to fetch hashes and blocks from remote peers.
   261  func New(checkpoint uint64, stateDb ethdb.Database, stateBloom *trie.SyncBloom, mux *event.TypeMux, chain BlockChain, lightchain LightChain, dropPeer peerDropFn, options ...DownloadOption) *Downloader {
   262  	if lightchain == nil {
   263  		lightchain = chain
   264  	}
   265  	dl := &Downloader{
   266  		stateDB:        stateDb,
   267  		stateBloom:     stateBloom,
   268  		mux:            mux,
   269  		checkpoint:     checkpoint,
   270  		queue:          newQueue(blockCacheMaxItems, blockCacheInitialItems),
   271  		peers:          newPeerSet(),
   272  		rttEstimate:    uint64(rttMaxEstimate),
   273  		rttConfidence:  uint64(1000000),
   274  		blockchain:     chain,
   275  		lightchain:     lightchain,
   276  		dropPeer:       dropPeer,
   277  		headerCh:       make(chan dataPack, 1),
   278  		bodyCh:         make(chan dataPack, 1),
   279  		receiptCh:      make(chan dataPack, 1),
   280  		bodyWakeCh:     make(chan bool, 1),
   281  		receiptWakeCh:  make(chan bool, 1),
   282  		headerProcCh:   make(chan []*types.Header, 1),
   283  		quitCh:         make(chan struct{}),
   284  		stateCh:        make(chan dataPack),
   285  		SnapSyncer:     snap.NewSyncer(stateDb),
   286  		stateSyncStart: make(chan *stateSync),
   287  		syncStatsState: stateSyncStats{
   288  			processed: rawdb.ReadFastTrieProgress(stateDb),
   289  		},
   290  		trackStateReq: make(chan *stateReq),
   291  	}
   292  	for _, option := range options {
   293  		if dl != nil {
   294  			dl = option(dl)
   295  		}
   296  	}
   297  	go dl.qosTuner()
   298  	go dl.stateFetcher()
   299  	return dl
   300  }
   301  
   302  // Progress retrieves the synchronisation boundaries, specifically the origin
   303  // block where synchronisation started at (may have failed/suspended); the block
   304  // or header sync is currently at; and the latest known block which the sync targets.
   305  //
   306  // In addition, during the state download phase of fast synchronisation the number
   307  // of processed and the total number of known states are also returned. Otherwise
   308  // these are zero.
   309  func (d *Downloader) Progress() ethereum.SyncProgress {
   310  	// Lock the current stats and return the progress
   311  	d.syncStatsLock.RLock()
   312  	defer d.syncStatsLock.RUnlock()
   313  
   314  	current := uint64(0)
   315  	mode := d.getMode()
   316  	switch {
   317  	case d.blockchain != nil && mode == FullSync:
   318  		current = d.blockchain.CurrentBlock().NumberU64()
   319  	case d.blockchain != nil && mode == FastSync:
   320  		current = d.blockchain.CurrentFastBlock().NumberU64()
   321  	case d.lightchain != nil:
   322  		current = d.lightchain.CurrentHeader().Number.Uint64()
   323  	default:
   324  		log.Error("Unknown downloader chain/mode combo", "light", d.lightchain != nil, "full", d.blockchain != nil, "mode", mode)
   325  	}
   326  	return ethereum.SyncProgress{
   327  		StartingBlock: d.syncStatsChainOrigin,
   328  		CurrentBlock:  current,
   329  		HighestBlock:  d.syncStatsChainHeight,
   330  		PulledStates:  d.syncStatsState.processed,
   331  		KnownStates:   d.syncStatsState.processed + d.syncStatsState.pending,
   332  	}
   333  }
   334  
   335  // Synchronising returns whether the downloader is currently retrieving blocks.
   336  func (d *Downloader) Synchronising() bool {
   337  	return atomic.LoadInt32(&d.synchronising) > 0
   338  }
   339  
   340  // RegisterPeer injects a new download peer into the set of block source to be
   341  // used for fetching hashes and blocks from.
   342  func (d *Downloader) RegisterPeer(id string, version uint, peer Peer) error {
   343  	var logger log.Logger
   344  	if len(id) < 16 {
   345  		// Tests use short IDs, don't choke on them
   346  		logger = log.New("peer", id)
   347  	} else {
   348  		logger = log.New("peer", id[:8])
   349  	}
   350  	logger.Trace("Registering sync peer")
   351  	if err := d.peers.Register(newPeerConnection(id, version, peer, logger)); err != nil {
   352  		logger.Error("Failed to register sync peer", "err", err)
   353  		return err
   354  	}
   355  	d.qosReduceConfidence()
   356  
   357  	return nil
   358  }
   359  
   360  // RegisterLightPeer injects a light client peer, wrapping it so it appears as a regular peer.
   361  func (d *Downloader) RegisterLightPeer(id string, version uint, peer LightPeer) error {
   362  	return d.RegisterPeer(id, version, &lightPeerWrapper{peer})
   363  }
   364  
   365  // UnregisterPeer remove a peer from the known list, preventing any action from
   366  // the specified peer. An effort is also made to return any pending fetches into
   367  // the queue.
   368  func (d *Downloader) UnregisterPeer(id string) error {
   369  	// Unregister the peer from the active peer set and revoke any fetch tasks
   370  	var logger log.Logger
   371  	if len(id) < 16 {
   372  		// Tests use short IDs, don't choke on them
   373  		logger = log.New("peer", id)
   374  	} else {
   375  		logger = log.New("peer", id[:8])
   376  	}
   377  	logger.Trace("Unregistering sync peer")
   378  	if err := d.peers.Unregister(id); err != nil {
   379  		logger.Error("Failed to unregister sync peer", "err", err)
   380  		return err
   381  	}
   382  	d.queue.Revoke(id)
   383  
   384  	return nil
   385  }
   386  
   387  // Synchronise tries to sync up our local block chain with a remote peer, both
   388  // adding various sanity checks as well as wrapping it with various log entries.
   389  func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error {
   390  	err := d.synchronise(id, head, td, mode)
   391  
   392  	switch err {
   393  	case nil, errBusy, errCanceled:
   394  		return err
   395  	}
   396  	if errors.Is(err, errInvalidChain) || errors.Is(err, errBadPeer) || errors.Is(err, errTimeout) ||
   397  		errors.Is(err, errStallingPeer) || errors.Is(err, errUnsyncedPeer) || errors.Is(err, errEmptyHeaderSet) ||
   398  		errors.Is(err, errPeersUnavailable) || errors.Is(err, errTooOld) || errors.Is(err, errInvalidAncestor) {
   399  		log.Warn("Synchronisation failed, dropping peer", "peer", id, "err", err)
   400  		if d.dropPeer == nil {
   401  			// The dropPeer method is nil when `--copydb` is used for a local copy.
   402  			// Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
   403  			log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", id)
   404  		} else {
   405  			d.dropPeer(id)
   406  		}
   407  		return err
   408  	}
   409  	log.Warn("Synchronisation failed, retrying", "err", err)
   410  	return err
   411  }
   412  
   413  // synchronise will select the peer and use it for synchronising. If an empty string is given
   414  // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the
   415  // checks fail an error will be returned. This method is synchronous
   416  func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error {
   417  	// Mock out the synchronisation if testing
   418  	if d.synchroniseMock != nil {
   419  		return d.synchroniseMock(id, hash)
   420  	}
   421  	// Make sure only one goroutine is ever allowed past this point at once
   422  	if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
   423  		return errBusy
   424  	}
   425  	defer atomic.StoreInt32(&d.synchronising, 0)
   426  
   427  	// Post a user notification of the sync (only once per session)
   428  	if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
   429  		log.Info("Block synchronisation started")
   430  	}
   431  	// If we are already full syncing, but have a fast-sync bloom filter laying
   432  	// around, make sure it doesn't use memory any more. This is a special case
   433  	// when the user attempts to fast sync a new empty network.
   434  	if mode == FullSync && d.stateBloom != nil {
   435  		d.stateBloom.Close()
   436  	}
   437  	// If snap sync was requested, create the snap scheduler and switch to fast
   438  	// sync mode. Long term we could drop fast sync or merge the two together,
   439  	// but until snap becomes prevalent, we should support both. TODO(karalabe).
   440  	if mode == SnapSync {
   441  		if !d.snapSync {
   442  			// Snap sync uses the snapshot namespace to store potentially flakey data until
   443  			// sync completely heals and finishes. Pause snapshot maintenance in the mean
   444  			// time to prevent access.
   445  			if snapshots := d.blockchain.Snapshots(); snapshots != nil { // Only nil in tests
   446  				snapshots.Disable()
   447  			}
   448  			log.Warn("Enabling snapshot sync prototype")
   449  			d.snapSync = true
   450  		}
   451  		mode = FastSync
   452  	}
   453  	// Reset the queue, peer set and wake channels to clean any internal leftover state
   454  	d.queue.Reset(blockCacheMaxItems, blockCacheInitialItems)
   455  	d.peers.Reset()
   456  
   457  	for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
   458  		select {
   459  		case <-ch:
   460  		default:
   461  		}
   462  	}
   463  	for _, ch := range []chan dataPack{d.headerCh, d.bodyCh, d.receiptCh} {
   464  		for empty := false; !empty; {
   465  			select {
   466  			case <-ch:
   467  			default:
   468  				empty = true
   469  			}
   470  		}
   471  	}
   472  	for empty := false; !empty; {
   473  		select {
   474  		case <-d.headerProcCh:
   475  		default:
   476  			empty = true
   477  		}
   478  	}
   479  	// Create cancel channel for aborting mid-flight and mark the master peer
   480  	d.cancelLock.Lock()
   481  	d.cancelCh = make(chan struct{})
   482  	d.cancelPeer = id
   483  	d.cancelLock.Unlock()
   484  
   485  	defer d.Cancel() // No matter what, we can't leave the cancel channel open
   486  
   487  	// Atomically set the requested sync mode
   488  	atomic.StoreUint32(&d.mode, uint32(mode))
   489  
   490  	// Retrieve the origin peer and initiate the downloading process
   491  	p := d.peers.Peer(id)
   492  	if p == nil {
   493  		return errUnknownPeer
   494  	}
   495  	return d.syncWithPeer(p, hash, td)
   496  }
   497  
   498  func (d *Downloader) getMode() SyncMode {
   499  	return SyncMode(atomic.LoadUint32(&d.mode))
   500  }
   501  
   502  // syncWithPeer starts a block synchronization based on the hash chain from the
   503  // specified peer and head hash.
   504  func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.Int) (err error) {
   505  	d.mux.Post(StartEvent{})
   506  	defer func() {
   507  		// reset on error
   508  		if err != nil {
   509  			d.mux.Post(FailedEvent{err})
   510  		} else {
   511  			latest := d.lightchain.CurrentHeader()
   512  			d.mux.Post(DoneEvent{latest})
   513  		}
   514  	}()
   515  	if p.version < eth.ETH65 {
   516  		return fmt.Errorf("%w: advertized %d < required %d", errTooOld, p.version, eth.ETH65)
   517  	}
   518  	mode := d.getMode()
   519  
   520  	log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", mode)
   521  	defer func(start time.Time) {
   522  		log.Debug("Synchronisation terminated", "elapsed", common.PrettyDuration(time.Since(start)))
   523  	}(time.Now())
   524  
   525  	// Look up the sync boundaries: the common ancestor and the target block
   526  	latest, pivot, err := d.fetchHead(p)
   527  	if err != nil {
   528  		return err
   529  	}
   530  	if mode == FastSync && pivot == nil {
   531  		// If no pivot block was returned, the head is below the min full block
   532  		// threshold (i.e. new chian). In that case we won't really fast sync
   533  		// anyway, but still need a valid pivot block to avoid some code hitting
   534  		// nil panics on an access.
   535  		pivot = d.blockchain.CurrentBlock().Header()
   536  	}
   537  	height := latest.Number.Uint64()
   538  
   539  	origin, err := d.findAncestor(p, latest)
   540  	if err != nil {
   541  		return err
   542  	}
   543  	d.syncStatsLock.Lock()
   544  	if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin {
   545  		d.syncStatsChainOrigin = origin
   546  	}
   547  	d.syncStatsChainHeight = height
   548  	d.syncStatsLock.Unlock()
   549  
   550  	// Ensure our origin point is below any fast sync pivot point
   551  	if mode == FastSync {
   552  		if height <= uint64(fsMinFullBlocks) {
   553  			origin = 0
   554  		} else {
   555  			pivotNumber := pivot.Number.Uint64()
   556  			if pivotNumber <= origin {
   557  				origin = pivotNumber - 1
   558  			}
   559  			// Write out the pivot into the database so a rollback beyond it will
   560  			// reenable fast sync
   561  			rawdb.WriteLastPivotNumber(d.stateDB, pivotNumber)
   562  		}
   563  	}
   564  	d.committed = 1
   565  	if mode == FastSync && pivot.Number.Uint64() != 0 {
   566  		d.committed = 0
   567  	}
   568  	if mode == FastSync {
   569  		// Set the ancient data limitation.
   570  		// If we are running fast sync, all block data older than ancientLimit will be
   571  		// written to the ancient store. More recent data will be written to the active
   572  		// database and will wait for the freezer to migrate.
   573  		//
   574  		// If there is a checkpoint available, then calculate the ancientLimit through
   575  		// that. Otherwise calculate the ancient limit through the advertised height
   576  		// of the remote peer.
   577  		//
   578  		// The reason for picking checkpoint first is that a malicious peer can give us
   579  		// a fake (very high) height, forcing the ancient limit to also be very high.
   580  		// The peer would start to feed us valid blocks until head, resulting in all of
   581  		// the blocks might be written into the ancient store. A following mini-reorg
   582  		// could cause issues.
   583  		if d.checkpoint != 0 && d.checkpoint > fullMaxForkAncestry+1 {
   584  			d.ancientLimit = d.checkpoint
   585  		} else if height > fullMaxForkAncestry+1 {
   586  			d.ancientLimit = height - fullMaxForkAncestry - 1
   587  		} else {
   588  			d.ancientLimit = 0
   589  		}
   590  		frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here.
   591  
   592  		// If a part of blockchain data has already been written into active store,
   593  		// disable the ancient style insertion explicitly.
   594  		if origin >= frozen && frozen != 0 {
   595  			d.ancientLimit = 0
   596  			log.Info("Disabling direct-ancient mode", "origin", origin, "ancient", frozen-1)
   597  		} else if d.ancientLimit > 0 {
   598  			log.Debug("Enabling direct-ancient mode", "ancient", d.ancientLimit)
   599  		}
   600  		// Rewind the ancient store and blockchain if reorg happens.
   601  		if origin+1 < frozen {
   602  			if err := d.lightchain.SetHead(origin + 1); err != nil {
   603  				return err
   604  			}
   605  		}
   606  	}
   607  	// Initiate the sync using a concurrent header and content retrieval algorithm
   608  	d.queue.Prepare(origin+1, mode)
   609  	if d.syncInitHook != nil {
   610  		d.syncInitHook(origin, height)
   611  	}
   612  	fetchers := []func() error{
   613  		func() error { return d.fetchHeaders(p, origin+1) }, // Headers are always retrieved
   614  		func() error { return d.fetchBodies(origin + 1) },   // Bodies are retrieved during normal and fast sync
   615  		func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync
   616  		func() error { return d.processHeaders(origin+1, td) },
   617  	}
   618  	if mode == FastSync {
   619  		d.pivotLock.Lock()
   620  		d.pivotHeader = pivot
   621  		d.pivotLock.Unlock()
   622  
   623  		fetchers = append(fetchers, func() error { return d.processFastSyncContent() })
   624  	} else if mode == FullSync {
   625  		fetchers = append(fetchers, d.processFullSyncContent)
   626  	}
   627  	return d.spawnSync(fetchers)
   628  }
   629  
   630  // spawnSync runs d.process and all given fetcher functions to completion in
   631  // separate goroutines, returning the first error that appears.
   632  func (d *Downloader) spawnSync(fetchers []func() error) error {
   633  	errc := make(chan error, len(fetchers))
   634  	d.cancelWg.Add(len(fetchers))
   635  	for _, fn := range fetchers {
   636  		fn := fn
   637  		go func() { defer d.cancelWg.Done(); errc <- fn() }()
   638  	}
   639  	// Wait for the first error, then terminate the others.
   640  	var err error
   641  	for i := 0; i < len(fetchers); i++ {
   642  		if i == len(fetchers)-1 {
   643  			// Close the queue when all fetchers have exited.
   644  			// This will cause the block processor to end when
   645  			// it has processed the queue.
   646  			d.queue.Close()
   647  		}
   648  		if err = <-errc; err != nil && err != errCanceled {
   649  			break
   650  		}
   651  	}
   652  	d.queue.Close()
   653  	d.Cancel()
   654  	return err
   655  }
   656  
   657  // cancel aborts all of the operations and resets the queue. However, cancel does
   658  // not wait for the running download goroutines to finish. This method should be
   659  // used when cancelling the downloads from inside the downloader.
   660  func (d *Downloader) cancel() {
   661  	// Close the current cancel channel
   662  	d.cancelLock.Lock()
   663  	defer d.cancelLock.Unlock()
   664  
   665  	if d.cancelCh != nil {
   666  		select {
   667  		case <-d.cancelCh:
   668  			// Channel was already closed
   669  		default:
   670  			close(d.cancelCh)
   671  		}
   672  	}
   673  }
   674  
   675  // Cancel aborts all of the operations and waits for all download goroutines to
   676  // finish before returning.
   677  func (d *Downloader) Cancel() {
   678  	d.cancel()
   679  	d.cancelWg.Wait()
   680  }
   681  
   682  // Terminate interrupts the downloader, canceling all pending operations.
   683  // The downloader cannot be reused after calling Terminate.
   684  func (d *Downloader) Terminate() {
   685  	// Close the termination channel (make sure double close is allowed)
   686  	d.quitLock.Lock()
   687  	select {
   688  	case <-d.quitCh:
   689  	default:
   690  		close(d.quitCh)
   691  	}
   692  	if d.stateBloom != nil {
   693  		d.stateBloom.Close()
   694  	}
   695  	d.quitLock.Unlock()
   696  
   697  	// Cancel any pending download requests
   698  	d.Cancel()
   699  }
   700  
   701  // fetchHead retrieves the head header and prior pivot block (if available) from
   702  // a remote peer.
   703  func (d *Downloader) fetchHead(p *peerConnection) (head *types.Header, pivot *types.Header, err error) {
   704  	p.log.Debug("Retrieving remote chain head")
   705  	mode := d.getMode()
   706  
   707  	// Request the advertised remote head block and wait for the response
   708  	latest, _ := p.peer.Head()
   709  	fetch := 1
   710  	if mode == FastSync {
   711  		fetch = 2 // head + pivot headers
   712  	}
   713  	go p.peer.RequestHeadersByHash(latest, fetch, fsMinFullBlocks-1, true)
   714  
   715  	ttl := d.requestTTL()
   716  	timeout := time.After(ttl)
   717  	for {
   718  		select {
   719  		case <-d.cancelCh:
   720  			return nil, nil, errCanceled
   721  
   722  		case packet := <-d.headerCh:
   723  			// Discard anything not from the origin peer
   724  			if packet.PeerId() != p.id {
   725  				log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
   726  				break
   727  			}
   728  			// Make sure the peer gave us at least one and at most the requested headers
   729  			headers := packet.(*headerPack).headers
   730  			if len(headers) == 0 || len(headers) > fetch {
   731  				return nil, nil, fmt.Errorf("%w: returned headers %d != requested %d", errBadPeer, len(headers), fetch)
   732  			}
   733  			// The first header needs to be the head, validate against the checkpoint
   734  			// and request. If only 1 header was returned, make sure there's no pivot
   735  			// or there was not one requested.
   736  			head := headers[0]
   737  			if (mode == FastSync || mode == LightSync) && head.Number.Uint64() < d.checkpoint {
   738  				return nil, nil, fmt.Errorf("%w: remote head %d below checkpoint %d", errUnsyncedPeer, head.Number, d.checkpoint)
   739  			}
   740  			if len(headers) == 1 {
   741  				if mode == FastSync && head.Number.Uint64() > uint64(fsMinFullBlocks) {
   742  					return nil, nil, fmt.Errorf("%w: no pivot included along head header", errBadPeer)
   743  				}
   744  				p.log.Debug("Remote head identified, no pivot", "number", head.Number, "hash", head.Hash())
   745  				return head, nil, nil
   746  			}
   747  			// At this point we have 2 headers in total and the first is the
   748  			// validated head of the chian. Check the pivot number and return,
   749  			pivot := headers[1]
   750  			if pivot.Number.Uint64() != head.Number.Uint64()-uint64(fsMinFullBlocks) {
   751  				return nil, nil, fmt.Errorf("%w: remote pivot %d != requested %d", errInvalidChain, pivot.Number, head.Number.Uint64()-uint64(fsMinFullBlocks))
   752  			}
   753  			return head, pivot, nil
   754  
   755  		case <-timeout:
   756  			p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
   757  			return nil, nil, errTimeout
   758  
   759  		case <-d.bodyCh:
   760  		case <-d.receiptCh:
   761  			// Out of bounds delivery, ignore
   762  		}
   763  	}
   764  }
   765  
   766  // calculateRequestSpan calculates what headers to request from a peer when trying to determine the
   767  // common ancestor.
   768  // It returns parameters to be used for peer.RequestHeadersByNumber:
   769  //  from - starting block number
   770  //  count - number of headers to request
   771  //  skip - number of headers to skip
   772  // and also returns 'max', the last block which is expected to be returned by the remote peers,
   773  // given the (from,count,skip)
   774  func calculateRequestSpan(remoteHeight, localHeight uint64) (int64, int, int, uint64) {
   775  	var (
   776  		from     int
   777  		count    int
   778  		MaxCount = MaxHeaderFetch / 16
   779  	)
   780  	// requestHead is the highest block that we will ask for. If requestHead is not offset,
   781  	// the highest block that we will get is 16 blocks back from head, which means we
   782  	// will fetch 14 or 15 blocks unnecessarily in the case the height difference
   783  	// between us and the peer is 1-2 blocks, which is most common
   784  	requestHead := int(remoteHeight) - 1
   785  	if requestHead < 0 {
   786  		requestHead = 0
   787  	}
   788  	// requestBottom is the lowest block we want included in the query
   789  	// Ideally, we want to include the one just below our own head
   790  	requestBottom := int(localHeight - 1)
   791  	if requestBottom < 0 {
   792  		requestBottom = 0
   793  	}
   794  	totalSpan := requestHead - requestBottom
   795  	span := 1 + totalSpan/MaxCount
   796  	if span < 2 {
   797  		span = 2
   798  	}
   799  	if span > 16 {
   800  		span = 16
   801  	}
   802  
   803  	count = 1 + totalSpan/span
   804  	if count > MaxCount {
   805  		count = MaxCount
   806  	}
   807  	if count < 2 {
   808  		count = 2
   809  	}
   810  	from = requestHead - (count-1)*span
   811  	if from < 0 {
   812  		from = 0
   813  	}
   814  	max := from + (count-1)*span
   815  	return int64(from), count, span - 1, uint64(max)
   816  }
   817  
   818  // findAncestor tries to locate the common ancestor link of the local chain and
   819  // a remote peers blockchain. In the general case when our node was in sync and
   820  // on the correct chain, checking the top N links should already get us a match.
   821  // In the rare scenario when we ended up on a long reorganisation (i.e. none of
   822  // the head links match), we do a binary search to find the common ancestor.
   823  func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header) (uint64, error) {
   824  	// Figure out the valid ancestor range to prevent rewrite attacks
   825  	var (
   826  		floor        = int64(-1)
   827  		localHeight  uint64
   828  		remoteHeight = remoteHeader.Number.Uint64()
   829  	)
   830  	mode := d.getMode()
   831  	switch mode {
   832  	case FullSync:
   833  		localHeight = d.blockchain.CurrentBlock().NumberU64()
   834  	case FastSync:
   835  		localHeight = d.blockchain.CurrentFastBlock().NumberU64()
   836  	default:
   837  		localHeight = d.lightchain.CurrentHeader().Number.Uint64()
   838  	}
   839  	p.log.Debug("Looking for common ancestor", "local", localHeight, "remote", remoteHeight)
   840  
   841  	// Recap floor value for binary search
   842  	maxForkAncestry := fullMaxForkAncestry
   843  	if d.getMode() == LightSync {
   844  		maxForkAncestry = lightMaxForkAncestry
   845  	}
   846  	if localHeight >= maxForkAncestry {
   847  		// We're above the max reorg threshold, find the earliest fork point
   848  		floor = int64(localHeight - maxForkAncestry)
   849  	}
   850  	// If we're doing a light sync, ensure the floor doesn't go below the CHT, as
   851  	// all headers before that point will be missing.
   852  	if mode == LightSync {
   853  		// If we don't know the current CHT position, find it
   854  		if d.genesis == 0 {
   855  			header := d.lightchain.CurrentHeader()
   856  			for header != nil {
   857  				d.genesis = header.Number.Uint64()
   858  				if floor >= int64(d.genesis)-1 {
   859  					break
   860  				}
   861  				header = d.lightchain.GetHeaderByHash(header.ParentHash)
   862  			}
   863  		}
   864  		// We already know the "genesis" block number, cap floor to that
   865  		if floor < int64(d.genesis)-1 {
   866  			floor = int64(d.genesis) - 1
   867  		}
   868  	}
   869  
   870  	ancestor, err := d.findAncestorSpanSearch(p, mode, remoteHeight, localHeight, floor)
   871  	if err == nil {
   872  		return ancestor, nil
   873  	}
   874  	// The returned error was not nil.
   875  	// If the error returned does not reflect that a common ancestor was not found, return it.
   876  	// If the error reflects that a common ancestor was not found, continue to binary search,
   877  	// where the error value will be reassigned.
   878  	if !errors.Is(err, errNoAncestorFound) {
   879  		return 0, err
   880  	}
   881  
   882  	ancestor, err = d.findAncestorBinarySearch(p, mode, remoteHeight, floor)
   883  	if err != nil {
   884  		return 0, err
   885  	}
   886  	return ancestor, nil
   887  }
   888  
   889  func (d *Downloader) findAncestorSpanSearch(p *peerConnection, mode SyncMode, remoteHeight, localHeight uint64, floor int64) (commonAncestor uint64, err error) {
   890  	from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight)
   891  
   892  	p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip)
   893  	go p.peer.RequestHeadersByNumber(uint64(from), count, skip, false)
   894  
   895  	// Wait for the remote response to the head fetch
   896  	number, hash := uint64(0), common.Hash{}
   897  
   898  	ttl := d.requestTTL()
   899  	timeout := time.After(ttl)
   900  
   901  	for finished := false; !finished; {
   902  		select {
   903  		case <-d.cancelCh:
   904  			return 0, errCanceled
   905  
   906  		case packet := <-d.headerCh:
   907  			// Discard anything not from the origin peer
   908  			if packet.PeerId() != p.id {
   909  				log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
   910  				break
   911  			}
   912  			// Make sure the peer actually gave something valid
   913  			headers := packet.(*headerPack).headers
   914  			if len(headers) == 0 {
   915  				p.log.Warn("Empty head header set")
   916  				return 0, errEmptyHeaderSet
   917  			}
   918  			// Make sure the peer's reply conforms to the request
   919  			for i, header := range headers {
   920  				expectNumber := from + int64(i)*int64(skip+1)
   921  				if number := header.Number.Int64(); number != expectNumber {
   922  					p.log.Warn("Head headers broke chain ordering", "index", i, "requested", expectNumber, "received", number)
   923  					return 0, fmt.Errorf("%w: %v", errInvalidChain, errors.New("head headers broke chain ordering"))
   924  				}
   925  			}
   926  			// Check if a common ancestor was found
   927  			finished = true
   928  			for i := len(headers) - 1; i >= 0; i-- {
   929  				// Skip any headers that underflow/overflow our requested set
   930  				if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > max {
   931  					continue
   932  				}
   933  				// Otherwise check if we already know the header or not
   934  				h := headers[i].Hash()
   935  				n := headers[i].Number.Uint64()
   936  
   937  				var known bool
   938  				switch mode {
   939  				case FullSync:
   940  					known = d.blockchain.HasBlock(h, n)
   941  				case FastSync:
   942  					known = d.blockchain.HasFastBlock(h, n)
   943  				default:
   944  					known = d.lightchain.HasHeader(h, n)
   945  				}
   946  				if known {
   947  					number, hash = n, h
   948  					break
   949  				}
   950  			}
   951  
   952  		case <-timeout:
   953  			p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
   954  			return 0, errTimeout
   955  
   956  		case <-d.bodyCh:
   957  		case <-d.receiptCh:
   958  			// Out of bounds delivery, ignore
   959  		}
   960  	}
   961  	// If the head fetch already found an ancestor, return
   962  	if hash != (common.Hash{}) {
   963  		if int64(number) <= floor {
   964  			p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
   965  			return 0, errInvalidAncestor
   966  		}
   967  		p.log.Debug("Found common ancestor", "number", number, "hash", hash)
   968  		return number, nil
   969  	}
   970  	return 0, errNoAncestorFound
   971  }
   972  
   973  func (d *Downloader) findAncestorBinarySearch(p *peerConnection, mode SyncMode, remoteHeight uint64, floor int64) (commonAncestor uint64, err error) {
   974  	hash := common.Hash{}
   975  
   976  	// Ancestor not found, we need to binary search over our chain
   977  	start, end := uint64(0), remoteHeight
   978  	if floor > 0 {
   979  		start = uint64(floor)
   980  	}
   981  	p.log.Trace("Binary searching for common ancestor", "start", start, "end", end)
   982  
   983  	for start+1 < end {
   984  		// Split our chain interval in two, and request the hash to cross check
   985  		check := (start + end) / 2
   986  
   987  		ttl := d.requestTTL()
   988  		timeout := time.After(ttl)
   989  
   990  		go p.peer.RequestHeadersByNumber(check, 1, 0, false)
   991  
   992  		// Wait until a reply arrives to this request
   993  		for arrived := false; !arrived; {
   994  			select {
   995  			case <-d.cancelCh:
   996  				return 0, errCanceled
   997  
   998  			case packet := <-d.headerCh:
   999  				// Discard anything not from the origin peer
  1000  				if packet.PeerId() != p.id {
  1001  					log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
  1002  					break
  1003  				}
  1004  				// Make sure the peer actually gave something valid
  1005  				headers := packet.(*headerPack).headers
  1006  				if len(headers) != 1 {
  1007  					p.log.Warn("Multiple headers for single request", "headers", len(headers))
  1008  					return 0, fmt.Errorf("%w: multiple headers (%d) for single request", errBadPeer, len(headers))
  1009  				}
  1010  				arrived = true
  1011  
  1012  				// Modify the search interval based on the response
  1013  				h := headers[0].Hash()
  1014  				n := headers[0].Number.Uint64()
  1015  
  1016  				var known bool
  1017  				switch mode {
  1018  				case FullSync:
  1019  					known = d.blockchain.HasBlock(h, n)
  1020  				case FastSync:
  1021  					known = d.blockchain.HasFastBlock(h, n)
  1022  				default:
  1023  					known = d.lightchain.HasHeader(h, n)
  1024  				}
  1025  				if !known {
  1026  					end = check
  1027  					break
  1028  				}
  1029  				header := d.lightchain.GetHeaderByHash(h) // Independent of sync mode, header surely exists
  1030  				if header == nil {
  1031  					p.log.Error("header not found", "hash", h, "request", check)
  1032  					return 0, fmt.Errorf("%w: header no found (%s)", errBadPeer, h)
  1033  				}
  1034  				if header.Number.Uint64() != check {
  1035  					p.log.Warn("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
  1036  					return 0, fmt.Errorf("%w: non-requested header (%d)", errBadPeer, header.Number)
  1037  				}
  1038  				start = check
  1039  				hash = h
  1040  
  1041  			case <-timeout:
  1042  				p.log.Debug("Waiting for search header timed out", "elapsed", ttl)
  1043  				return 0, errTimeout
  1044  
  1045  			case <-d.bodyCh:
  1046  			case <-d.receiptCh:
  1047  				// Out of bounds delivery, ignore
  1048  			}
  1049  		}
  1050  	}
  1051  	// Ensure valid ancestry and return
  1052  	if int64(start) <= floor {
  1053  		p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
  1054  		return 0, errInvalidAncestor
  1055  	}
  1056  	p.log.Debug("Found common ancestor", "number", start, "hash", hash)
  1057  	return start, nil
  1058  }
  1059  
  1060  // fetchHeaders keeps retrieving headers concurrently from the number
  1061  // requested, until no more are returned, potentially throttling on the way. To
  1062  // facilitate concurrency but still protect against malicious nodes sending bad
  1063  // headers, we construct a header chain skeleton using the "origin" peer we are
  1064  // syncing with, and fill in the missing headers using anyone else. Headers from
  1065  // other peers are only accepted if they map cleanly to the skeleton. If no one
  1066  // can fill in the skeleton - not even the origin peer - it's assumed invalid and
  1067  // the origin is dropped.
  1068  func (d *Downloader) fetchHeaders(p *peerConnection, from uint64) error {
  1069  	p.log.Debug("Directing header downloads", "origin", from)
  1070  	defer p.log.Debug("Header download terminated")
  1071  
  1072  	// Create a timeout timer, and the associated header fetcher
  1073  	skeleton := true            // Skeleton assembly phase or finishing up
  1074  	pivoting := false           // Whether the next request is pivot verification
  1075  	request := time.Now()       // time of the last skeleton fetch request
  1076  	timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
  1077  	<-timeout.C                 // timeout channel should be initially empty
  1078  	defer timeout.Stop()
  1079  
  1080  	var ttl time.Duration
  1081  	getHeaders := func(from uint64) {
  1082  		request = time.Now()
  1083  
  1084  		ttl = d.requestTTL()
  1085  		timeout.Reset(ttl)
  1086  
  1087  		if skeleton {
  1088  			p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from)
  1089  			go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false)
  1090  		} else {
  1091  			p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from)
  1092  			go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false)
  1093  		}
  1094  	}
  1095  	getNextPivot := func() {
  1096  		pivoting = true
  1097  		request = time.Now()
  1098  
  1099  		ttl = d.requestTTL()
  1100  		timeout.Reset(ttl)
  1101  
  1102  		d.pivotLock.RLock()
  1103  		pivot := d.pivotHeader.Number.Uint64()
  1104  		d.pivotLock.RUnlock()
  1105  
  1106  		p.log.Trace("Fetching next pivot header", "number", pivot+uint64(fsMinFullBlocks))
  1107  		go p.peer.RequestHeadersByNumber(pivot+uint64(fsMinFullBlocks), 2, fsMinFullBlocks-9, false) // move +64 when it's 2x64-8 deep
  1108  	}
  1109  	// Start pulling the header chain skeleton until all is done
  1110  	ancestor := from
  1111  	getHeaders(from)
  1112  
  1113  	mode := d.getMode()
  1114  	for {
  1115  		select {
  1116  		case <-d.cancelCh:
  1117  			return errCanceled
  1118  
  1119  		case packet := <-d.headerCh:
  1120  			// Make sure the active peer is giving us the skeleton headers
  1121  			if packet.PeerId() != p.id {
  1122  				log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId())
  1123  				break
  1124  			}
  1125  			headerReqTimer.UpdateSince(request)
  1126  			timeout.Stop()
  1127  
  1128  			// If the pivot is being checked, move if it became stale and run the real retrieval
  1129  			var pivot uint64
  1130  
  1131  			d.pivotLock.RLock()
  1132  			if d.pivotHeader != nil {
  1133  				pivot = d.pivotHeader.Number.Uint64()
  1134  			}
  1135  			d.pivotLock.RUnlock()
  1136  
  1137  			if pivoting {
  1138  				if packet.Items() == 2 {
  1139  					// Retrieve the headers and do some sanity checks, just in case
  1140  					headers := packet.(*headerPack).headers
  1141  
  1142  					if have, want := headers[0].Number.Uint64(), pivot+uint64(fsMinFullBlocks); have != want {
  1143  						log.Warn("Peer sent invalid next pivot", "have", have, "want", want)
  1144  						return fmt.Errorf("%w: next pivot number %d != requested %d", errInvalidChain, have, want)
  1145  					}
  1146  					if have, want := headers[1].Number.Uint64(), pivot+2*uint64(fsMinFullBlocks)-8; have != want {
  1147  						log.Warn("Peer sent invalid pivot confirmer", "have", have, "want", want)
  1148  						return fmt.Errorf("%w: next pivot confirmer number %d != requested %d", errInvalidChain, have, want)
  1149  					}
  1150  					log.Warn("Pivot seemingly stale, moving", "old", pivot, "new", headers[0].Number)
  1151  					pivot = headers[0].Number.Uint64()
  1152  
  1153  					d.pivotLock.Lock()
  1154  					d.pivotHeader = headers[0]
  1155  					d.pivotLock.Unlock()
  1156  
  1157  					// Write out the pivot into the database so a rollback beyond
  1158  					// it will reenable fast sync and update the state root that
  1159  					// the state syncer will be downloading.
  1160  					rawdb.WriteLastPivotNumber(d.stateDB, pivot)
  1161  				}
  1162  				pivoting = false
  1163  				getHeaders(from)
  1164  				continue
  1165  			}
  1166  			// If the skeleton's finished, pull any remaining head headers directly from the origin
  1167  			if skeleton && packet.Items() == 0 {
  1168  				skeleton = false
  1169  				getHeaders(from)
  1170  				continue
  1171  			}
  1172  			// If no more headers are inbound, notify the content fetchers and return
  1173  			if packet.Items() == 0 {
  1174  				// Don't abort header fetches while the pivot is downloading
  1175  				if atomic.LoadInt32(&d.committed) == 0 && pivot <= from {
  1176  					p.log.Debug("No headers, waiting for pivot commit")
  1177  					select {
  1178  					case <-time.After(fsHeaderContCheck):
  1179  						getHeaders(from)
  1180  						continue
  1181  					case <-d.cancelCh:
  1182  						return errCanceled
  1183  					}
  1184  				}
  1185  				// Pivot done (or not in fast sync) and no more headers, terminate the process
  1186  				p.log.Debug("No more headers available")
  1187  				select {
  1188  				case d.headerProcCh <- nil:
  1189  					return nil
  1190  				case <-d.cancelCh:
  1191  					return errCanceled
  1192  				}
  1193  			}
  1194  			headers := packet.(*headerPack).headers
  1195  
  1196  			// If we received a skeleton batch, resolve internals concurrently
  1197  			if skeleton {
  1198  				filled, proced, err := d.fillHeaderSkeleton(from, headers)
  1199  				if err != nil {
  1200  					p.log.Debug("Skeleton chain invalid", "err", err)
  1201  					return fmt.Errorf("%w: %v", errInvalidChain, err)
  1202  				}
  1203  				headers = filled[proced:]
  1204  				from += uint64(proced)
  1205  			} else {
  1206  				// If we're closing in on the chain head, but haven't yet reached it, delay
  1207  				// the last few headers so mini reorgs on the head don't cause invalid hash
  1208  				// chain errors.
  1209  				if n := len(headers); n > 0 {
  1210  					// Retrieve the current head we're at
  1211  					var head uint64
  1212  					if mode == LightSync {
  1213  						head = d.lightchain.CurrentHeader().Number.Uint64()
  1214  					} else {
  1215  						head = d.blockchain.CurrentFastBlock().NumberU64()
  1216  						if full := d.blockchain.CurrentBlock().NumberU64(); head < full {
  1217  							head = full
  1218  						}
  1219  					}
  1220  					// If the head is below the common ancestor, we're actually deduplicating
  1221  					// already existing chain segments, so use the ancestor as the fake head.
  1222  					// Otherwise we might end up delaying header deliveries pointlessly.
  1223  					if head < ancestor {
  1224  						head = ancestor
  1225  					}
  1226  					// If the head is way older than this batch, delay the last few headers
  1227  					if head+uint64(reorgProtThreshold) < headers[n-1].Number.Uint64() {
  1228  						delay := reorgProtHeaderDelay
  1229  						if delay > n {
  1230  							delay = n
  1231  						}
  1232  						headers = headers[:n-delay]
  1233  					}
  1234  				}
  1235  			}
  1236  			// Insert all the new headers and fetch the next batch
  1237  			if len(headers) > 0 {
  1238  				p.log.Trace("Scheduling new headers", "count", len(headers), "from", from)
  1239  				select {
  1240  				case d.headerProcCh <- headers:
  1241  				case <-d.cancelCh:
  1242  					return errCanceled
  1243  				}
  1244  				from += uint64(len(headers))
  1245  
  1246  				// If we're still skeleton filling fast sync, check pivot staleness
  1247  				// before continuing to the next skeleton filling
  1248  				if skeleton && pivot > 0 {
  1249  					getNextPivot()
  1250  				} else {
  1251  					getHeaders(from)
  1252  				}
  1253  			} else {
  1254  				// No headers delivered, or all of them being delayed, sleep a bit and retry
  1255  				p.log.Trace("All headers delayed, waiting")
  1256  				select {
  1257  				case <-time.After(fsHeaderContCheck):
  1258  					getHeaders(from)
  1259  					continue
  1260  				case <-d.cancelCh:
  1261  					return errCanceled
  1262  				}
  1263  			}
  1264  
  1265  		case <-timeout.C:
  1266  			if d.dropPeer == nil {
  1267  				// The dropPeer method is nil when `--copydb` is used for a local copy.
  1268  				// Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  1269  				p.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", p.id)
  1270  				break
  1271  			}
  1272  			// Header retrieval timed out, consider the peer bad and drop
  1273  			p.log.Debug("Header request timed out", "elapsed", ttl)
  1274  			headerTimeoutMeter.Mark(1)
  1275  			d.dropPeer(p.id)
  1276  
  1277  			// Finish the sync gracefully instead of dumping the gathered data though
  1278  			for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1279  				select {
  1280  				case ch <- false:
  1281  				case <-d.cancelCh:
  1282  				}
  1283  			}
  1284  			select {
  1285  			case d.headerProcCh <- nil:
  1286  			case <-d.cancelCh:
  1287  			}
  1288  			return fmt.Errorf("%w: header request timed out", errBadPeer)
  1289  		}
  1290  	}
  1291  }
  1292  
  1293  // fillHeaderSkeleton concurrently retrieves headers from all our available peers
  1294  // and maps them to the provided skeleton header chain.
  1295  //
  1296  // Any partial results from the beginning of the skeleton is (if possible) forwarded
  1297  // immediately to the header processor to keep the rest of the pipeline full even
  1298  // in the case of header stalls.
  1299  //
  1300  // The method returns the entire filled skeleton and also the number of headers
  1301  // already forwarded for processing.
  1302  func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) {
  1303  	log.Debug("Filling up skeleton", "from", from)
  1304  	d.queue.ScheduleSkeleton(from, skeleton)
  1305  
  1306  	var (
  1307  		deliver = func(packet dataPack) (int, error) {
  1308  			pack := packet.(*headerPack)
  1309  			return d.queue.DeliverHeaders(pack.peerID, pack.headers, d.headerProcCh)
  1310  		}
  1311  		expire  = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) }
  1312  		reserve = func(p *peerConnection, count int) (*fetchRequest, bool, bool) {
  1313  			return d.queue.ReserveHeaders(p, count), false, false
  1314  		}
  1315  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) }
  1316  		capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) }
  1317  		setIdle  = func(p *peerConnection, accepted int, deliveryTime time.Time) {
  1318  			p.SetHeadersIdle(accepted, deliveryTime)
  1319  		}
  1320  	)
  1321  	err := d.fetchParts(d.headerCh, deliver, d.queue.headerContCh, expire,
  1322  		d.queue.PendingHeaders, d.queue.InFlightHeaders, reserve,
  1323  		nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers")
  1324  
  1325  	log.Debug("Skeleton fill terminated", "err", err)
  1326  
  1327  	filled, proced := d.queue.RetrieveHeaders()
  1328  	return filled, proced, err
  1329  }
  1330  
  1331  // fetchBodies iteratively downloads the scheduled block bodies, taking any
  1332  // available peers, reserving a chunk of blocks for each, waiting for delivery
  1333  // and also periodically checking for timeouts.
  1334  func (d *Downloader) fetchBodies(from uint64) error {
  1335  	log.Debug("Downloading block bodies", "origin", from)
  1336  
  1337  	var (
  1338  		deliver = func(packet dataPack) (int, error) {
  1339  			pack := packet.(*bodyPack)
  1340  			return d.queue.DeliverBodies(pack.peerID, pack.transactions, pack.uncles)
  1341  		}
  1342  		expire   = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) }
  1343  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) }
  1344  		capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) }
  1345  		setIdle  = func(p *peerConnection, accepted int, deliveryTime time.Time) { p.SetBodiesIdle(accepted, deliveryTime) }
  1346  	)
  1347  	err := d.fetchParts(d.bodyCh, deliver, d.bodyWakeCh, expire,
  1348  		d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ReserveBodies,
  1349  		d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies")
  1350  
  1351  	log.Debug("Block body download terminated", "err", err)
  1352  	return err
  1353  }
  1354  
  1355  // fetchReceipts iteratively downloads the scheduled block receipts, taking any
  1356  // available peers, reserving a chunk of receipts for each, waiting for delivery
  1357  // and also periodically checking for timeouts.
  1358  func (d *Downloader) fetchReceipts(from uint64) error {
  1359  	log.Debug("Downloading transaction receipts", "origin", from)
  1360  
  1361  	var (
  1362  		deliver = func(packet dataPack) (int, error) {
  1363  			pack := packet.(*receiptPack)
  1364  			return d.queue.DeliverReceipts(pack.peerID, pack.receipts)
  1365  		}
  1366  		expire   = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) }
  1367  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) }
  1368  		capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) }
  1369  		setIdle  = func(p *peerConnection, accepted int, deliveryTime time.Time) {
  1370  			p.SetReceiptsIdle(accepted, deliveryTime)
  1371  		}
  1372  	)
  1373  	err := d.fetchParts(d.receiptCh, deliver, d.receiptWakeCh, expire,
  1374  		d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ReserveReceipts,
  1375  		d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts")
  1376  
  1377  	log.Debug("Transaction receipt download terminated", "err", err)
  1378  	return err
  1379  }
  1380  
  1381  // fetchParts iteratively downloads scheduled block parts, taking any available
  1382  // peers, reserving a chunk of fetch requests for each, waiting for delivery and
  1383  // also periodically checking for timeouts.
  1384  //
  1385  // As the scheduling/timeout logic mostly is the same for all downloaded data
  1386  // types, this method is used by each for data gathering and is instrumented with
  1387  // various callbacks to handle the slight differences between processing them.
  1388  //
  1389  // The instrumentation parameters:
  1390  //  - errCancel:   error type to return if the fetch operation is cancelled (mostly makes logging nicer)
  1391  //  - deliveryCh:  channel from which to retrieve downloaded data packets (merged from all concurrent peers)
  1392  //  - deliver:     processing callback to deliver data packets into type specific download queues (usually within `queue`)
  1393  //  - wakeCh:      notification channel for waking the fetcher when new tasks are available (or sync completed)
  1394  //  - expire:      task callback method to abort requests that took too long and return the faulty peers (traffic shaping)
  1395  //  - pending:     task callback for the number of requests still needing download (detect completion/non-completability)
  1396  //  - inFlight:    task callback for the number of in-progress requests (wait for all active downloads to finish)
  1397  //  - throttle:    task callback to check if the processing queue is full and activate throttling (bound memory use)
  1398  //  - reserve:     task callback to reserve new download tasks to a particular peer (also signals partial completions)
  1399  //  - fetchHook:   tester callback to notify of new tasks being initiated (allows testing the scheduling logic)
  1400  //  - fetch:       network callback to actually send a particular download request to a physical remote peer
  1401  //  - cancel:      task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer)
  1402  //  - capacity:    network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping)
  1403  //  - idle:        network callback to retrieve the currently (type specific) idle peers that can be assigned tasks
  1404  //  - setIdle:     network callback to set a peer back to idle and update its estimated capacity (traffic shaping)
  1405  //  - kind:        textual label of the type being downloaded to display in log messages
  1406  func (d *Downloader) fetchParts(deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool,
  1407  	expire func() map[string]int, pending func() int, inFlight func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, bool),
  1408  	fetchHook func([]*types.Header, ...interface{}), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
  1409  	idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int, time.Time), kind string) error {
  1410  
  1411  	// Create a ticker to detect expired retrieval tasks
  1412  	ticker := time.NewTicker(100 * time.Millisecond)
  1413  	defer ticker.Stop()
  1414  
  1415  	update := make(chan struct{}, 1)
  1416  
  1417  	// Prepare the queue and fetch block parts until the block header fetcher's done
  1418  	finished := false
  1419  	for {
  1420  		select {
  1421  		case <-d.cancelCh:
  1422  			return errCanceled
  1423  
  1424  		case packet := <-deliveryCh:
  1425  			deliveryTime := time.Now()
  1426  			// If the peer was previously banned and failed to deliver its pack
  1427  			// in a reasonable time frame, ignore its message.
  1428  			if peer := d.peers.Peer(packet.PeerId()); peer != nil {
  1429  				// Deliver the received chunk of data and check chain validity
  1430  				accepted, err := deliver(packet)
  1431  				if errors.Is(err, errInvalidChain) {
  1432  					return err
  1433  				}
  1434  				// Unless a peer delivered something completely else than requested (usually
  1435  				// caused by a timed out request which came through in the end), set it to
  1436  				// idle. If the delivery's stale, the peer should have already been idled.
  1437  				if !errors.Is(err, errStaleDelivery) {
  1438  					setIdle(peer, accepted, deliveryTime)
  1439  				}
  1440  				// Issue a log to the user to see what's going on
  1441  				switch {
  1442  				case err == nil && packet.Items() == 0:
  1443  					peer.log.Trace("Requested data not delivered", "type", kind)
  1444  				case err == nil:
  1445  					peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats())
  1446  				default:
  1447  					peer.log.Debug("Failed to deliver retrieved data", "type", kind, "err", err)
  1448  				}
  1449  			}
  1450  			// Blocks assembled, try to update the progress
  1451  			select {
  1452  			case update <- struct{}{}:
  1453  			default:
  1454  			}
  1455  
  1456  		case cont := <-wakeCh:
  1457  			// The header fetcher sent a continuation flag, check if it's done
  1458  			if !cont {
  1459  				finished = true
  1460  			}
  1461  			// Headers arrive, try to update the progress
  1462  			select {
  1463  			case update <- struct{}{}:
  1464  			default:
  1465  			}
  1466  
  1467  		case <-ticker.C:
  1468  			// Sanity check update the progress
  1469  			select {
  1470  			case update <- struct{}{}:
  1471  			default:
  1472  			}
  1473  
  1474  		case <-update:
  1475  			// Short circuit if we lost all our peers
  1476  			if d.peers.Len() == 0 {
  1477  				return errNoPeers
  1478  			}
  1479  			// Check for fetch request timeouts and demote the responsible peers
  1480  			for pid, fails := range expire() {
  1481  				if peer := d.peers.Peer(pid); peer != nil {
  1482  					// If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps
  1483  					// ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times
  1484  					// out that sync wise we need to get rid of the peer.
  1485  					//
  1486  					// The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth
  1487  					// and latency of a peer separately, which requires pushing the measures capacity a bit and seeing
  1488  					// how response times reacts, to it always requests one more than the minimum (i.e. min 2).
  1489  					if fails > 2 {
  1490  						peer.log.Trace("Data delivery timed out", "type", kind)
  1491  						setIdle(peer, 0, time.Now())
  1492  					} else {
  1493  						peer.log.Debug("Stalling delivery, dropping", "type", kind)
  1494  
  1495  						if d.dropPeer == nil {
  1496  							// The dropPeer method is nil when `--copydb` is used for a local copy.
  1497  							// Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  1498  							peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", pid)
  1499  						} else {
  1500  							d.dropPeer(pid)
  1501  
  1502  							// If this peer was the master peer, abort sync immediately
  1503  							d.cancelLock.RLock()
  1504  							master := pid == d.cancelPeer
  1505  							d.cancelLock.RUnlock()
  1506  
  1507  							if master {
  1508  								d.cancel()
  1509  								return errTimeout
  1510  							}
  1511  						}
  1512  					}
  1513  				}
  1514  			}
  1515  			// If there's nothing more to fetch, wait or terminate
  1516  			if pending() == 0 {
  1517  				if !inFlight() && finished {
  1518  					log.Debug("Data fetching completed", "type", kind)
  1519  					return nil
  1520  				}
  1521  				break
  1522  			}
  1523  			// Send a download request to all idle peers, until throttled
  1524  			progressed, throttled, running := false, false, inFlight()
  1525  			idles, total := idle()
  1526  			pendCount := pending()
  1527  			for _, peer := range idles {
  1528  				// Short circuit if throttling activated
  1529  				if throttled {
  1530  					break
  1531  				}
  1532  				// Short circuit if there is no more available task.
  1533  				if pendCount = pending(); pendCount == 0 {
  1534  					break
  1535  				}
  1536  				// Reserve a chunk of fetches for a peer. A nil can mean either that
  1537  				// no more headers are available, or that the peer is known not to
  1538  				// have them.
  1539  				request, progress, throttle := reserve(peer, capacity(peer))
  1540  				if progress {
  1541  					progressed = true
  1542  				}
  1543  				if throttle {
  1544  					throttled = true
  1545  					throttleCounter.Inc(1)
  1546  				}
  1547  				if request == nil {
  1548  					continue
  1549  				}
  1550  				if request.From > 0 {
  1551  					peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From)
  1552  				} else {
  1553  					peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number)
  1554  				}
  1555  				// Fetch the chunk and make sure any errors return the hashes to the queue
  1556  				if fetchHook != nil {
  1557  					fetchHook(request.Headers, d.getMode(), peer.id)
  1558  				}
  1559  				if err := fetch(peer, request); err != nil {
  1560  					// Although we could try and make an attempt to fix this, this error really
  1561  					// means that we've double allocated a fetch task to a peer. If that is the
  1562  					// case, the internal state of the downloader and the queue is very wrong so
  1563  					// better hard crash and note the error instead of silently accumulating into
  1564  					// a much bigger issue.
  1565  					panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind))
  1566  				}
  1567  				running = true
  1568  			}
  1569  			// Make sure that we have peers available for fetching. If all peers have been tried
  1570  			// and all failed throw an error
  1571  			if !progressed && !throttled && !running && len(idles) == total && pendCount > 0 {
  1572  				return errPeersUnavailable
  1573  			}
  1574  		}
  1575  	}
  1576  }
  1577  
  1578  // processHeaders takes batches of retrieved headers from an input channel and
  1579  // keeps processing and scheduling them into the header chain and downloader's
  1580  // queue until the stream ends or a failure occurs.
  1581  func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
  1582  	// Keep a count of uncertain headers to roll back
  1583  	var (
  1584  		rollback    uint64 // Zero means no rollback (fine as you can't unroll the genesis)
  1585  		rollbackErr error
  1586  		mode        = d.getMode()
  1587  	)
  1588  	defer func() {
  1589  		if rollback > 0 {
  1590  			lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0
  1591  			if mode != LightSync {
  1592  				lastFastBlock = d.blockchain.CurrentFastBlock().Number()
  1593  				lastBlock = d.blockchain.CurrentBlock().Number()
  1594  			}
  1595  			if err := d.lightchain.SetHead(rollback - 1); err != nil { // -1 to target the parent of the first uncertain block
  1596  				// We're already unwinding the stack, only print the error to make it more visible
  1597  				log.Error("Failed to roll back chain segment", "head", rollback-1, "err", err)
  1598  			}
  1599  			curFastBlock, curBlock := common.Big0, common.Big0
  1600  			if mode != LightSync {
  1601  				curFastBlock = d.blockchain.CurrentFastBlock().Number()
  1602  				curBlock = d.blockchain.CurrentBlock().Number()
  1603  			}
  1604  			log.Warn("Rolled back chain segment",
  1605  				"header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number),
  1606  				"fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock),
  1607  				"block", fmt.Sprintf("%d->%d", lastBlock, curBlock), "reason", rollbackErr)
  1608  		}
  1609  	}()
  1610  	// Wait for batches of headers to process
  1611  	gotHeaders := false
  1612  
  1613  	for {
  1614  		select {
  1615  		case <-d.cancelCh:
  1616  			rollbackErr = errCanceled
  1617  			return errCanceled
  1618  
  1619  		case headers := <-d.headerProcCh:
  1620  			// Terminate header processing if we synced up
  1621  			if len(headers) == 0 {
  1622  				// Notify everyone that headers are fully processed
  1623  				for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1624  					select {
  1625  					case ch <- false:
  1626  					case <-d.cancelCh:
  1627  					}
  1628  				}
  1629  				// If no headers were retrieved at all, the peer violated its TD promise that it had a
  1630  				// better chain compared to ours. The only exception is if its promised blocks were
  1631  				// already imported by other means (e.g. fetcher):
  1632  				//
  1633  				// R <remote peer>, L <local node>: Both at block 10
  1634  				// R: Mine block 11, and propagate it to L
  1635  				// L: Queue block 11 for import
  1636  				// L: Notice that R's head and TD increased compared to ours, start sync
  1637  				// L: Import of block 11 finishes
  1638  				// L: Sync begins, and finds common ancestor at 11
  1639  				// L: Request new headers up from 11 (R's TD was higher, it must have something)
  1640  				// R: Nothing to give
  1641  				if mode != LightSync {
  1642  					head := d.blockchain.CurrentBlock()
  1643  					if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 {
  1644  						return errStallingPeer
  1645  					}
  1646  				}
  1647  				// If fast or light syncing, ensure promised headers are indeed delivered. This is
  1648  				// needed to detect scenarios where an attacker feeds a bad pivot and then bails out
  1649  				// of delivering the post-pivot blocks that would flag the invalid content.
  1650  				//
  1651  				// This check cannot be executed "as is" for full imports, since blocks may still be
  1652  				// queued for processing when the header download completes. However, as long as the
  1653  				// peer gave us something useful, we're already happy/progressed (above check).
  1654  				if mode == FastSync || mode == LightSync {
  1655  					head := d.lightchain.CurrentHeader()
  1656  					if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 {
  1657  						return errStallingPeer
  1658  					}
  1659  				}
  1660  				// Disable any rollback and return
  1661  				rollback = 0
  1662  				return nil
  1663  			}
  1664  			// Otherwise split the chunk of headers into batches and process them
  1665  			gotHeaders = true
  1666  			for len(headers) > 0 {
  1667  				// Terminate if something failed in between processing chunks
  1668  				select {
  1669  				case <-d.cancelCh:
  1670  					rollbackErr = errCanceled
  1671  					return errCanceled
  1672  				default:
  1673  				}
  1674  				// Select the next chunk of headers to import
  1675  				limit := maxHeadersProcess
  1676  				if limit > len(headers) {
  1677  					limit = len(headers)
  1678  				}
  1679  				chunk := headers[:limit]
  1680  
  1681  				// In case of header only syncing, validate the chunk immediately
  1682  				if mode == FastSync || mode == LightSync {
  1683  					// If we're importing pure headers, verify based on their recentness
  1684  					var pivot uint64
  1685  
  1686  					d.pivotLock.RLock()
  1687  					if d.pivotHeader != nil {
  1688  						pivot = d.pivotHeader.Number.Uint64()
  1689  					}
  1690  					d.pivotLock.RUnlock()
  1691  
  1692  					frequency := fsHeaderCheckFrequency
  1693  					if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot {
  1694  						frequency = 1
  1695  					}
  1696  					if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil {
  1697  						rollbackErr = err
  1698  
  1699  						// If some headers were inserted, track them as uncertain
  1700  						if (mode == FastSync || frequency > 1) && n > 0 && rollback == 0 {
  1701  							rollback = chunk[0].Number.Uint64()
  1702  						}
  1703  						log.Warn("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "parent", chunk[n].ParentHash, "err", err)
  1704  						return fmt.Errorf("%w: %v", errInvalidChain, err)
  1705  					}
  1706  					// All verifications passed, track all headers within the alloted limits
  1707  					if mode == FastSync {
  1708  						head := chunk[len(chunk)-1].Number.Uint64()
  1709  						if head-rollback > uint64(fsHeaderSafetyNet) {
  1710  							rollback = head - uint64(fsHeaderSafetyNet)
  1711  						} else {
  1712  							rollback = 1
  1713  						}
  1714  					}
  1715  				}
  1716  				// Unless we're doing light chains, schedule the headers for associated content retrieval
  1717  				if mode == FullSync || mode == FastSync {
  1718  					// If we've reached the allowed number of pending headers, stall a bit
  1719  					for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
  1720  						select {
  1721  						case <-d.cancelCh:
  1722  							rollbackErr = errCanceled
  1723  							return errCanceled
  1724  						case <-time.After(time.Second):
  1725  						}
  1726  					}
  1727  					// Otherwise insert the headers for content retrieval
  1728  					inserts := d.queue.Schedule(chunk, origin)
  1729  					if len(inserts) != len(chunk) {
  1730  						rollbackErr = fmt.Errorf("stale headers: len inserts %v len(chunk) %v", len(inserts), len(chunk))
  1731  						return fmt.Errorf("%w: stale headers", errBadPeer)
  1732  					}
  1733  				}
  1734  				headers = headers[limit:]
  1735  				origin += uint64(limit)
  1736  			}
  1737  			// Update the highest block number we know if a higher one is found.
  1738  			d.syncStatsLock.Lock()
  1739  			if d.syncStatsChainHeight < origin {
  1740  				d.syncStatsChainHeight = origin - 1
  1741  			}
  1742  			d.syncStatsLock.Unlock()
  1743  
  1744  			// Signal the content downloaders of the availablility of new tasks
  1745  			for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1746  				select {
  1747  				case ch <- true:
  1748  				default:
  1749  				}
  1750  			}
  1751  		}
  1752  	}
  1753  }
  1754  
  1755  // processFullSyncContent takes fetch results from the queue and imports them into the chain.
  1756  func (d *Downloader) processFullSyncContent() error {
  1757  	for {
  1758  		results := d.queue.Results(true)
  1759  		if len(results) == 0 {
  1760  			return nil
  1761  		}
  1762  		if d.chainInsertHook != nil {
  1763  			d.chainInsertHook(results)
  1764  		}
  1765  		if err := d.importBlockResults(results); err != nil {
  1766  			return err
  1767  		}
  1768  	}
  1769  }
  1770  
  1771  func (d *Downloader) importBlockResults(results []*fetchResult) error {
  1772  	// Check for any early termination requests
  1773  	if len(results) == 0 {
  1774  		return nil
  1775  	}
  1776  	select {
  1777  	case <-d.quitCh:
  1778  		return errCancelContentProcessing
  1779  	default:
  1780  	}
  1781  	// Retrieve the a batch of results to import
  1782  	first, last := results[0].Header, results[len(results)-1].Header
  1783  	log.Debug("Inserting downloaded chain", "items", len(results),
  1784  		"firstnum", first.Number, "firsthash", first.Hash(),
  1785  		"lastnum", last.Number, "lasthash", last.Hash(),
  1786  	)
  1787  	blocks := make([]*types.Block, len(results))
  1788  	for i, result := range results {
  1789  		blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1790  	}
  1791  	if index, err := d.blockchain.InsertChain(blocks); err != nil {
  1792  		if index < len(results) {
  1793  			log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1794  		} else {
  1795  			// The InsertChain method in blockchain.go will sometimes return an out-of-bounds index,
  1796  			// when it needs to preprocess blocks to import a sidechain.
  1797  			// The importer will put together a new list of blocks to import, which is a superset
  1798  			// of the blocks delivered from the downloader, and the indexing will be off.
  1799  			log.Debug("Downloaded item processing failed on sidechain import", "index", index, "err", err)
  1800  		}
  1801  		return fmt.Errorf("%w: %v", errInvalidChain, err)
  1802  	}
  1803  	return nil
  1804  }
  1805  
  1806  // processFastSyncContent takes fetch results from the queue and writes them to the
  1807  // database. It also controls the synchronisation of state nodes of the pivot block.
  1808  func (d *Downloader) processFastSyncContent() error {
  1809  	// Start syncing state of the reported head block. This should get us most of
  1810  	// the state of the pivot block.
  1811  	d.pivotLock.RLock()
  1812  	sync := d.syncState(d.pivotHeader.Root)
  1813  	d.pivotLock.RUnlock()
  1814  
  1815  	defer func() {
  1816  		// The `sync` object is replaced every time the pivot moves. We need to
  1817  		// defer close the very last active one, hence the lazy evaluation vs.
  1818  		// calling defer sync.Cancel() !!!
  1819  		sync.Cancel()
  1820  	}()
  1821  
  1822  	closeOnErr := func(s *stateSync) {
  1823  		if err := s.Wait(); err != nil && err != errCancelStateFetch && err != errCanceled && err != snap.ErrCancelled {
  1824  			d.queue.Close() // wake up Results
  1825  		}
  1826  	}
  1827  	go closeOnErr(sync)
  1828  
  1829  	// To cater for moving pivot points, track the pivot block and subsequently
  1830  	// accumulated download results separately.
  1831  	var (
  1832  		oldPivot *fetchResult   // Locked in pivot block, might change eventually
  1833  		oldTail  []*fetchResult // Downloaded content after the pivot
  1834  	)
  1835  	for {
  1836  		// Wait for the next batch of downloaded data to be available, and if the pivot
  1837  		// block became stale, move the goalpost
  1838  		results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness
  1839  		if len(results) == 0 {
  1840  			// If pivot sync is done, stop
  1841  			if oldPivot == nil {
  1842  				return sync.Cancel()
  1843  			}
  1844  			// If sync failed, stop
  1845  			select {
  1846  			case <-d.cancelCh:
  1847  				sync.Cancel()
  1848  				return errCanceled
  1849  			default:
  1850  			}
  1851  		}
  1852  		if d.chainInsertHook != nil {
  1853  			d.chainInsertHook(results)
  1854  		}
  1855  		// If we haven't downloaded the pivot block yet, check pivot staleness
  1856  		// notifications from the header downloader
  1857  		d.pivotLock.RLock()
  1858  		pivot := d.pivotHeader
  1859  		d.pivotLock.RUnlock()
  1860  
  1861  		if oldPivot == nil {
  1862  			if pivot.Root != sync.root {
  1863  				sync.Cancel()
  1864  				sync = d.syncState(pivot.Root)
  1865  
  1866  				go closeOnErr(sync)
  1867  			}
  1868  		} else {
  1869  			results = append(append([]*fetchResult{oldPivot}, oldTail...), results...)
  1870  		}
  1871  		// Split around the pivot block and process the two sides via fast/full sync
  1872  		if atomic.LoadInt32(&d.committed) == 0 {
  1873  			latest := results[len(results)-1].Header
  1874  			// If the height is above the pivot block by 2 sets, it means the pivot
  1875  			// become stale in the network and it was garbage collected, move to a
  1876  			// new pivot.
  1877  			//
  1878  			// Note, we have `reorgProtHeaderDelay` number of blocks withheld, Those
  1879  			// need to be taken into account, otherwise we're detecting the pivot move
  1880  			// late and will drop peers due to unavailable state!!!
  1881  			if height := latest.Number.Uint64(); height >= pivot.Number.Uint64()+2*uint64(fsMinFullBlocks)-uint64(reorgProtHeaderDelay) {
  1882  				log.Warn("Pivot became stale, moving", "old", pivot.Number.Uint64(), "new", height-uint64(fsMinFullBlocks)+uint64(reorgProtHeaderDelay))
  1883  				pivot = results[len(results)-1-fsMinFullBlocks+reorgProtHeaderDelay].Header // must exist as lower old pivot is uncommitted
  1884  
  1885  				d.pivotLock.Lock()
  1886  				d.pivotHeader = pivot
  1887  				d.pivotLock.Unlock()
  1888  
  1889  				// Write out the pivot into the database so a rollback beyond it will
  1890  				// reenable fast sync
  1891  				rawdb.WriteLastPivotNumber(d.stateDB, pivot.Number.Uint64())
  1892  			}
  1893  		}
  1894  		P, beforeP, afterP := splitAroundPivot(pivot.Number.Uint64(), results)
  1895  		if err := d.commitFastSyncData(beforeP, sync); err != nil {
  1896  			return err
  1897  		}
  1898  		if P != nil {
  1899  			// If new pivot block found, cancel old state retrieval and restart
  1900  			if oldPivot != P {
  1901  				sync.Cancel()
  1902  				sync = d.syncState(P.Header.Root)
  1903  
  1904  				go closeOnErr(sync)
  1905  				oldPivot = P
  1906  			}
  1907  			// Wait for completion, occasionally checking for pivot staleness
  1908  			select {
  1909  			case <-sync.done:
  1910  				if sync.err != nil {
  1911  					return sync.err
  1912  				}
  1913  				if err := d.commitPivotBlock(P); err != nil {
  1914  					return err
  1915  				}
  1916  				oldPivot = nil
  1917  
  1918  			case <-time.After(time.Second):
  1919  				oldTail = afterP
  1920  				continue
  1921  			}
  1922  		}
  1923  		// Fast sync done, pivot commit done, full import
  1924  		if err := d.importBlockResults(afterP); err != nil {
  1925  			return err
  1926  		}
  1927  	}
  1928  }
  1929  
  1930  func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) {
  1931  	if len(results) == 0 {
  1932  		return nil, nil, nil
  1933  	}
  1934  	if lastNum := results[len(results)-1].Header.Number.Uint64(); lastNum < pivot {
  1935  		// the pivot is somewhere in the future
  1936  		return nil, results, nil
  1937  	}
  1938  	// This can also be optimized, but only happens very seldom
  1939  	for _, result := range results {
  1940  		num := result.Header.Number.Uint64()
  1941  		switch {
  1942  		case num < pivot:
  1943  			before = append(before, result)
  1944  		case num == pivot:
  1945  			p = result
  1946  		default:
  1947  			after = append(after, result)
  1948  		}
  1949  	}
  1950  	return p, before, after
  1951  }
  1952  
  1953  func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error {
  1954  	// Check for any early termination requests
  1955  	if len(results) == 0 {
  1956  		return nil
  1957  	}
  1958  	select {
  1959  	case <-d.quitCh:
  1960  		return errCancelContentProcessing
  1961  	case <-stateSync.done:
  1962  		if err := stateSync.Wait(); err != nil {
  1963  			return err
  1964  		}
  1965  	default:
  1966  	}
  1967  	// Retrieve the a batch of results to import
  1968  	first, last := results[0].Header, results[len(results)-1].Header
  1969  	log.Debug("Inserting fast-sync blocks", "items", len(results),
  1970  		"firstnum", first.Number, "firsthash", first.Hash(),
  1971  		"lastnumn", last.Number, "lasthash", last.Hash(),
  1972  	)
  1973  	blocks := make([]*types.Block, len(results))
  1974  	receipts := make([]types.Receipts, len(results))
  1975  	for i, result := range results {
  1976  		blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1977  		receipts[i] = result.Receipts
  1978  	}
  1979  	if index, err := d.blockchain.InsertReceiptChain(blocks, receipts, d.ancientLimit); err != nil {
  1980  		log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1981  		return fmt.Errorf("%w: %v", errInvalidChain, err)
  1982  	}
  1983  	return nil
  1984  }
  1985  
  1986  func (d *Downloader) commitPivotBlock(result *fetchResult) error {
  1987  	block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1988  	log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
  1989  
  1990  	// Commit the pivot block as the new head, will require full sync from here on
  1991  	if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}, d.ancientLimit); err != nil {
  1992  		return err
  1993  	}
  1994  	if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil {
  1995  		return err
  1996  	}
  1997  	atomic.StoreInt32(&d.committed, 1)
  1998  
  1999  	// If we had a bloom filter for the state sync, deallocate it now. Note, we only
  2000  	// deallocate internally, but keep the empty wrapper. This ensures that if we do
  2001  	// a rollback after committing the pivot and restarting fast sync, we don't end
  2002  	// up using a nil bloom. Empty bloom is fine, it just returns that it does not
  2003  	// have the info we need, so reach down to the database instead.
  2004  	if d.stateBloom != nil {
  2005  		d.stateBloom.Close()
  2006  	}
  2007  	return nil
  2008  }
  2009  
  2010  // DeliverHeaders injects a new batch of block headers received from a remote
  2011  // node into the download schedule.
  2012  func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) error {
  2013  	return d.deliver(d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
  2014  }
  2015  
  2016  // DeliverBodies injects a new batch of block bodies received from a remote node.
  2017  func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) error {
  2018  	return d.deliver(d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
  2019  }
  2020  
  2021  // DeliverReceipts injects a new batch of receipts received from a remote node.
  2022  func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) error {
  2023  	return d.deliver(d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
  2024  }
  2025  
  2026  // DeliverNodeData injects a new batch of node state data received from a remote node.
  2027  func (d *Downloader) DeliverNodeData(id string, data [][]byte) error {
  2028  	return d.deliver(d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter)
  2029  }
  2030  
  2031  // DeliverSnapPacket is invoked from a peer's message handler when it transmits a
  2032  // data packet for the local node to consume.
  2033  func (d *Downloader) DeliverSnapPacket(peer *snap.Peer, packet snap.Packet) error {
  2034  	switch packet := packet.(type) {
  2035  	case *snap.AccountRangePacket:
  2036  		hashes, accounts, err := packet.Unpack()
  2037  		if err != nil {
  2038  			return err
  2039  		}
  2040  		return d.SnapSyncer.OnAccounts(peer, packet.ID, hashes, accounts, packet.Proof)
  2041  
  2042  	case *snap.StorageRangesPacket:
  2043  		hashset, slotset := packet.Unpack()
  2044  		return d.SnapSyncer.OnStorage(peer, packet.ID, hashset, slotset, packet.Proof)
  2045  
  2046  	case *snap.ByteCodesPacket:
  2047  		return d.SnapSyncer.OnByteCodes(peer, packet.ID, packet.Codes)
  2048  
  2049  	case *snap.TrieNodesPacket:
  2050  		return d.SnapSyncer.OnTrieNodes(peer, packet.ID, packet.Nodes)
  2051  
  2052  	default:
  2053  		return fmt.Errorf("unexpected snap packet type: %T", packet)
  2054  	}
  2055  }
  2056  
  2057  // deliver injects a new batch of data received from a remote node.
  2058  func (d *Downloader) deliver(destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) {
  2059  	// Update the delivery metrics for both good and failed deliveries
  2060  	inMeter.Mark(int64(packet.Items()))
  2061  	defer func() {
  2062  		if err != nil {
  2063  			dropMeter.Mark(int64(packet.Items()))
  2064  		}
  2065  	}()
  2066  	// Deliver or abort if the sync is canceled while queuing
  2067  	d.cancelLock.RLock()
  2068  	cancel := d.cancelCh
  2069  	d.cancelLock.RUnlock()
  2070  	if cancel == nil {
  2071  		return errNoSyncActive
  2072  	}
  2073  	select {
  2074  	case destCh <- packet:
  2075  		return nil
  2076  	case <-cancel:
  2077  		return errNoSyncActive
  2078  	}
  2079  }
  2080  
  2081  // qosTuner is the quality of service tuning loop that occasionally gathers the
  2082  // peer latency statistics and updates the estimated request round trip time.
  2083  func (d *Downloader) qosTuner() {
  2084  	for {
  2085  		// Retrieve the current median RTT and integrate into the previoust target RTT
  2086  		rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
  2087  		atomic.StoreUint64(&d.rttEstimate, uint64(rtt))
  2088  
  2089  		// A new RTT cycle passed, increase our confidence in the estimated RTT
  2090  		conf := atomic.LoadUint64(&d.rttConfidence)
  2091  		conf = conf + (1000000-conf)/2
  2092  		atomic.StoreUint64(&d.rttConfidence, conf)
  2093  
  2094  		// Log the new QoS values and sleep until the next RTT
  2095  		log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  2096  		select {
  2097  		case <-d.quitCh:
  2098  			return
  2099  		case <-time.After(rtt):
  2100  		}
  2101  	}
  2102  }
  2103  
  2104  // qosReduceConfidence is meant to be called when a new peer joins the downloader's
  2105  // peer set, needing to reduce the confidence we have in out QoS estimates.
  2106  func (d *Downloader) qosReduceConfidence() {
  2107  	// If we have a single peer, confidence is always 1
  2108  	peers := uint64(d.peers.Len())
  2109  	if peers == 0 {
  2110  		// Ensure peer connectivity races don't catch us off guard
  2111  		return
  2112  	}
  2113  	if peers == 1 {
  2114  		atomic.StoreUint64(&d.rttConfidence, 1000000)
  2115  		return
  2116  	}
  2117  	// If we have a ton of peers, don't drop confidence)
  2118  	if peers >= uint64(qosConfidenceCap) {
  2119  		return
  2120  	}
  2121  	// Otherwise drop the confidence factor
  2122  	conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers
  2123  	if float64(conf)/1000000 < rttMinConfidence {
  2124  		conf = uint64(rttMinConfidence * 1000000)
  2125  	}
  2126  	atomic.StoreUint64(&d.rttConfidence, conf)
  2127  
  2128  	rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate))
  2129  	log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  2130  }
  2131  
  2132  // requestRTT returns the current target round trip time for a download request
  2133  // to complete in.
  2134  //
  2135  // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that
  2136  // the downloader tries to adapt queries to the RTT, so multiple RTT values can
  2137  // be adapted to, but smaller ones are preferred (stabler download stream).
  2138  func (d *Downloader) requestRTT() time.Duration {
  2139  	return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10
  2140  }
  2141  
  2142  // requestTTL returns the current timeout allowance for a single download request
  2143  // to finish under.
  2144  func (d *Downloader) requestTTL() time.Duration {
  2145  	var (
  2146  		rtt  = time.Duration(atomic.LoadUint64(&d.rttEstimate))
  2147  		conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0
  2148  	)
  2149  	ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf)
  2150  	if ttl > ttlLimit {
  2151  		ttl = ttlLimit
  2152  	}
  2153  	return ttl
  2154  }