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