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