github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/eth/downloader/downloader.go (about)

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