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