github.com/Inphi/go-ethereum@v1.9.7/eth/downloader/downloader.go (about)

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