github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/chain/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  	if localHeight >= MaxForkAncestry {
   669  		// We're above the max reorg threshold, find the earliest fork point
   670  		floor = int64(localHeight - MaxForkAncestry)
   671  
   672  		// If we're doing a light sync, ensure the floor doesn't go below the CHT, as
   673  		// all headers before that point will be missing.
   674  		if d.mode == LightSync {
   675  			// If we dont know the current CHT position, find it
   676  			if d.genesis == 0 {
   677  				header := d.lightchain.CurrentHeader()
   678  				for header != nil {
   679  					d.genesis = header.Number.Uint64()
   680  					if floor >= int64(d.genesis)-1 {
   681  						break
   682  					}
   683  					header = d.lightchain.GetHeaderByHash(header.ParentHash)
   684  				}
   685  			}
   686  			// We already know the "genesis" block number, cap floor to that
   687  			if floor < int64(d.genesis)-1 {
   688  				floor = int64(d.genesis) - 1
   689  			}
   690  		}
   691  	}
   692  	from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight)
   693  
   694  	p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip)
   695  	go p.peer.RequestHeadersByNumber(uint64(from), count, skip, false)
   696  
   697  	// Wait for the remote response to the head fetch
   698  	number, hash := uint64(0), common.Hash{}
   699  
   700  	ttl := d.requestTTL()
   701  	timeout := time.After(ttl)
   702  
   703  	for finished := false; !finished; {
   704  		select {
   705  		case <-d.cancelCh:
   706  			return 0, errCancelHeaderFetch
   707  
   708  		case packet := <-d.headerCh:
   709  			// Discard anything not from the origin peer
   710  			if packet.PeerId() != p.id {
   711  				log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
   712  				break
   713  			}
   714  			// Make sure the peer actually gave something valid
   715  			headers := packet.(*headerPack).headers
   716  			if len(headers) == 0 {
   717  				p.log.Warn("Empty head header set")
   718  				return 0, errEmptyHeaderSet
   719  			}
   720  			// Make sure the peer's reply conforms to the request
   721  			for i, header := range headers {
   722  				expectNumber := from + int64(i)*int64(skip+1)
   723  				if number := header.Number.Int64(); number != expectNumber {
   724  					p.log.Warn("Head headers broke chain ordering", "index", i, "requested", expectNumber, "received", number)
   725  					return 0, errInvalidChain
   726  				}
   727  			}
   728  			// Check if a common ancestor was found
   729  			finished = true
   730  			for i := len(headers) - 1; i >= 0; i-- {
   731  				// Skip any headers that underflow/overflow our requested set
   732  				if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > max {
   733  					continue
   734  				}
   735  				// Otherwise check if we already know the header or not
   736  				h := headers[i].Hash()
   737  				n := headers[i].Number.Uint64()
   738  
   739  				var known bool
   740  				switch d.mode {
   741  				case FullSync:
   742  					known = d.blockchain.HasBlock(h, n)
   743  				case FastSync:
   744  					known = d.blockchain.HasFastBlock(h, n)
   745  				default:
   746  					known = d.lightchain.HasHeader(h, n)
   747  				}
   748  				if known {
   749  					number, hash = n, h
   750  					break
   751  				}
   752  			}
   753  
   754  		case <-timeout:
   755  			p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
   756  			return 0, errTimeout
   757  
   758  		case <-d.bodyCh:
   759  		case <-d.receiptCh:
   760  			// Out of bounds delivery, ignore
   761  		}
   762  	}
   763  	// If the head fetch already found an ancestor, return
   764  	if hash != (common.Hash{}) {
   765  		if int64(number) <= floor {
   766  			p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
   767  			return 0, errInvalidAncestor
   768  		}
   769  		p.log.Debug("Found common ancestor", "number", number, "hash", hash)
   770  		return number, nil
   771  	}
   772  	// Ancestor not found, we need to binary search over our chain
   773  	start, end := uint64(0), remoteHeight
   774  	if floor > 0 {
   775  		start = uint64(floor)
   776  	}
   777  	p.log.Trace("Binary searching for common ancestor", "start", start, "end", end)
   778  
   779  	for start+1 < end {
   780  		// Split our chain interval in two, and request the hash to cross check
   781  		check := (start + end) / 2
   782  
   783  		ttl := d.requestTTL()
   784  		timeout := time.After(ttl)
   785  
   786  		go p.peer.RequestHeadersByNumber(check, 1, 0, false)
   787  
   788  		// Wait until a reply arrives to this request
   789  		for arrived := false; !arrived; {
   790  			select {
   791  			case <-d.cancelCh:
   792  				return 0, errCancelHeaderFetch
   793  
   794  			case packer := <-d.headerCh:
   795  				// Discard anything not from the origin peer
   796  				if packer.PeerId() != p.id {
   797  					log.Debug("Received headers from incorrect peer", "peer", packer.PeerId())
   798  					break
   799  				}
   800  				// Make sure the peer actually gave something valid
   801  				headers := packer.(*headerPack).headers
   802  				if len(headers) != 1 {
   803  					p.log.Debug("Multiple headers for single request", "headers", len(headers))
   804  					return 0, errBadPeer
   805  				}
   806  				arrived = true
   807  
   808  				// Modify the search interval based on the response
   809  				h := headers[0].Hash()
   810  				n := headers[0].Number.Uint64()
   811  
   812  				var known bool
   813  				switch d.mode {
   814  				case FullSync:
   815  					known = d.blockchain.HasBlock(h, n)
   816  				case FastSync:
   817  					known = d.blockchain.HasFastBlock(h, n)
   818  				default:
   819  					known = d.lightchain.HasHeader(h, n)
   820  				}
   821  				if !known {
   822  					end = check
   823  					break
   824  				}
   825  				header := d.lightchain.GetHeaderByHash(h) // Independent of sync mode, header surely exists
   826  				if header.Number.Uint64() != check {
   827  					p.log.Debug("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
   828  					return 0, errBadPeer
   829  				}
   830  				start = check
   831  				hash = h
   832  
   833  			case <-timeout:
   834  				p.log.Debug("Waiting for search header timed out", "elapsed", ttl)
   835  				return 0, errTimeout
   836  
   837  			case <-d.bodyCh:
   838  			case <-d.receiptCh:
   839  				// Out of bounds delivery, ignore
   840  			}
   841  		}
   842  	}
   843  	// Ensure valid ancestry and return
   844  	if int64(start) <= floor {
   845  		p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
   846  		return 0, errInvalidAncestor
   847  	}
   848  	p.log.Debug("Found common ancestor", "number", start, "hash", hash)
   849  	return start, nil
   850  }
   851  
   852  // fetchHeaders keeps retrieving headers concurrently from the number
   853  // requested, until no more are returned, potentially throttling on the way. To
   854  // facilitate concurrency but still protect against malicious nodes sending bad
   855  // headers, we construct a header chain skeleton using the "origin" peer we are
   856  // syncing with, and fill in the missing headers using anyone else. Headers from
   857  // other peers are only accepted if they map cleanly to the skeleton. If no one
   858  // can fill in the skeleton - not even the origin peer - it's assumed invalid and
   859  // the origin is dropped.
   860  func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, pivot uint64) error {
   861  	p.log.Debug("Directing header downloads", "origin", from)
   862  	defer p.log.Debug("Header download terminated")
   863  
   864  	// Create a timeout timer, and the associated header fetcher
   865  	skeleton := true            // Skeleton assembly phase or finishing up
   866  	request := time.Now()       // time of the last skeleton fetch request
   867  	timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
   868  	<-timeout.C                 // timeout channel should be initially empty
   869  	defer timeout.Stop()
   870  
   871  	var ttl time.Duration
   872  	getHeaders := func(from uint64) {
   873  		request = time.Now()
   874  
   875  		ttl = d.requestTTL()
   876  		timeout.Reset(ttl)
   877  
   878  		if skeleton {
   879  			p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from)
   880  			go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false)
   881  		} else {
   882  			p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from)
   883  			go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false)
   884  		}
   885  	}
   886  	// Start pulling the header chain skeleton until all is done
   887  	getHeaders(from)
   888  
   889  	for {
   890  		select {
   891  		case <-d.cancelCh:
   892  			return errCancelHeaderFetch
   893  
   894  		case packet := <-d.headerCh:
   895  			// Make sure the active peer is giving us the skeleton headers
   896  			if packet.PeerId() != p.id {
   897  				log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId())
   898  				break
   899  			}
   900  			headerReqTimer.UpdateSince(request)
   901  			timeout.Stop()
   902  
   903  			// If the skeleton's finished, pull any remaining head headers directly from the origin
   904  			if packet.Items() == 0 && skeleton {
   905  				skeleton = false
   906  				getHeaders(from)
   907  				continue
   908  			}
   909  			// If no more headers are inbound, notify the content fetchers and return
   910  			if packet.Items() == 0 {
   911  				// Don't abort header fetches while the pivot is downloading
   912  				if atomic.LoadInt32(&d.committed) == 0 && pivot <= from {
   913  					p.log.Debug("No headers, waiting for pivot commit")
   914  					select {
   915  					case <-time.After(fsHeaderContCheck):
   916  						getHeaders(from)
   917  						continue
   918  					case <-d.cancelCh:
   919  						return errCancelHeaderFetch
   920  					}
   921  				}
   922  				// Pivot done (or not in fast sync) and no more headers, terminate the process
   923  				p.log.Debug("No more headers available")
   924  				select {
   925  				case d.headerProcCh <- nil:
   926  					return nil
   927  				case <-d.cancelCh:
   928  					return errCancelHeaderFetch
   929  				}
   930  			}
   931  			headers := packet.(*headerPack).headers
   932  
   933  			// If we received a skeleton batch, resolve internals concurrently
   934  			if skeleton {
   935  				filled, proced, err := d.fillHeaderSkeleton(from, headers)
   936  				if err != nil {
   937  					p.log.Debug("Skeleton chain invalid", "err", err)
   938  					return errInvalidChain
   939  				}
   940  				headers = filled[proced:]
   941  				from += uint64(proced)
   942  			} else {
   943  				// If we're closing in on the chain head, but haven't yet reached it, delay
   944  				// the last few headers so mini reorgs on the head don't cause invalid hash
   945  				// chain errors.
   946  				if n := len(headers); n > 0 {
   947  					// Retrieve the current head we're at
   948  					head := uint64(0)
   949  					if d.mode == LightSync {
   950  						head = d.lightchain.CurrentHeader().Number.Uint64()
   951  					} else {
   952  						head = d.blockchain.CurrentFastBlock().NumberU64()
   953  						if full := d.blockchain.CurrentBlock().NumberU64(); head < full {
   954  							head = full
   955  						}
   956  					}
   957  					// If the head is way older than this batch, delay the last few headers
   958  					if head+uint64(reorgProtThreshold) < headers[n-1].Number.Uint64() {
   959  						delay := reorgProtHeaderDelay
   960  						if delay > n {
   961  							delay = n
   962  						}
   963  						headers = headers[:n-delay]
   964  					}
   965  				}
   966  			}
   967  			// Insert all the new headers and fetch the next batch
   968  			if len(headers) > 0 {
   969  				p.log.Trace("Scheduling new headers", "count", len(headers), "from", from)
   970  				select {
   971  				case d.headerProcCh <- headers:
   972  				case <-d.cancelCh:
   973  					return errCancelHeaderFetch
   974  				}
   975  				from += uint64(len(headers))
   976  				getHeaders(from)
   977  			} else {
   978  				// No headers delivered, or all of them being delayed, sleep a bit and retry
   979  				p.log.Trace("All headers delayed, waiting")
   980  				select {
   981  				case <-time.After(fsHeaderContCheck):
   982  					getHeaders(from)
   983  					continue
   984  				case <-d.cancelCh:
   985  					return errCancelHeaderFetch
   986  				}
   987  			}
   988  
   989  		case <-timeout.C:
   990  			if d.dropPeer == nil {
   991  				// The dropPeer method is nil when `--copydb` is used for a local copy.
   992  				// Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
   993  				p.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", p.id)
   994  				break
   995  			}
   996  			// Header retrieval timed out, consider the peer bad and drop
   997  			p.log.Debug("Header request timed out", "elapsed", ttl)
   998  			headerTimeoutMeter.Mark(1)
   999  			d.dropPeer(p.id)
  1000  
  1001  			// Finish the sync gracefully instead of dumping the gathered data though
  1002  			for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1003  				select {
  1004  				case ch <- false:
  1005  				case <-d.cancelCh:
  1006  				}
  1007  			}
  1008  			select {
  1009  			case d.headerProcCh <- nil:
  1010  			case <-d.cancelCh:
  1011  			}
  1012  			return errBadPeer
  1013  		}
  1014  	}
  1015  }
  1016  
  1017  // fillHeaderSkeleton concurrently retrieves headers from all our available peers
  1018  // and maps them to the provided skeleton header chain.
  1019  //
  1020  // Any partial results from the beginning of the skeleton is (if possible) forwarded
  1021  // immediately to the header processor to keep the rest of the pipeline full even
  1022  // in the case of header stalls.
  1023  //
  1024  // The method returns the entire filled skeleton and also the number of headers
  1025  // already forwarded for processing.
  1026  func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) {
  1027  	log.Debug("Filling up skeleton", "from", from)
  1028  	d.queue.ScheduleSkeleton(from, skeleton)
  1029  
  1030  	var (
  1031  		deliver = func(packet dataPack) (int, error) {
  1032  			pack := packet.(*headerPack)
  1033  			return d.queue.DeliverHeaders(pack.peerID, pack.headers, d.headerProcCh)
  1034  		}
  1035  		expire   = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) }
  1036  		throttle = func() bool { return false }
  1037  		reserve  = func(p *peerConnection, count int) (*fetchRequest, bool, error) {
  1038  			return d.queue.ReserveHeaders(p, count), false, nil
  1039  		}
  1040  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) }
  1041  		capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) }
  1042  		setIdle  = func(p *peerConnection, accepted int) { p.SetHeadersIdle(accepted) }
  1043  	)
  1044  	err := d.fetchParts(errCancelHeaderFetch, d.headerCh, deliver, d.queue.headerContCh, expire,
  1045  		d.queue.PendingHeaders, d.queue.InFlightHeaders, throttle, reserve,
  1046  		nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers")
  1047  
  1048  	log.Debug("Skeleton fill terminated", "err", err)
  1049  
  1050  	filled, proced := d.queue.RetrieveHeaders()
  1051  	return filled, proced, err
  1052  }
  1053  
  1054  // fetchBodies iteratively downloads the scheduled block bodies, taking any
  1055  // available peers, reserving a chunk of blocks for each, waiting for delivery
  1056  // and also periodically checking for timeouts.
  1057  func (d *Downloader) fetchBodies(from uint64) error {
  1058  	log.Debug("Downloading block bodies", "origin", from)
  1059  
  1060  	var (
  1061  		deliver = func(packet dataPack) (int, error) {
  1062  			pack := packet.(*bodyPack)
  1063  			return d.queue.DeliverBodies(pack.peerID, pack.transactions, pack.uncles)
  1064  		}
  1065  		expire   = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) }
  1066  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) }
  1067  		capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) }
  1068  		setIdle  = func(p *peerConnection, accepted int) { p.SetBodiesIdle(accepted) }
  1069  	)
  1070  	err := d.fetchParts(errCancelBodyFetch, d.bodyCh, deliver, d.bodyWakeCh, expire,
  1071  		d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ShouldThrottleBlocks, d.queue.ReserveBodies,
  1072  		d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies")
  1073  
  1074  	log.Debug("Block body download terminated", "err", err)
  1075  	return err
  1076  }
  1077  
  1078  // fetchReceipts iteratively downloads the scheduled block receipts, taking any
  1079  // available peers, reserving a chunk of receipts for each, waiting for delivery
  1080  // and also periodically checking for timeouts.
  1081  func (d *Downloader) fetchReceipts(from uint64) error {
  1082  	log.Debug("Downloading transaction receipts", "origin", from)
  1083  
  1084  	var (
  1085  		deliver = func(packet dataPack) (int, error) {
  1086  			pack := packet.(*receiptPack)
  1087  			return d.queue.DeliverReceipts(pack.peerID, pack.receipts)
  1088  		}
  1089  		expire   = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) }
  1090  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) }
  1091  		capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) }
  1092  		setIdle  = func(p *peerConnection, accepted int) { p.SetReceiptsIdle(accepted) }
  1093  	)
  1094  	err := d.fetchParts(errCancelReceiptFetch, d.receiptCh, deliver, d.receiptWakeCh, expire,
  1095  		d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ShouldThrottleReceipts, d.queue.ReserveReceipts,
  1096  		d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts")
  1097  
  1098  	log.Debug("Transaction receipt download terminated", "err", err)
  1099  	return err
  1100  }
  1101  
  1102  // fetchParts iteratively downloads scheduled block parts, taking any available
  1103  // peers, reserving a chunk of fetch requests for each, waiting for delivery and
  1104  // also periodically checking for timeouts.
  1105  //
  1106  // As the scheduling/timeout logic mostly is the same for all downloaded data
  1107  // types, this method is used by each for data gathering and is instrumented with
  1108  // various callbacks to handle the slight differences between processing them.
  1109  //
  1110  // The instrumentation parameters:
  1111  //  - errCancel:   error type to return if the fetch operation is cancelled (mostly makes logging nicer)
  1112  //  - deliveryCh:  channel from which to retrieve downloaded data packets (merged from all concurrent peers)
  1113  //  - deliver:     processing callback to deliver data packets into type specific download queues (usually within `queue`)
  1114  //  - wakeCh:      notification channel for waking the fetcher when new tasks are available (or sync completed)
  1115  //  - expire:      task callback method to abort requests that took too long and return the faulty peers (traffic shaping)
  1116  //  - pending:     task callback for the number of requests still needing download (detect completion/non-completability)
  1117  //  - inFlight:    task callback for the number of in-progress requests (wait for all active downloads to finish)
  1118  //  - throttle:    task callback to check if the processing queue is full and activate throttling (bound memory use)
  1119  //  - reserve:     task callback to reserve new download tasks to a particular peer (also signals partial completions)
  1120  //  - fetchHook:   tester callback to notify of new tasks being initiated (allows testing the scheduling logic)
  1121  //  - fetch:       network callback to actually send a particular download request to a physical remote peer
  1122  //  - cancel:      task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer)
  1123  //  - capacity:    network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping)
  1124  //  - idle:        network callback to retrieve the currently (type specific) idle peers that can be assigned tasks
  1125  //  - setIdle:     network callback to set a peer back to idle and update its estimated capacity (traffic shaping)
  1126  //  - kind:        textual label of the type being downloaded to display in log mesages
  1127  func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool,
  1128  	expire func() map[string]int, pending func() int, inFlight func() bool, throttle func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, error),
  1129  	fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
  1130  	idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int), kind string) error {
  1131  
  1132  	// Create a ticker to detect expired retrieval tasks
  1133  	ticker := time.NewTicker(100 * time.Millisecond)
  1134  	defer ticker.Stop()
  1135  
  1136  	update := make(chan struct{}, 1)
  1137  
  1138  	// Prepare the queue and fetch block parts until the block header fetcher's done
  1139  	finished := false
  1140  	for {
  1141  		select {
  1142  		case <-d.cancelCh:
  1143  			return errCancel
  1144  
  1145  		case packet := <-deliveryCh:
  1146  			// If the peer was previously banned and failed to deliver its pack
  1147  			// in a reasonable time frame, ignore its message.
  1148  			if peer := d.peers.Peer(packet.PeerId()); peer != nil {
  1149  				// Deliver the received chunk of data and check chain validity
  1150  				accepted, err := deliver(packet)
  1151  				if err == errInvalidChain {
  1152  					return err
  1153  				}
  1154  				// Unless a peer delivered something completely else than requested (usually
  1155  				// caused by a timed out request which came through in the end), set it to
  1156  				// idle. If the delivery's stale, the peer should have already been idled.
  1157  				if err != errStaleDelivery {
  1158  					setIdle(peer, accepted)
  1159  				}
  1160  				// Issue a log to the user to see what's going on
  1161  				switch {
  1162  				case err == nil && packet.Items() == 0:
  1163  					peer.log.Trace("Requested data not delivered", "type", kind)
  1164  				case err == nil:
  1165  					peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats())
  1166  				default:
  1167  					peer.log.Trace("Failed to deliver retrieved data", "type", kind, "err", err)
  1168  				}
  1169  			}
  1170  			// Blocks assembled, try to update the progress
  1171  			select {
  1172  			case update <- struct{}{}:
  1173  			default:
  1174  			}
  1175  
  1176  		case cont := <-wakeCh:
  1177  			// The header fetcher sent a continuation flag, check if it's done
  1178  			if !cont {
  1179  				finished = true
  1180  			}
  1181  			// Headers arrive, try to update the progress
  1182  			select {
  1183  			case update <- struct{}{}:
  1184  			default:
  1185  			}
  1186  
  1187  		case <-ticker.C:
  1188  			// Sanity check update the progress
  1189  			select {
  1190  			case update <- struct{}{}:
  1191  			default:
  1192  			}
  1193  
  1194  		case <-update:
  1195  			// Short circuit if we lost all our peers
  1196  			if d.peers.Len() == 0 {
  1197  				return errNoPeers
  1198  			}
  1199  			// Check for fetch request timeouts and demote the responsible peers
  1200  			for pid, fails := range expire() {
  1201  				if peer := d.peers.Peer(pid); peer != nil {
  1202  					// If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps
  1203  					// ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times
  1204  					// out that sync wise we need to get rid of the peer.
  1205  					//
  1206  					// The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth
  1207  					// and latency of a peer separately, which requires pushing the measures capacity a bit and seeing
  1208  					// how response times reacts, to it always requests one more than the minimum (i.e. min 2).
  1209  					if fails > 2 {
  1210  						peer.log.Trace("Data delivery timed out", "type", kind)
  1211  						setIdle(peer, 0)
  1212  					} else {
  1213  						peer.log.Debug("Stalling delivery, dropping", "type", kind)
  1214  						if d.dropPeer == nil {
  1215  							// The dropPeer method is nil when `--copydb` is used for a local copy.
  1216  							// Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored
  1217  							peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", pid)
  1218  						} else {
  1219  							d.dropPeer(pid)
  1220  						}
  1221  					}
  1222  				}
  1223  			}
  1224  			// If there's nothing more to fetch, wait or terminate
  1225  			if pending() == 0 {
  1226  				if !inFlight() && finished {
  1227  					log.Debug("Data fetching completed", "type", kind)
  1228  					return nil
  1229  				}
  1230  				break
  1231  			}
  1232  			// Send a download request to all idle peers, until throttled
  1233  			progressed, throttled, running := false, false, inFlight()
  1234  			idles, total := idle()
  1235  
  1236  			for _, peer := range idles {
  1237  				// Short circuit if throttling activated
  1238  				if throttle() {
  1239  					throttled = true
  1240  					break
  1241  				}
  1242  				// Short circuit if there is no more available task.
  1243  				if pending() == 0 {
  1244  					break
  1245  				}
  1246  				// Reserve a chunk of fetches for a peer. A nil can mean either that
  1247  				// no more headers are available, or that the peer is known not to
  1248  				// have them.
  1249  				request, progress, err := reserve(peer, capacity(peer))
  1250  				if err != nil {
  1251  					return err
  1252  				}
  1253  				if progress {
  1254  					progressed = true
  1255  				}
  1256  				if request == nil {
  1257  					continue
  1258  				}
  1259  				if request.From > 0 {
  1260  					peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From)
  1261  				} else {
  1262  					peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number)
  1263  				}
  1264  				// Fetch the chunk and make sure any errors return the hashes to the queue
  1265  				if fetchHook != nil {
  1266  					fetchHook(request.Headers)
  1267  				}
  1268  				if err := fetch(peer, request); err != nil {
  1269  					// Although we could try and make an attempt to fix this, this error really
  1270  					// means that we've double allocated a fetch task to a peer. If that is the
  1271  					// case, the internal state of the downloader and the queue is very wrong so
  1272  					// better hard crash and note the error instead of silently accumulating into
  1273  					// a much bigger issue.
  1274  					panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind))
  1275  				}
  1276  				running = true
  1277  			}
  1278  			// Make sure that we have peers available for fetching. If all peers have been tried
  1279  			// and all failed throw an error
  1280  			if !progressed && !throttled && !running && len(idles) == total && pending() > 0 {
  1281  				return errPeersUnavailable
  1282  			}
  1283  		}
  1284  	}
  1285  }
  1286  
  1287  // processHeaders takes batches of retrieved headers from an input channel and
  1288  // keeps processing and scheduling them into the header chain and downloader's
  1289  // queue until the stream ends or a failure occurs.
  1290  func (d *Downloader) processHeaders(origin uint64, pivot uint64, td *big.Int) error {
  1291  	// Keep a count of uncertain headers to roll back
  1292  	rollback := []*types.Header{}
  1293  	defer func() {
  1294  		if len(rollback) > 0 {
  1295  			// Flatten the headers and roll them back
  1296  			hashes := make([]common.Hash, len(rollback))
  1297  			for i, header := range rollback {
  1298  				hashes[i] = header.Hash()
  1299  			}
  1300  			lastHeader, lastFastBlock, lastBlock := d.lightchain.CurrentHeader().Number, common.Big0, common.Big0
  1301  			if d.mode != LightSync {
  1302  				lastFastBlock = d.blockchain.CurrentFastBlock().Number()
  1303  				lastBlock = d.blockchain.CurrentBlock().Number()
  1304  			}
  1305  			d.lightchain.Rollback(hashes)
  1306  			curFastBlock, curBlock := common.Big0, common.Big0
  1307  			if d.mode != LightSync {
  1308  				curFastBlock = d.blockchain.CurrentFastBlock().Number()
  1309  				curBlock = d.blockchain.CurrentBlock().Number()
  1310  			}
  1311  			log.Warn("Rolled back headers", "count", len(hashes),
  1312  				"header", fmt.Sprintf("%d->%d", lastHeader, d.lightchain.CurrentHeader().Number),
  1313  				"fast", fmt.Sprintf("%d->%d", lastFastBlock, curFastBlock),
  1314  				"block", fmt.Sprintf("%d->%d", lastBlock, curBlock))
  1315  		}
  1316  	}()
  1317  
  1318  	// Wait for batches of headers to process
  1319  	gotHeaders := false
  1320  
  1321  	for {
  1322  		select {
  1323  		case <-d.cancelCh:
  1324  			return errCancelHeaderProcessing
  1325  
  1326  		case headers := <-d.headerProcCh:
  1327  			// Terminate header processing if we synced up
  1328  			if len(headers) == 0 {
  1329  				// Notify everyone that headers are fully processed
  1330  				for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1331  					select {
  1332  					case ch <- false:
  1333  					case <-d.cancelCh:
  1334  					}
  1335  				}
  1336  				// If no headers were retrieved at all, the peer violated its TD promise that it had a
  1337  				// better chain compared to ours. The only exception is if its promised blocks were
  1338  				// already imported by other means (e.g. fetcher):
  1339  				//
  1340  				// R <remote peer>, L <local node>: Both at block 10
  1341  				// R: Mine block 11, and propagate it to L
  1342  				// L: Queue block 11 for import
  1343  				// L: Notice that R's head and TD increased compared to ours, start sync
  1344  				// L: Import of block 11 finishes
  1345  				// L: Sync begins, and finds common ancestor at 11
  1346  				// L: Request new headers up from 11 (R's TD was higher, it must have something)
  1347  				// R: Nothing to give
  1348  				if d.mode != LightSync {
  1349  					head := d.blockchain.CurrentBlock()
  1350  					if !gotHeaders && td.Cmp(d.blockchain.GetTd(head.Hash(), head.NumberU64())) > 0 {
  1351  						return errStallingPeer
  1352  					}
  1353  				}
  1354  				// If fast or light syncing, ensure promised headers are indeed delivered. This is
  1355  				// needed to detect scenarios where an attacker feeds a bad pivot and then bails out
  1356  				// of delivering the post-pivot blocks that would flag the invalid content.
  1357  				//
  1358  				// This check cannot be executed "as is" for full imports, since blocks may still be
  1359  				// queued for processing when the header download completes. However, as long as the
  1360  				// peer gave us something useful, we're already happy/progressed (above check).
  1361  				if d.mode == FastSync || d.mode == LightSync {
  1362  					head := d.lightchain.CurrentHeader()
  1363  					if td.Cmp(d.lightchain.GetTd(head.Hash(), head.Number.Uint64())) > 0 {
  1364  						return errStallingPeer
  1365  					}
  1366  				}
  1367  				// Disable any rollback and return
  1368  				rollback = nil
  1369  				return nil
  1370  			}
  1371  			// Otherwise split the chunk of headers into batches and process them
  1372  			gotHeaders = true
  1373  			for len(headers) > 0 {
  1374  				// Terminate if something failed in between processing chunks
  1375  				select {
  1376  				case <-d.cancelCh:
  1377  					return errCancelHeaderProcessing
  1378  				default:
  1379  				}
  1380  				// Select the next chunk of headers to import
  1381  				limit := maxHeadersProcess
  1382  				if limit > len(headers) {
  1383  					limit = len(headers)
  1384  				}
  1385  				chunk := headers[:limit]
  1386  
  1387  				// In case of header only syncing, validate the chunk immediately
  1388  				if d.mode == FastSync || d.mode == LightSync {
  1389  					// Collect the yet unknown headers to mark them as uncertain
  1390  					unknown := make([]*types.Header, 0, len(headers))
  1391  					for _, header := range chunk {
  1392  						if !d.lightchain.HasHeader(header.Hash(), header.Number.Uint64()) {
  1393  							unknown = append(unknown, header)
  1394  						}
  1395  					}
  1396  					// If we're importing pure headers, verify based on their recentness
  1397  					frequency := fsHeaderCheckFrequency
  1398  					if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot {
  1399  						frequency = 1
  1400  					}
  1401  					if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil {
  1402  						// If some headers were inserted, add them too to the rollback list
  1403  						if n > 0 {
  1404  							rollback = append(rollback, chunk[:n]...)
  1405  						}
  1406  						log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "err", err)
  1407  						return errInvalidChain
  1408  					}
  1409  					// All verifications passed, store newly found uncertain headers
  1410  					rollback = append(rollback, unknown...)
  1411  					if len(rollback) > fsHeaderSafetyNet {
  1412  						rollback = append(rollback[:0], rollback[len(rollback)-fsHeaderSafetyNet:]...)
  1413  					}
  1414  				}
  1415  				// Unless we're doing light chains, schedule the headers for associated content retrieval
  1416  				if d.mode == FullSync || d.mode == FastSync {
  1417  					// If we've reached the allowed number of pending headers, stall a bit
  1418  					for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
  1419  						select {
  1420  						case <-d.cancelCh:
  1421  							return errCancelHeaderProcessing
  1422  						case <-time.After(time.Second):
  1423  						}
  1424  					}
  1425  					// Otherwise insert the headers for content retrieval
  1426  					inserts := d.queue.Schedule(chunk, origin)
  1427  					if len(inserts) != len(chunk) {
  1428  						log.Debug("Stale headers")
  1429  						return errBadPeer
  1430  					}
  1431  				}
  1432  				headers = headers[limit:]
  1433  				origin += uint64(limit)
  1434  			}
  1435  			// Update the highest block number we know if a higher one is found.
  1436  			d.syncStatsLock.Lock()
  1437  			if d.syncStatsChainHeight < origin {
  1438  				d.syncStatsChainHeight = origin - 1
  1439  			}
  1440  			d.syncStatsLock.Unlock()
  1441  
  1442  			// Signal the content downloaders of the availablility of new tasks
  1443  			for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1444  				select {
  1445  				case ch <- true:
  1446  				default:
  1447  				}
  1448  			}
  1449  		}
  1450  	}
  1451  }
  1452  
  1453  // processFullSyncContent takes fetch results from the queue and imports them into the chain.
  1454  func (d *Downloader) processFullSyncContent() error {
  1455  	for {
  1456  		results := d.queue.Results(true)
  1457  		if len(results) == 0 {
  1458  			return nil
  1459  		}
  1460  		if d.chainInsertHook != nil {
  1461  			d.chainInsertHook(results)
  1462  		}
  1463  		if err := d.importBlockResults(results); err != nil {
  1464  			return err
  1465  		}
  1466  	}
  1467  }
  1468  
  1469  func (d *Downloader) importBlockResults(results []*fetchResult) error {
  1470  	// Check for any early termination requests
  1471  	if len(results) == 0 {
  1472  		return nil
  1473  	}
  1474  	select {
  1475  	case <-d.quitCh:
  1476  		return errCancelContentProcessing
  1477  	default:
  1478  	}
  1479  	// Retrieve the a batch of results to import
  1480  	first, last := results[0].Header, results[len(results)-1].Header
  1481  	log.Debug("Inserting downloaded chain", "items", len(results),
  1482  		"firstnum", first.Number, "firsthash", first.Hash(),
  1483  		"lastnum", last.Number, "lasthash", last.Hash(),
  1484  	)
  1485  	blocks := make([]*types.Block, len(results))
  1486  	for i, result := range results {
  1487  		blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1488  	}
  1489  	if index, err := d.blockchain.InsertChain(blocks); err != nil {
  1490  		if index < len(results) {
  1491  			log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1492  		} else {
  1493  			// The InsertChain method in blockchain.go will sometimes return an out-of-bounds index,
  1494  			// when it needs to preprocess blocks to import a sidechain.
  1495  			// The importer will put together a new list of blocks to import, which is a superset
  1496  			// of the blocks delivered from the downloader, and the indexing will be off.
  1497  			log.Debug("Downloaded item processing failed on sidechain import", "index", index, "err", err)
  1498  		}
  1499  		return errInvalidChain
  1500  	}
  1501  	return nil
  1502  }
  1503  
  1504  // processFastSyncContent takes fetch results from the queue and writes them to the
  1505  // database. It also controls the synchronisation of state nodes of the pivot block.
  1506  func (d *Downloader) processFastSyncContent(latest *types.Header) error {
  1507  	// Start syncing state of the reported head block. This should get us most of
  1508  	// the state of the pivot block.
  1509  	stateSync := d.syncState(latest.Root)
  1510  	defer stateSync.Cancel()
  1511  	go func() {
  1512  		if err := stateSync.Wait(); err != nil && err != errCancelStateFetch {
  1513  			d.queue.Close() // wake up Results
  1514  		}
  1515  	}()
  1516  	// Figure out the ideal pivot block. Note, that this goalpost may move if the
  1517  	// sync takes long enough for the chain head to move significantly.
  1518  	pivot := uint64(0)
  1519  	if height := latest.Number.Uint64(); height > uint64(fsMinFullBlocks) {
  1520  		pivot = height - uint64(fsMinFullBlocks)
  1521  	}
  1522  	// To cater for moving pivot points, track the pivot block and subsequently
  1523  	// accumulated download results separately.
  1524  	var (
  1525  		oldPivot *fetchResult   // Locked in pivot block, might change eventually
  1526  		oldTail  []*fetchResult // Downloaded content after the pivot
  1527  	)
  1528  	for {
  1529  		// Wait for the next batch of downloaded data to be available, and if the pivot
  1530  		// block became stale, move the goalpost
  1531  		results := d.queue.Results(oldPivot == nil) // Block if we're not monitoring pivot staleness
  1532  		if len(results) == 0 {
  1533  			// If pivot sync is done, stop
  1534  			if oldPivot == nil {
  1535  				return stateSync.Cancel()
  1536  			}
  1537  			// If sync failed, stop
  1538  			select {
  1539  			case <-d.cancelCh:
  1540  				return stateSync.Cancel()
  1541  			default:
  1542  			}
  1543  		}
  1544  		if d.chainInsertHook != nil {
  1545  			d.chainInsertHook(results)
  1546  		}
  1547  		if oldPivot != nil {
  1548  			results = append(append([]*fetchResult{oldPivot}, oldTail...), results...)
  1549  		}
  1550  		// Split around the pivot block and process the two sides via fast/full sync
  1551  		if atomic.LoadInt32(&d.committed) == 0 {
  1552  			latest = results[len(results)-1].Header
  1553  			if height := latest.Number.Uint64(); height > pivot+2*uint64(fsMinFullBlocks) {
  1554  				log.Warn("Pivot became stale, moving", "old", pivot, "new", height-uint64(fsMinFullBlocks))
  1555  				pivot = height - uint64(fsMinFullBlocks)
  1556  			}
  1557  		}
  1558  		P, beforeP, afterP := splitAroundPivot(pivot, results)
  1559  		if err := d.commitFastSyncData(beforeP, stateSync); err != nil {
  1560  			return err
  1561  		}
  1562  		if P != nil {
  1563  			// If new pivot block found, cancel old state retrieval and restart
  1564  			if oldPivot != P {
  1565  				stateSync.Cancel()
  1566  
  1567  				stateSync = d.syncState(P.Header.Root)
  1568  				defer stateSync.Cancel()
  1569  				go func() {
  1570  					if err := stateSync.Wait(); err != nil && err != errCancelStateFetch {
  1571  						d.queue.Close() // wake up Results
  1572  					}
  1573  				}()
  1574  				oldPivot = P
  1575  			}
  1576  			// Wait for completion, occasionally checking for pivot staleness
  1577  			select {
  1578  			case <-stateSync.done:
  1579  				if stateSync.err != nil {
  1580  					return stateSync.err
  1581  				}
  1582  				if err := d.commitPivotBlock(P); err != nil {
  1583  					return err
  1584  				}
  1585  				oldPivot = nil
  1586  
  1587  			case <-time.After(time.Second):
  1588  				oldTail = afterP
  1589  				continue
  1590  			}
  1591  		}
  1592  		// Fast sync done, pivot commit done, full import
  1593  		if err := d.importBlockResults(afterP); err != nil {
  1594  			return err
  1595  		}
  1596  	}
  1597  }
  1598  
  1599  func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) {
  1600  	for _, result := range results {
  1601  		num := result.Header.Number.Uint64()
  1602  		switch {
  1603  		case num < pivot:
  1604  			before = append(before, result)
  1605  		case num == pivot:
  1606  			p = result
  1607  		default:
  1608  			after = append(after, result)
  1609  		}
  1610  	}
  1611  	return p, before, after
  1612  }
  1613  
  1614  func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error {
  1615  	// Check for any early termination requests
  1616  	if len(results) == 0 {
  1617  		return nil
  1618  	}
  1619  	select {
  1620  	case <-d.quitCh:
  1621  		return errCancelContentProcessing
  1622  	case <-stateSync.done:
  1623  		if err := stateSync.Wait(); err != nil {
  1624  			return err
  1625  		}
  1626  	default:
  1627  	}
  1628  	// Retrieve the a batch of results to import
  1629  	first, last := results[0].Header, results[len(results)-1].Header
  1630  	log.Debug("Inserting fast-sync blocks", "items", len(results),
  1631  		"firstnum", first.Number, "firsthash", first.Hash(),
  1632  		"lastnumn", last.Number, "lasthash", last.Hash(),
  1633  	)
  1634  	blocks := make([]*types.Block, len(results))
  1635  	receipts := make([]types.Receipts, len(results))
  1636  	for i, result := range results {
  1637  		blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1638  		receipts[i] = result.Receipts
  1639  	}
  1640  	if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil {
  1641  		log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1642  		return errInvalidChain
  1643  	}
  1644  	return nil
  1645  }
  1646  
  1647  func (d *Downloader) commitPivotBlock(result *fetchResult) error {
  1648  	block := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1649  	log.Debug("Committing fast sync pivot as new head", "number", block.Number(), "hash", block.Hash())
  1650  	if _, err := d.blockchain.InsertReceiptChain([]*types.Block{block}, []types.Receipts{result.Receipts}); err != nil {
  1651  		return err
  1652  	}
  1653  	if err := d.blockchain.FastSyncCommitHead(block.Hash()); err != nil {
  1654  		return err
  1655  	}
  1656  	atomic.StoreInt32(&d.committed, 1)
  1657  	return nil
  1658  }
  1659  
  1660  // DeliverHeaders injects a new batch of block headers received from a remote
  1661  // node into the download schedule.
  1662  func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) {
  1663  	return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
  1664  }
  1665  
  1666  // DeliverBodies injects a new batch of block bodies received from a remote node.
  1667  func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) {
  1668  	return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
  1669  }
  1670  
  1671  // DeliverReceipts injects a new batch of receipts received from a remote node.
  1672  func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) {
  1673  	return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
  1674  }
  1675  
  1676  // DeliverNodeData injects a new batch of node state data received from a remote node.
  1677  func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) {
  1678  	return d.deliver(id, d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter)
  1679  }
  1680  
  1681  // deliver injects a new batch of data received from a remote node.
  1682  func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) {
  1683  	// Update the delivery metrics for both good and failed deliveries
  1684  	inMeter.Mark(int64(packet.Items()))
  1685  	defer func() {
  1686  		if err != nil {
  1687  			dropMeter.Mark(int64(packet.Items()))
  1688  		}
  1689  	}()
  1690  	// Deliver or abort if the sync is canceled while queuing
  1691  	d.cancelLock.RLock()
  1692  	cancel := d.cancelCh
  1693  	d.cancelLock.RUnlock()
  1694  	if cancel == nil {
  1695  		return errNoSyncActive
  1696  	}
  1697  	select {
  1698  	case destCh <- packet:
  1699  		return nil
  1700  	case <-cancel:
  1701  		return errNoSyncActive
  1702  	}
  1703  }
  1704  
  1705  // qosTuner is the quality of service tuning loop that occasionally gathers the
  1706  // peer latency statistics and updates the estimated request round trip time.
  1707  func (d *Downloader) qosTuner() {
  1708  	for {
  1709  		// Retrieve the current median RTT and integrate into the previoust target RTT
  1710  		rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
  1711  		atomic.StoreUint64(&d.rttEstimate, uint64(rtt))
  1712  
  1713  		// A new RTT cycle passed, increase our confidence in the estimated RTT
  1714  		conf := atomic.LoadUint64(&d.rttConfidence)
  1715  		conf = conf + (1000000-conf)/2
  1716  		atomic.StoreUint64(&d.rttConfidence, conf)
  1717  
  1718  		// Log the new QoS values and sleep until the next RTT
  1719  		log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1720  		select {
  1721  		case <-d.quitCh:
  1722  			return
  1723  		case <-time.After(rtt):
  1724  		}
  1725  	}
  1726  }
  1727  
  1728  // qosReduceConfidence is meant to be called when a new peer joins the downloader's
  1729  // peer set, needing to reduce the confidence we have in out QoS estimates.
  1730  func (d *Downloader) qosReduceConfidence() {
  1731  	// If we have a single peer, confidence is always 1
  1732  	peers := uint64(d.peers.Len())
  1733  	if peers == 0 {
  1734  		// Ensure peer connectivity races don't catch us off guard
  1735  		return
  1736  	}
  1737  	if peers == 1 {
  1738  		atomic.StoreUint64(&d.rttConfidence, 1000000)
  1739  		return
  1740  	}
  1741  	// If we have a ton of peers, don't drop confidence)
  1742  	if peers >= uint64(qosConfidenceCap) {
  1743  		return
  1744  	}
  1745  	// Otherwise drop the confidence factor
  1746  	conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers
  1747  	if float64(conf)/1000000 < rttMinConfidence {
  1748  		conf = uint64(rttMinConfidence * 1000000)
  1749  	}
  1750  	atomic.StoreUint64(&d.rttConfidence, conf)
  1751  
  1752  	rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1753  	log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1754  }
  1755  
  1756  // requestRTT returns the current target round trip time for a download request
  1757  // to complete in.
  1758  //
  1759  // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that
  1760  // the downloader tries to adapt queries to the RTT, so multiple RTT values can
  1761  // be adapted to, but smaller ones are preferred (stabler download stream).
  1762  func (d *Downloader) requestRTT() time.Duration {
  1763  	return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10
  1764  }
  1765  
  1766  // requestTTL returns the current timeout allowance for a single download request
  1767  // to finish under.
  1768  func (d *Downloader) requestTTL() time.Duration {
  1769  	var (
  1770  		rtt  = time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1771  		conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0
  1772  	)
  1773  	ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf)
  1774  	if ttl > ttlLimit {
  1775  		ttl = ttlLimit
  1776  	}
  1777  	return ttl
  1778  }