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