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