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