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