github.com/puppeth/go-ethereum@v0.8.6-0.20171014130046-e9295163aa25/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  	return d.syncWithPeer(p, hash, td)
   398  }
   399  
   400  // syncWithPeer starts a block synchronization based on the hash chain from the
   401  // specified peer and head hash.
   402  func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.Int) (err error) {
   403  	d.mux.Post(StartEvent{})
   404  	defer func() {
   405  		// reset on error
   406  		if err != nil {
   407  			d.mux.Post(FailedEvent{err})
   408  		} else {
   409  			d.mux.Post(DoneEvent{})
   410  		}
   411  	}()
   412  	if p.version < 62 {
   413  		return errTooOld
   414  	}
   415  
   416  	log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", d.mode)
   417  	defer func(start time.Time) {
   418  		log.Debug("Synchronisation terminated", "elapsed", time.Since(start))
   419  	}(time.Now())
   420  
   421  	// Look up the sync boundaries: the common ancestor and the target block
   422  	latest, err := d.fetchHeight(p)
   423  	if err != nil {
   424  		return err
   425  	}
   426  	height := latest.Number.Uint64()
   427  
   428  	origin, err := d.findAncestor(p, height)
   429  	if err != nil {
   430  		return err
   431  	}
   432  	d.syncStatsLock.Lock()
   433  	if d.syncStatsChainHeight <= origin || d.syncStatsChainOrigin > origin {
   434  		d.syncStatsChainOrigin = origin
   435  	}
   436  	d.syncStatsChainHeight = height
   437  	d.syncStatsLock.Unlock()
   438  
   439  	// Initiate the sync using a concurrent header and content retrieval algorithm
   440  	pivot := uint64(0)
   441  	switch d.mode {
   442  	case LightSync:
   443  		pivot = height
   444  	case FastSync:
   445  		// Calculate the new fast/slow sync pivot point
   446  		if d.fsPivotLock == nil {
   447  			pivotOffset, err := rand.Int(rand.Reader, big.NewInt(int64(fsPivotInterval)))
   448  			if err != nil {
   449  				panic(fmt.Sprintf("Failed to access crypto random source: %v", err))
   450  			}
   451  			if height > uint64(fsMinFullBlocks)+pivotOffset.Uint64() {
   452  				pivot = height - uint64(fsMinFullBlocks) - pivotOffset.Uint64()
   453  			}
   454  		} else {
   455  			// Pivot point locked in, use this and do not pick a new one!
   456  			pivot = d.fsPivotLock.Number.Uint64()
   457  		}
   458  		// If the point is below the origin, move origin back to ensure state download
   459  		if pivot < origin {
   460  			if pivot > 0 {
   461  				origin = pivot - 1
   462  			} else {
   463  				origin = 0
   464  			}
   465  		}
   466  		log.Debug("Fast syncing until pivot block", "pivot", pivot)
   467  	}
   468  	d.queue.Prepare(origin+1, d.mode, pivot, latest)
   469  	if d.syncInitHook != nil {
   470  		d.syncInitHook(origin, height)
   471  	}
   472  
   473  	fetchers := []func() error{
   474  		func() error { return d.fetchHeaders(p, origin+1) }, // Headers are always retrieved
   475  		func() error { return d.fetchBodies(origin + 1) },   // Bodies are retrieved during normal and fast sync
   476  		func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during fast sync
   477  		func() error { return d.processHeaders(origin+1, td) },
   478  	}
   479  	if d.mode == FastSync {
   480  		fetchers = append(fetchers, func() error { return d.processFastSyncContent(latest) })
   481  	} else if d.mode == FullSync {
   482  		fetchers = append(fetchers, d.processFullSyncContent)
   483  	}
   484  	err = d.spawnSync(fetchers)
   485  	if err != nil && d.mode == FastSync && d.fsPivotLock != nil {
   486  		// If sync failed in the critical section, bump the fail counter.
   487  		atomic.AddUint32(&d.fsPivotFails, 1)
   488  	}
   489  	return err
   490  }
   491  
   492  // spawnSync runs d.process and all given fetcher functions to completion in
   493  // separate goroutines, returning the first error that appears.
   494  func (d *Downloader) spawnSync(fetchers []func() error) error {
   495  	var wg sync.WaitGroup
   496  	errc := make(chan error, len(fetchers))
   497  	wg.Add(len(fetchers))
   498  	for _, fn := range fetchers {
   499  		fn := fn
   500  		go func() { defer wg.Done(); errc <- fn() }()
   501  	}
   502  	// Wait for the first error, then terminate the others.
   503  	var err error
   504  	for i := 0; i < len(fetchers); i++ {
   505  		if i == len(fetchers)-1 {
   506  			// Close the queue when all fetchers have exited.
   507  			// This will cause the block processor to end when
   508  			// it has processed the queue.
   509  			d.queue.Close()
   510  		}
   511  		if err = <-errc; err != nil {
   512  			break
   513  		}
   514  	}
   515  	d.queue.Close()
   516  	d.Cancel()
   517  	wg.Wait()
   518  	return err
   519  }
   520  
   521  // Cancel cancels all of the operations and resets the queue. It returns true
   522  // if the cancel operation was completed.
   523  func (d *Downloader) Cancel() {
   524  	// Close the current cancel channel
   525  	d.cancelLock.Lock()
   526  	if d.cancelCh != nil {
   527  		select {
   528  		case <-d.cancelCh:
   529  			// Channel was already closed
   530  		default:
   531  			close(d.cancelCh)
   532  		}
   533  	}
   534  	d.cancelLock.Unlock()
   535  }
   536  
   537  // Terminate interrupts the downloader, canceling all pending operations.
   538  // The downloader cannot be reused after calling Terminate.
   539  func (d *Downloader) Terminate() {
   540  	// Close the termination channel (make sure double close is allowed)
   541  	d.quitLock.Lock()
   542  	select {
   543  	case <-d.quitCh:
   544  	default:
   545  		close(d.quitCh)
   546  	}
   547  	d.quitLock.Unlock()
   548  
   549  	// Cancel any pending download requests
   550  	d.Cancel()
   551  }
   552  
   553  // fetchHeight retrieves the head header of the remote peer to aid in estimating
   554  // the total time a pending synchronisation would take.
   555  func (d *Downloader) fetchHeight(p *peerConnection) (*types.Header, error) {
   556  	p.log.Debug("Retrieving remote chain height")
   557  
   558  	// Request the advertised remote head block and wait for the response
   559  	head, _ := p.peer.Head()
   560  	go p.peer.RequestHeadersByHash(head, 1, 0, false)
   561  
   562  	ttl := d.requestTTL()
   563  	timeout := time.After(ttl)
   564  	for {
   565  		select {
   566  		case <-d.cancelCh:
   567  			return nil, errCancelBlockFetch
   568  
   569  		case packet := <-d.headerCh:
   570  			// Discard anything not from the origin peer
   571  			if packet.PeerId() != p.id {
   572  				log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
   573  				break
   574  			}
   575  			// Make sure the peer actually gave something valid
   576  			headers := packet.(*headerPack).headers
   577  			if len(headers) != 1 {
   578  				p.log.Debug("Multiple headers for single request", "headers", len(headers))
   579  				return nil, errBadPeer
   580  			}
   581  			head := headers[0]
   582  			p.log.Debug("Remote head header identified", "number", head.Number, "hash", head.Hash())
   583  			return head, nil
   584  
   585  		case <-timeout:
   586  			p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
   587  			return nil, errTimeout
   588  
   589  		case <-d.bodyCh:
   590  		case <-d.receiptCh:
   591  			// Out of bounds delivery, ignore
   592  		}
   593  	}
   594  }
   595  
   596  // findAncestor tries to locate the common ancestor link of the local chain and
   597  // a remote peers blockchain. In the general case when our node was in sync and
   598  // on the correct chain, checking the top N links should already get us a match.
   599  // In the rare scenario when we ended up on a long reorganisation (i.e. none of
   600  // the head links match), we do a binary search to find the common ancestor.
   601  func (d *Downloader) findAncestor(p *peerConnection, height uint64) (uint64, error) {
   602  	// Figure out the valid ancestor range to prevent rewrite attacks
   603  	floor, ceil := int64(-1), d.lightchain.CurrentHeader().Number.Uint64()
   604  
   605  	p.log.Debug("Looking for common ancestor", "local", ceil, "remote", height)
   606  	if d.mode == FullSync {
   607  		ceil = d.blockchain.CurrentBlock().NumberU64()
   608  	} else if d.mode == FastSync {
   609  		ceil = d.blockchain.CurrentFastBlock().NumberU64()
   610  	}
   611  	if ceil >= MaxForkAncestry {
   612  		floor = int64(ceil - MaxForkAncestry)
   613  	}
   614  	// Request the topmost blocks to short circuit binary ancestor lookup
   615  	head := ceil
   616  	if head > height {
   617  		head = height
   618  	}
   619  	from := int64(head) - int64(MaxHeaderFetch)
   620  	if from < 0 {
   621  		from = 0
   622  	}
   623  	// Span out with 15 block gaps into the future to catch bad head reports
   624  	limit := 2 * MaxHeaderFetch / 16
   625  	count := 1 + int((int64(ceil)-from)/16)
   626  	if count > limit {
   627  		count = limit
   628  	}
   629  	go p.peer.RequestHeadersByNumber(uint64(from), count, 15, false)
   630  
   631  	// Wait for the remote response to the head fetch
   632  	number, hash := uint64(0), common.Hash{}
   633  
   634  	ttl := d.requestTTL()
   635  	timeout := time.After(ttl)
   636  
   637  	for finished := false; !finished; {
   638  		select {
   639  		case <-d.cancelCh:
   640  			return 0, errCancelHeaderFetch
   641  
   642  		case packet := <-d.headerCh:
   643  			// Discard anything not from the origin peer
   644  			if packet.PeerId() != p.id {
   645  				log.Debug("Received headers from incorrect peer", "peer", packet.PeerId())
   646  				break
   647  			}
   648  			// Make sure the peer actually gave something valid
   649  			headers := packet.(*headerPack).headers
   650  			if len(headers) == 0 {
   651  				p.log.Warn("Empty head header set")
   652  				return 0, errEmptyHeaderSet
   653  			}
   654  			// Make sure the peer's reply conforms to the request
   655  			for i := 0; i < len(headers); i++ {
   656  				if number := headers[i].Number.Int64(); number != from+int64(i)*16 {
   657  					p.log.Warn("Head headers broke chain ordering", "index", i, "requested", from+int64(i)*16, "received", number)
   658  					return 0, errInvalidChain
   659  				}
   660  			}
   661  			// Check if a common ancestor was found
   662  			finished = true
   663  			for i := len(headers) - 1; i >= 0; i-- {
   664  				// Skip any headers that underflow/overflow our requested set
   665  				if headers[i].Number.Int64() < from || headers[i].Number.Uint64() > ceil {
   666  					continue
   667  				}
   668  				// Otherwise check if we already know the header or not
   669  				if (d.mode == FullSync && d.blockchain.HasBlockAndState(headers[i].Hash())) || (d.mode != FullSync && d.lightchain.HasHeader(headers[i].Hash(), headers[i].Number.Uint64())) {
   670  					number, hash = headers[i].Number.Uint64(), headers[i].Hash()
   671  
   672  					// If every header is known, even future ones, the peer straight out lied about its head
   673  					if number > height && i == limit-1 {
   674  						p.log.Warn("Lied about chain head", "reported", height, "found", number)
   675  						return 0, errStallingPeer
   676  					}
   677  					break
   678  				}
   679  			}
   680  
   681  		case <-timeout:
   682  			p.log.Debug("Waiting for head header timed out", "elapsed", ttl)
   683  			return 0, errTimeout
   684  
   685  		case <-d.bodyCh:
   686  		case <-d.receiptCh:
   687  			// Out of bounds delivery, ignore
   688  		}
   689  	}
   690  	// If the head fetch already found an ancestor, return
   691  	if !common.EmptyHash(hash) {
   692  		if int64(number) <= floor {
   693  			p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
   694  			return 0, errInvalidAncestor
   695  		}
   696  		p.log.Debug("Found common ancestor", "number", number, "hash", hash)
   697  		return number, nil
   698  	}
   699  	// Ancestor not found, we need to binary search over our chain
   700  	start, end := uint64(0), head
   701  	if floor > 0 {
   702  		start = uint64(floor)
   703  	}
   704  	for start+1 < end {
   705  		// Split our chain interval in two, and request the hash to cross check
   706  		check := (start + end) / 2
   707  
   708  		ttl := d.requestTTL()
   709  		timeout := time.After(ttl)
   710  
   711  		go p.peer.RequestHeadersByNumber(uint64(check), 1, 0, false)
   712  
   713  		// Wait until a reply arrives to this request
   714  		for arrived := false; !arrived; {
   715  			select {
   716  			case <-d.cancelCh:
   717  				return 0, errCancelHeaderFetch
   718  
   719  			case packer := <-d.headerCh:
   720  				// Discard anything not from the origin peer
   721  				if packer.PeerId() != p.id {
   722  					log.Debug("Received headers from incorrect peer", "peer", packer.PeerId())
   723  					break
   724  				}
   725  				// Make sure the peer actually gave something valid
   726  				headers := packer.(*headerPack).headers
   727  				if len(headers) != 1 {
   728  					p.log.Debug("Multiple headers for single request", "headers", len(headers))
   729  					return 0, errBadPeer
   730  				}
   731  				arrived = true
   732  
   733  				// Modify the search interval based on the response
   734  				if (d.mode == FullSync && !d.blockchain.HasBlockAndState(headers[0].Hash())) || (d.mode != FullSync && !d.lightchain.HasHeader(headers[0].Hash(), headers[0].Number.Uint64())) {
   735  					end = check
   736  					break
   737  				}
   738  				header := d.lightchain.GetHeaderByHash(headers[0].Hash()) // Independent of sync mode, header surely exists
   739  				if header.Number.Uint64() != check {
   740  					p.log.Debug("Received non requested header", "number", header.Number, "hash", header.Hash(), "request", check)
   741  					return 0, errBadPeer
   742  				}
   743  				start = check
   744  
   745  			case <-timeout:
   746  				p.log.Debug("Waiting for search header timed out", "elapsed", ttl)
   747  				return 0, errTimeout
   748  
   749  			case <-d.bodyCh:
   750  			case <-d.receiptCh:
   751  				// Out of bounds delivery, ignore
   752  			}
   753  		}
   754  	}
   755  	// Ensure valid ancestry and return
   756  	if int64(start) <= floor {
   757  		p.log.Warn("Ancestor below allowance", "number", start, "hash", hash, "allowance", floor)
   758  		return 0, errInvalidAncestor
   759  	}
   760  	p.log.Debug("Found common ancestor", "number", start, "hash", hash)
   761  	return start, nil
   762  }
   763  
   764  // fetchHeaders keeps retrieving headers concurrently from the number
   765  // requested, until no more are returned, potentially throttling on the way. To
   766  // facilitate concurrency but still protect against malicious nodes sending bad
   767  // headers, we construct a header chain skeleton using the "origin" peer we are
   768  // syncing with, and fill in the missing headers using anyone else. Headers from
   769  // other peers are only accepted if they map cleanly to the skeleton. If no one
   770  // can fill in the skeleton - not even the origin peer - it's assumed invalid and
   771  // the origin is dropped.
   772  func (d *Downloader) fetchHeaders(p *peerConnection, from uint64) error {
   773  	p.log.Debug("Directing header downloads", "origin", from)
   774  	defer p.log.Debug("Header download terminated")
   775  
   776  	// Create a timeout timer, and the associated header fetcher
   777  	skeleton := true            // Skeleton assembly phase or finishing up
   778  	request := time.Now()       // time of the last skeleton fetch request
   779  	timeout := time.NewTimer(0) // timer to dump a non-responsive active peer
   780  	<-timeout.C                 // timeout channel should be initially empty
   781  	defer timeout.Stop()
   782  
   783  	var ttl time.Duration
   784  	getHeaders := func(from uint64) {
   785  		request = time.Now()
   786  
   787  		ttl = d.requestTTL()
   788  		timeout.Reset(ttl)
   789  
   790  		if skeleton {
   791  			p.log.Trace("Fetching skeleton headers", "count", MaxHeaderFetch, "from", from)
   792  			go p.peer.RequestHeadersByNumber(from+uint64(MaxHeaderFetch)-1, MaxSkeletonSize, MaxHeaderFetch-1, false)
   793  		} else {
   794  			p.log.Trace("Fetching full headers", "count", MaxHeaderFetch, "from", from)
   795  			go p.peer.RequestHeadersByNumber(from, MaxHeaderFetch, 0, false)
   796  		}
   797  	}
   798  	// Start pulling the header chain skeleton until all is done
   799  	getHeaders(from)
   800  
   801  	for {
   802  		select {
   803  		case <-d.cancelCh:
   804  			return errCancelHeaderFetch
   805  
   806  		case packet := <-d.headerCh:
   807  			// Make sure the active peer is giving us the skeleton headers
   808  			if packet.PeerId() != p.id {
   809  				log.Debug("Received skeleton from incorrect peer", "peer", packet.PeerId())
   810  				break
   811  			}
   812  			headerReqTimer.UpdateSince(request)
   813  			timeout.Stop()
   814  
   815  			// If the skeleton's finished, pull any remaining head headers directly from the origin
   816  			if packet.Items() == 0 && skeleton {
   817  				skeleton = false
   818  				getHeaders(from)
   819  				continue
   820  			}
   821  			// If no more headers are inbound, notify the content fetchers and return
   822  			if packet.Items() == 0 {
   823  				p.log.Debug("No more headers available")
   824  				select {
   825  				case d.headerProcCh <- nil:
   826  					return nil
   827  				case <-d.cancelCh:
   828  					return errCancelHeaderFetch
   829  				}
   830  			}
   831  			headers := packet.(*headerPack).headers
   832  
   833  			// If we received a skeleton batch, resolve internals concurrently
   834  			if skeleton {
   835  				filled, proced, err := d.fillHeaderSkeleton(from, headers)
   836  				if err != nil {
   837  					p.log.Debug("Skeleton chain invalid", "err", err)
   838  					return errInvalidChain
   839  				}
   840  				headers = filled[proced:]
   841  				from += uint64(proced)
   842  			}
   843  			// Insert all the new headers and fetch the next batch
   844  			if len(headers) > 0 {
   845  				p.log.Trace("Scheduling new headers", "count", len(headers), "from", from)
   846  				select {
   847  				case d.headerProcCh <- headers:
   848  				case <-d.cancelCh:
   849  					return errCancelHeaderFetch
   850  				}
   851  				from += uint64(len(headers))
   852  			}
   853  			getHeaders(from)
   854  
   855  		case <-timeout.C:
   856  			// Header retrieval timed out, consider the peer bad and drop
   857  			p.log.Debug("Header request timed out", "elapsed", ttl)
   858  			headerTimeoutMeter.Mark(1)
   859  			d.dropPeer(p.id)
   860  
   861  			// Finish the sync gracefully instead of dumping the gathered data though
   862  			for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
   863  				select {
   864  				case ch <- false:
   865  				case <-d.cancelCh:
   866  				}
   867  			}
   868  			select {
   869  			case d.headerProcCh <- nil:
   870  			case <-d.cancelCh:
   871  			}
   872  			return errBadPeer
   873  		}
   874  	}
   875  }
   876  
   877  // fillHeaderSkeleton concurrently retrieves headers from all our available peers
   878  // and maps them to the provided skeleton header chain.
   879  //
   880  // Any partial results from the beginning of the skeleton is (if possible) forwarded
   881  // immediately to the header processor to keep the rest of the pipeline full even
   882  // in the case of header stalls.
   883  //
   884  // The method returs the entire filled skeleton and also the number of headers
   885  // already forwarded for processing.
   886  func (d *Downloader) fillHeaderSkeleton(from uint64, skeleton []*types.Header) ([]*types.Header, int, error) {
   887  	log.Debug("Filling up skeleton", "from", from)
   888  	d.queue.ScheduleSkeleton(from, skeleton)
   889  
   890  	var (
   891  		deliver = func(packet dataPack) (int, error) {
   892  			pack := packet.(*headerPack)
   893  			return d.queue.DeliverHeaders(pack.peerId, pack.headers, d.headerProcCh)
   894  		}
   895  		expire   = func() map[string]int { return d.queue.ExpireHeaders(d.requestTTL()) }
   896  		throttle = func() bool { return false }
   897  		reserve  = func(p *peerConnection, count int) (*fetchRequest, bool, error) {
   898  			return d.queue.ReserveHeaders(p, count), false, nil
   899  		}
   900  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchHeaders(req.From, MaxHeaderFetch) }
   901  		capacity = func(p *peerConnection) int { return p.HeaderCapacity(d.requestRTT()) }
   902  		setIdle  = func(p *peerConnection, accepted int) { p.SetHeadersIdle(accepted) }
   903  	)
   904  	err := d.fetchParts(errCancelHeaderFetch, d.headerCh, deliver, d.queue.headerContCh, expire,
   905  		d.queue.PendingHeaders, d.queue.InFlightHeaders, throttle, reserve,
   906  		nil, fetch, d.queue.CancelHeaders, capacity, d.peers.HeaderIdlePeers, setIdle, "headers")
   907  
   908  	log.Debug("Skeleton fill terminated", "err", err)
   909  
   910  	filled, proced := d.queue.RetrieveHeaders()
   911  	return filled, proced, err
   912  }
   913  
   914  // fetchBodies iteratively downloads the scheduled block bodies, taking any
   915  // available peers, reserving a chunk of blocks for each, waiting for delivery
   916  // and also periodically checking for timeouts.
   917  func (d *Downloader) fetchBodies(from uint64) error {
   918  	log.Debug("Downloading block bodies", "origin", from)
   919  
   920  	var (
   921  		deliver = func(packet dataPack) (int, error) {
   922  			pack := packet.(*bodyPack)
   923  			return d.queue.DeliverBodies(pack.peerId, pack.transactions, pack.uncles)
   924  		}
   925  		expire   = func() map[string]int { return d.queue.ExpireBodies(d.requestTTL()) }
   926  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchBodies(req) }
   927  		capacity = func(p *peerConnection) int { return p.BlockCapacity(d.requestRTT()) }
   928  		setIdle  = func(p *peerConnection, accepted int) { p.SetBodiesIdle(accepted) }
   929  	)
   930  	err := d.fetchParts(errCancelBodyFetch, d.bodyCh, deliver, d.bodyWakeCh, expire,
   931  		d.queue.PendingBlocks, d.queue.InFlightBlocks, d.queue.ShouldThrottleBlocks, d.queue.ReserveBodies,
   932  		d.bodyFetchHook, fetch, d.queue.CancelBodies, capacity, d.peers.BodyIdlePeers, setIdle, "bodies")
   933  
   934  	log.Debug("Block body download terminated", "err", err)
   935  	return err
   936  }
   937  
   938  // fetchReceipts iteratively downloads the scheduled block receipts, taking any
   939  // available peers, reserving a chunk of receipts for each, waiting for delivery
   940  // and also periodically checking for timeouts.
   941  func (d *Downloader) fetchReceipts(from uint64) error {
   942  	log.Debug("Downloading transaction receipts", "origin", from)
   943  
   944  	var (
   945  		deliver = func(packet dataPack) (int, error) {
   946  			pack := packet.(*receiptPack)
   947  			return d.queue.DeliverReceipts(pack.peerId, pack.receipts)
   948  		}
   949  		expire   = func() map[string]int { return d.queue.ExpireReceipts(d.requestTTL()) }
   950  		fetch    = func(p *peerConnection, req *fetchRequest) error { return p.FetchReceipts(req) }
   951  		capacity = func(p *peerConnection) int { return p.ReceiptCapacity(d.requestRTT()) }
   952  		setIdle  = func(p *peerConnection, accepted int) { p.SetReceiptsIdle(accepted) }
   953  	)
   954  	err := d.fetchParts(errCancelReceiptFetch, d.receiptCh, deliver, d.receiptWakeCh, expire,
   955  		d.queue.PendingReceipts, d.queue.InFlightReceipts, d.queue.ShouldThrottleReceipts, d.queue.ReserveReceipts,
   956  		d.receiptFetchHook, fetch, d.queue.CancelReceipts, capacity, d.peers.ReceiptIdlePeers, setIdle, "receipts")
   957  
   958  	log.Debug("Transaction receipt download terminated", "err", err)
   959  	return err
   960  }
   961  
   962  // fetchParts iteratively downloads scheduled block parts, taking any available
   963  // peers, reserving a chunk of fetch requests for each, waiting for delivery and
   964  // also periodically checking for timeouts.
   965  //
   966  // As the scheduling/timeout logic mostly is the same for all downloaded data
   967  // types, this method is used by each for data gathering and is instrumented with
   968  // various callbacks to handle the slight differences between processing them.
   969  //
   970  // The instrumentation parameters:
   971  //  - errCancel:   error type to return if the fetch operation is cancelled (mostly makes logging nicer)
   972  //  - deliveryCh:  channel from which to retrieve downloaded data packets (merged from all concurrent peers)
   973  //  - deliver:     processing callback to deliver data packets into type specific download queues (usually within `queue`)
   974  //  - wakeCh:      notification channel for waking the fetcher when new tasks are available (or sync completed)
   975  //  - expire:      task callback method to abort requests that took too long and return the faulty peers (traffic shaping)
   976  //  - pending:     task callback for the number of requests still needing download (detect completion/non-completability)
   977  //  - inFlight:    task callback for the number of in-progress requests (wait for all active downloads to finish)
   978  //  - throttle:    task callback to check if the processing queue is full and activate throttling (bound memory use)
   979  //  - reserve:     task callback to reserve new download tasks to a particular peer (also signals partial completions)
   980  //  - fetchHook:   tester callback to notify of new tasks being initiated (allows testing the scheduling logic)
   981  //  - fetch:       network callback to actually send a particular download request to a physical remote peer
   982  //  - cancel:      task callback to abort an in-flight download request and allow rescheduling it (in case of lost peer)
   983  //  - capacity:    network callback to retrieve the estimated type-specific bandwidth capacity of a peer (traffic shaping)
   984  //  - idle:        network callback to retrieve the currently (type specific) idle peers that can be assigned tasks
   985  //  - setIdle:     network callback to set a peer back to idle and update its estimated capacity (traffic shaping)
   986  //  - kind:        textual label of the type being downloaded to display in log mesages
   987  func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliver func(dataPack) (int, error), wakeCh chan bool,
   988  	expire func() map[string]int, pending func() int, inFlight func() bool, throttle func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, error),
   989  	fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int,
   990  	idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int), kind string) error {
   991  
   992  	// Create a ticker to detect expired retrieval tasks
   993  	ticker := time.NewTicker(100 * time.Millisecond)
   994  	defer ticker.Stop()
   995  
   996  	update := make(chan struct{}, 1)
   997  
   998  	// Prepare the queue and fetch block parts until the block header fetcher's done
   999  	finished := false
  1000  	for {
  1001  		select {
  1002  		case <-d.cancelCh:
  1003  			return errCancel
  1004  
  1005  		case packet := <-deliveryCh:
  1006  			// If the peer was previously banned and failed to deliver it's pack
  1007  			// in a reasonable time frame, ignore it's message.
  1008  			if peer := d.peers.Peer(packet.PeerId()); peer != nil {
  1009  				// Deliver the received chunk of data and check chain validity
  1010  				accepted, err := deliver(packet)
  1011  				if err == errInvalidChain {
  1012  					return err
  1013  				}
  1014  				// Unless a peer delivered something completely else than requested (usually
  1015  				// caused by a timed out request which came through in the end), set it to
  1016  				// idle. If the delivery's stale, the peer should have already been idled.
  1017  				if err != errStaleDelivery {
  1018  					setIdle(peer, accepted)
  1019  				}
  1020  				// Issue a log to the user to see what's going on
  1021  				switch {
  1022  				case err == nil && packet.Items() == 0:
  1023  					peer.log.Trace("Requested data not delivered", "type", kind)
  1024  				case err == nil:
  1025  					peer.log.Trace("Delivered new batch of data", "type", kind, "count", packet.Stats())
  1026  				default:
  1027  					peer.log.Trace("Failed to deliver retrieved data", "type", kind, "err", err)
  1028  				}
  1029  			}
  1030  			// Blocks assembled, try to update the progress
  1031  			select {
  1032  			case update <- struct{}{}:
  1033  			default:
  1034  			}
  1035  
  1036  		case cont := <-wakeCh:
  1037  			// The header fetcher sent a continuation flag, check if it's done
  1038  			if !cont {
  1039  				finished = true
  1040  			}
  1041  			// Headers arrive, try to update the progress
  1042  			select {
  1043  			case update <- struct{}{}:
  1044  			default:
  1045  			}
  1046  
  1047  		case <-ticker.C:
  1048  			// Sanity check update the progress
  1049  			select {
  1050  			case update <- struct{}{}:
  1051  			default:
  1052  			}
  1053  
  1054  		case <-update:
  1055  			// Short circuit if we lost all our peers
  1056  			if d.peers.Len() == 0 {
  1057  				return errNoPeers
  1058  			}
  1059  			// Check for fetch request timeouts and demote the responsible peers
  1060  			for pid, fails := range expire() {
  1061  				if peer := d.peers.Peer(pid); peer != nil {
  1062  					// If a lot of retrieval elements expired, we might have overestimated the remote peer or perhaps
  1063  					// ourselves. Only reset to minimal throughput but don't drop just yet. If even the minimal times
  1064  					// out that sync wise we need to get rid of the peer.
  1065  					//
  1066  					// The reason the minimum threshold is 2 is because the downloader tries to estimate the bandwidth
  1067  					// and latency of a peer separately, which requires pushing the measures capacity a bit and seeing
  1068  					// how response times reacts, to it always requests one more than the minimum (i.e. min 2).
  1069  					if fails > 2 {
  1070  						peer.log.Trace("Data delivery timed out", "type", kind)
  1071  						setIdle(peer, 0)
  1072  					} else {
  1073  						peer.log.Debug("Stalling delivery, dropping", "type", kind)
  1074  						d.dropPeer(pid)
  1075  					}
  1076  				}
  1077  			}
  1078  			// If there's nothing more to fetch, wait or terminate
  1079  			if pending() == 0 {
  1080  				if !inFlight() && finished {
  1081  					log.Debug("Data fetching completed", "type", kind)
  1082  					return nil
  1083  				}
  1084  				break
  1085  			}
  1086  			// Send a download request to all idle peers, until throttled
  1087  			progressed, throttled, running := false, false, inFlight()
  1088  			idles, total := idle()
  1089  
  1090  			for _, peer := range idles {
  1091  				// Short circuit if throttling activated
  1092  				if throttle() {
  1093  					throttled = true
  1094  					break
  1095  				}
  1096  				// Short circuit if there is no more available task.
  1097  				if pending() == 0 {
  1098  					break
  1099  				}
  1100  				// Reserve a chunk of fetches for a peer. A nil can mean either that
  1101  				// no more headers are available, or that the peer is known not to
  1102  				// have them.
  1103  				request, progress, err := reserve(peer, capacity(peer))
  1104  				if err != nil {
  1105  					return err
  1106  				}
  1107  				if progress {
  1108  					progressed = true
  1109  				}
  1110  				if request == nil {
  1111  					continue
  1112  				}
  1113  				if request.From > 0 {
  1114  					peer.log.Trace("Requesting new batch of data", "type", kind, "from", request.From)
  1115  				} else if len(request.Headers) > 0 {
  1116  					peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Headers), "from", request.Headers[0].Number)
  1117  				} else {
  1118  					peer.log.Trace("Requesting new batch of data", "type", kind, "count", len(request.Hashes))
  1119  				}
  1120  				// Fetch the chunk and make sure any errors return the hashes to the queue
  1121  				if fetchHook != nil {
  1122  					fetchHook(request.Headers)
  1123  				}
  1124  				if err := fetch(peer, request); err != nil {
  1125  					// Although we could try and make an attempt to fix this, this error really
  1126  					// means that we've double allocated a fetch task to a peer. If that is the
  1127  					// case, the internal state of the downloader and the queue is very wrong so
  1128  					// better hard crash and note the error instead of silently accumulating into
  1129  					// a much bigger issue.
  1130  					panic(fmt.Sprintf("%v: %s fetch assignment failed", peer, kind))
  1131  				}
  1132  				running = true
  1133  			}
  1134  			// Make sure that we have peers available for fetching. If all peers have been tried
  1135  			// and all failed throw an error
  1136  			if !progressed && !throttled && !running && len(idles) == total && pending() > 0 {
  1137  				return errPeersUnavailable
  1138  			}
  1139  		}
  1140  	}
  1141  }
  1142  
  1143  // processHeaders takes batches of retrieved headers from an input channel and
  1144  // keeps processing and scheduling them into the header chain and downloader's
  1145  // queue until the stream ends or a failure occurs.
  1146  func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
  1147  	// Calculate the pivoting point for switching from fast to slow sync
  1148  	pivot := d.queue.FastSyncPivot()
  1149  
  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  			// If we're already past the pivot point, this could be an attack, thread carefully
  1176  			if rollback[len(rollback)-1].Number.Uint64() > pivot {
  1177  				// If we didn't ever fail, lock in the pivot header (must! not! change!)
  1178  				if atomic.LoadUint32(&d.fsPivotFails) == 0 {
  1179  					for _, header := range rollback {
  1180  						if header.Number.Uint64() == pivot {
  1181  							log.Warn("Fast-sync pivot locked in", "number", pivot, "hash", header.Hash())
  1182  							d.fsPivotLock = header
  1183  						}
  1184  					}
  1185  				}
  1186  			}
  1187  		}
  1188  	}()
  1189  
  1190  	// Wait for batches of headers to process
  1191  	gotHeaders := false
  1192  
  1193  	for {
  1194  		select {
  1195  		case <-d.cancelCh:
  1196  			return errCancelHeaderProcessing
  1197  
  1198  		case headers := <-d.headerProcCh:
  1199  			// Terminate header processing if we synced up
  1200  			if len(headers) == 0 {
  1201  				// Notify everyone that headers are fully processed
  1202  				for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1203  					select {
  1204  					case ch <- false:
  1205  					case <-d.cancelCh:
  1206  					}
  1207  				}
  1208  				// If no headers were retrieved at all, the peer violated it's TD promise that it had a
  1209  				// better chain compared to ours. The only exception is if it's promised blocks were
  1210  				// already imported by other means (e.g. fecher):
  1211  				//
  1212  				// R <remote peer>, L <local node>: Both at block 10
  1213  				// R: Mine block 11, and propagate it to L
  1214  				// L: Queue block 11 for import
  1215  				// L: Notice that R's head and TD increased compared to ours, start sync
  1216  				// L: Import of block 11 finishes
  1217  				// L: Sync begins, and finds common ancestor at 11
  1218  				// L: Request new headers up from 11 (R's TD was higher, it must have something)
  1219  				// R: Nothing to give
  1220  				if d.mode != LightSync {
  1221  					if !gotHeaders && td.Cmp(d.blockchain.GetTdByHash(d.blockchain.CurrentBlock().Hash())) > 0 {
  1222  						return errStallingPeer
  1223  					}
  1224  				}
  1225  				// If fast or light syncing, ensure promised headers are indeed delivered. This is
  1226  				// needed to detect scenarios where an attacker feeds a bad pivot and then bails out
  1227  				// of delivering the post-pivot blocks that would flag the invalid content.
  1228  				//
  1229  				// This check cannot be executed "as is" for full imports, since blocks may still be
  1230  				// queued for processing when the header download completes. However, as long as the
  1231  				// peer gave us something useful, we're already happy/progressed (above check).
  1232  				if d.mode == FastSync || d.mode == LightSync {
  1233  					if td.Cmp(d.lightchain.GetTdByHash(d.lightchain.CurrentHeader().Hash())) > 0 {
  1234  						return errStallingPeer
  1235  					}
  1236  				}
  1237  				// Disable any rollback and return
  1238  				rollback = nil
  1239  				return nil
  1240  			}
  1241  			// Otherwise split the chunk of headers into batches and process them
  1242  			gotHeaders = true
  1243  
  1244  			for len(headers) > 0 {
  1245  				// Terminate if something failed in between processing chunks
  1246  				select {
  1247  				case <-d.cancelCh:
  1248  					return errCancelHeaderProcessing
  1249  				default:
  1250  				}
  1251  				// Select the next chunk of headers to import
  1252  				limit := maxHeadersProcess
  1253  				if limit > len(headers) {
  1254  					limit = len(headers)
  1255  				}
  1256  				chunk := headers[:limit]
  1257  
  1258  				// In case of header only syncing, validate the chunk immediately
  1259  				if d.mode == FastSync || d.mode == LightSync {
  1260  					// Collect the yet unknown headers to mark them as uncertain
  1261  					unknown := make([]*types.Header, 0, len(headers))
  1262  					for _, header := range chunk {
  1263  						if !d.lightchain.HasHeader(header.Hash(), header.Number.Uint64()) {
  1264  							unknown = append(unknown, header)
  1265  						}
  1266  					}
  1267  					// If we're importing pure headers, verify based on their recentness
  1268  					frequency := fsHeaderCheckFrequency
  1269  					if chunk[len(chunk)-1].Number.Uint64()+uint64(fsHeaderForceVerify) > pivot {
  1270  						frequency = 1
  1271  					}
  1272  					if n, err := d.lightchain.InsertHeaderChain(chunk, frequency); err != nil {
  1273  						// If some headers were inserted, add them too to the rollback list
  1274  						if n > 0 {
  1275  							rollback = append(rollback, chunk[:n]...)
  1276  						}
  1277  						log.Debug("Invalid header encountered", "number", chunk[n].Number, "hash", chunk[n].Hash(), "err", err)
  1278  						return errInvalidChain
  1279  					}
  1280  					// All verifications passed, store newly found uncertain headers
  1281  					rollback = append(rollback, unknown...)
  1282  					if len(rollback) > fsHeaderSafetyNet {
  1283  						rollback = append(rollback[:0], rollback[len(rollback)-fsHeaderSafetyNet:]...)
  1284  					}
  1285  				}
  1286  				// If we're fast syncing and just pulled in the pivot, make sure it's the one locked in
  1287  				if d.mode == FastSync && d.fsPivotLock != nil && chunk[0].Number.Uint64() <= pivot && chunk[len(chunk)-1].Number.Uint64() >= pivot {
  1288  					if pivot := chunk[int(pivot-chunk[0].Number.Uint64())]; pivot.Hash() != d.fsPivotLock.Hash() {
  1289  						log.Warn("Pivot doesn't match locked in one", "remoteNumber", pivot.Number, "remoteHash", pivot.Hash(), "localNumber", d.fsPivotLock.Number, "localHash", d.fsPivotLock.Hash())
  1290  						return errInvalidChain
  1291  					}
  1292  				}
  1293  				// Unless we're doing light chains, schedule the headers for associated content retrieval
  1294  				if d.mode == FullSync || d.mode == FastSync {
  1295  					// If we've reached the allowed number of pending headers, stall a bit
  1296  					for d.queue.PendingBlocks() >= maxQueuedHeaders || d.queue.PendingReceipts() >= maxQueuedHeaders {
  1297  						select {
  1298  						case <-d.cancelCh:
  1299  							return errCancelHeaderProcessing
  1300  						case <-time.After(time.Second):
  1301  						}
  1302  					}
  1303  					// Otherwise insert the headers for content retrieval
  1304  					inserts := d.queue.Schedule(chunk, origin)
  1305  					if len(inserts) != len(chunk) {
  1306  						log.Debug("Stale headers")
  1307  						return errBadPeer
  1308  					}
  1309  				}
  1310  				headers = headers[limit:]
  1311  				origin += uint64(limit)
  1312  			}
  1313  			// Signal the content downloaders of the availablility of new tasks
  1314  			for _, ch := range []chan bool{d.bodyWakeCh, d.receiptWakeCh} {
  1315  				select {
  1316  				case ch <- true:
  1317  				default:
  1318  				}
  1319  			}
  1320  		}
  1321  	}
  1322  }
  1323  
  1324  // processFullSyncContent takes fetch results from the queue and imports them into the chain.
  1325  func (d *Downloader) processFullSyncContent() error {
  1326  	for {
  1327  		results := d.queue.WaitResults()
  1328  		if len(results) == 0 {
  1329  			return nil
  1330  		}
  1331  		if d.chainInsertHook != nil {
  1332  			d.chainInsertHook(results)
  1333  		}
  1334  		if err := d.importBlockResults(results); err != nil {
  1335  			return err
  1336  		}
  1337  	}
  1338  }
  1339  
  1340  func (d *Downloader) importBlockResults(results []*fetchResult) error {
  1341  	for len(results) != 0 {
  1342  		// Check for any termination requests. This makes clean shutdown faster.
  1343  		select {
  1344  		case <-d.quitCh:
  1345  			return errCancelContentProcessing
  1346  		default:
  1347  		}
  1348  		// Retrieve the a batch of results to import
  1349  		items := int(math.Min(float64(len(results)), float64(maxResultsProcess)))
  1350  		first, last := results[0].Header, results[items-1].Header
  1351  		log.Debug("Inserting downloaded chain", "items", len(results),
  1352  			"firstnum", first.Number, "firsthash", first.Hash(),
  1353  			"lastnum", last.Number, "lasthash", last.Hash(),
  1354  		)
  1355  		blocks := make([]*types.Block, items)
  1356  		for i, result := range results[:items] {
  1357  			blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1358  		}
  1359  		if index, err := d.blockchain.InsertChain(blocks); err != nil {
  1360  			log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1361  			return errInvalidChain
  1362  		}
  1363  		// Shift the results to the next batch
  1364  		results = results[items:]
  1365  	}
  1366  	return nil
  1367  }
  1368  
  1369  // processFastSyncContent takes fetch results from the queue and writes them to the
  1370  // database. It also controls the synchronisation of state nodes of the pivot block.
  1371  func (d *Downloader) processFastSyncContent(latest *types.Header) error {
  1372  	// Start syncing state of the reported head block.
  1373  	// This should get us most of the state of the pivot block.
  1374  	stateSync := d.syncState(latest.Root)
  1375  	defer stateSync.Cancel()
  1376  	go func() {
  1377  		if err := stateSync.Wait(); err != nil {
  1378  			d.queue.Close() // wake up WaitResults
  1379  		}
  1380  	}()
  1381  
  1382  	pivot := d.queue.FastSyncPivot()
  1383  	for {
  1384  		results := d.queue.WaitResults()
  1385  		if len(results) == 0 {
  1386  			return stateSync.Cancel()
  1387  		}
  1388  		if d.chainInsertHook != nil {
  1389  			d.chainInsertHook(results)
  1390  		}
  1391  		P, beforeP, afterP := splitAroundPivot(pivot, results)
  1392  		if err := d.commitFastSyncData(beforeP, stateSync); err != nil {
  1393  			return err
  1394  		}
  1395  		if P != nil {
  1396  			stateSync.Cancel()
  1397  			if err := d.commitPivotBlock(P); err != nil {
  1398  				return err
  1399  			}
  1400  		}
  1401  		if err := d.importBlockResults(afterP); err != nil {
  1402  			return err
  1403  		}
  1404  	}
  1405  }
  1406  
  1407  func splitAroundPivot(pivot uint64, results []*fetchResult) (p *fetchResult, before, after []*fetchResult) {
  1408  	for _, result := range results {
  1409  		num := result.Header.Number.Uint64()
  1410  		switch {
  1411  		case num < pivot:
  1412  			before = append(before, result)
  1413  		case num == pivot:
  1414  			p = result
  1415  		default:
  1416  			after = append(after, result)
  1417  		}
  1418  	}
  1419  	return p, before, after
  1420  }
  1421  
  1422  func (d *Downloader) commitFastSyncData(results []*fetchResult, stateSync *stateSync) error {
  1423  	for len(results) != 0 {
  1424  		// Check for any termination requests.
  1425  		select {
  1426  		case <-d.quitCh:
  1427  			return errCancelContentProcessing
  1428  		case <-stateSync.done:
  1429  			if err := stateSync.Wait(); err != nil {
  1430  				return err
  1431  			}
  1432  		default:
  1433  		}
  1434  		// Retrieve the a batch of results to import
  1435  		items := int(math.Min(float64(len(results)), float64(maxResultsProcess)))
  1436  		first, last := results[0].Header, results[items-1].Header
  1437  		log.Debug("Inserting fast-sync blocks", "items", len(results),
  1438  			"firstnum", first.Number, "firsthash", first.Hash(),
  1439  			"lastnumn", last.Number, "lasthash", last.Hash(),
  1440  		)
  1441  		blocks := make([]*types.Block, items)
  1442  		receipts := make([]types.Receipts, items)
  1443  		for i, result := range results[:items] {
  1444  			blocks[i] = types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1445  			receipts[i] = result.Receipts
  1446  		}
  1447  		if index, err := d.blockchain.InsertReceiptChain(blocks, receipts); err != nil {
  1448  			log.Debug("Downloaded item processing failed", "number", results[index].Header.Number, "hash", results[index].Header.Hash(), "err", err)
  1449  			return errInvalidChain
  1450  		}
  1451  		// Shift the results to the next batch
  1452  		results = results[items:]
  1453  	}
  1454  	return nil
  1455  }
  1456  
  1457  func (d *Downloader) commitPivotBlock(result *fetchResult) error {
  1458  	b := types.NewBlockWithHeader(result.Header).WithBody(result.Transactions, result.Uncles)
  1459  	// Sync the pivot block state. This should complete reasonably quickly because
  1460  	// we've already synced up to the reported head block state earlier.
  1461  	if err := d.syncState(b.Root()).Wait(); err != nil {
  1462  		return err
  1463  	}
  1464  	log.Debug("Committing fast sync pivot as new head", "number", b.Number(), "hash", b.Hash())
  1465  	if _, err := d.blockchain.InsertReceiptChain([]*types.Block{b}, []types.Receipts{result.Receipts}); err != nil {
  1466  		return err
  1467  	}
  1468  	return d.blockchain.FastSyncCommitHead(b.Hash())
  1469  }
  1470  
  1471  // DeliverHeaders injects a new batch of block headers received from a remote
  1472  // node into the download schedule.
  1473  func (d *Downloader) DeliverHeaders(id string, headers []*types.Header) (err error) {
  1474  	return d.deliver(id, d.headerCh, &headerPack{id, headers}, headerInMeter, headerDropMeter)
  1475  }
  1476  
  1477  // DeliverBodies injects a new batch of block bodies received from a remote node.
  1478  func (d *Downloader) DeliverBodies(id string, transactions [][]*types.Transaction, uncles [][]*types.Header) (err error) {
  1479  	return d.deliver(id, d.bodyCh, &bodyPack{id, transactions, uncles}, bodyInMeter, bodyDropMeter)
  1480  }
  1481  
  1482  // DeliverReceipts injects a new batch of receipts received from a remote node.
  1483  func (d *Downloader) DeliverReceipts(id string, receipts [][]*types.Receipt) (err error) {
  1484  	return d.deliver(id, d.receiptCh, &receiptPack{id, receipts}, receiptInMeter, receiptDropMeter)
  1485  }
  1486  
  1487  // DeliverNodeData injects a new batch of node state data received from a remote node.
  1488  func (d *Downloader) DeliverNodeData(id string, data [][]byte) (err error) {
  1489  	return d.deliver(id, d.stateCh, &statePack{id, data}, stateInMeter, stateDropMeter)
  1490  }
  1491  
  1492  // deliver injects a new batch of data received from a remote node.
  1493  func (d *Downloader) deliver(id string, destCh chan dataPack, packet dataPack, inMeter, dropMeter metrics.Meter) (err error) {
  1494  	// Update the delivery metrics for both good and failed deliveries
  1495  	inMeter.Mark(int64(packet.Items()))
  1496  	defer func() {
  1497  		if err != nil {
  1498  			dropMeter.Mark(int64(packet.Items()))
  1499  		}
  1500  	}()
  1501  	// Deliver or abort if the sync is canceled while queuing
  1502  	d.cancelLock.RLock()
  1503  	cancel := d.cancelCh
  1504  	d.cancelLock.RUnlock()
  1505  	if cancel == nil {
  1506  		return errNoSyncActive
  1507  	}
  1508  	select {
  1509  	case destCh <- packet:
  1510  		return nil
  1511  	case <-cancel:
  1512  		return errNoSyncActive
  1513  	}
  1514  }
  1515  
  1516  // qosTuner is the quality of service tuning loop that occasionally gathers the
  1517  // peer latency statistics and updates the estimated request round trip time.
  1518  func (d *Downloader) qosTuner() {
  1519  	for {
  1520  		// Retrieve the current median RTT and integrate into the previoust target RTT
  1521  		rtt := time.Duration(float64(1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
  1522  		atomic.StoreUint64(&d.rttEstimate, uint64(rtt))
  1523  
  1524  		// A new RTT cycle passed, increase our confidence in the estimated RTT
  1525  		conf := atomic.LoadUint64(&d.rttConfidence)
  1526  		conf = conf + (1000000-conf)/2
  1527  		atomic.StoreUint64(&d.rttConfidence, conf)
  1528  
  1529  		// Log the new QoS values and sleep until the next RTT
  1530  		log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1531  		select {
  1532  		case <-d.quitCh:
  1533  			return
  1534  		case <-time.After(rtt):
  1535  		}
  1536  	}
  1537  }
  1538  
  1539  // qosReduceConfidence is meant to be called when a new peer joins the downloader's
  1540  // peer set, needing to reduce the confidence we have in out QoS estimates.
  1541  func (d *Downloader) qosReduceConfidence() {
  1542  	// If we have a single peer, confidence is always 1
  1543  	peers := uint64(d.peers.Len())
  1544  	if peers == 0 {
  1545  		// Ensure peer connectivity races don't catch us off guard
  1546  		return
  1547  	}
  1548  	if peers == 1 {
  1549  		atomic.StoreUint64(&d.rttConfidence, 1000000)
  1550  		return
  1551  	}
  1552  	// If we have a ton of peers, don't drop confidence)
  1553  	if peers >= uint64(qosConfidenceCap) {
  1554  		return
  1555  	}
  1556  	// Otherwise drop the confidence factor
  1557  	conf := atomic.LoadUint64(&d.rttConfidence) * (peers - 1) / peers
  1558  	if float64(conf)/1000000 < rttMinConfidence {
  1559  		conf = uint64(rttMinConfidence * 1000000)
  1560  	}
  1561  	atomic.StoreUint64(&d.rttConfidence, conf)
  1562  
  1563  	rtt := time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1564  	log.Debug("Relaxed downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
  1565  }
  1566  
  1567  // requestRTT returns the current target round trip time for a download request
  1568  // to complete in.
  1569  //
  1570  // Note, the returned RTT is .9 of the actually estimated RTT. The reason is that
  1571  // the downloader tries to adapt queries to the RTT, so multiple RTT values can
  1572  // be adapted to, but smaller ones are preffered (stabler download stream).
  1573  func (d *Downloader) requestRTT() time.Duration {
  1574  	return time.Duration(atomic.LoadUint64(&d.rttEstimate)) * 9 / 10
  1575  }
  1576  
  1577  // requestTTL returns the current timeout allowance for a single download request
  1578  // to finish under.
  1579  func (d *Downloader) requestTTL() time.Duration {
  1580  	var (
  1581  		rtt  = time.Duration(atomic.LoadUint64(&d.rttEstimate))
  1582  		conf = float64(atomic.LoadUint64(&d.rttConfidence)) / 1000000.0
  1583  	)
  1584  	ttl := time.Duration(ttlScaling) * time.Duration(float64(rtt)/conf)
  1585  	if ttl > ttlLimit {
  1586  		ttl = ttlLimit
  1587  	}
  1588  	return ttl
  1589  }