github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+incompatible/eth/downloader/downloader.go (about)

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