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