github.com/vantum/vantum@v0.0.0-20180815184342-fe37d5f7a990/eth/downloader/downloader.go (about)

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