github.com/snowblossomcoin/go-ethereum@v1.9.25/eth/fetcher/block_fetcher.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 fetcher contains the announcement based header, blocks or transaction synchronisation.
    18  package fetcher
    19  
    20  import (
    21  	"errors"
    22  	"math/rand"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/common/prque"
    27  	"github.com/ethereum/go-ethereum/consensus"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/log"
    30  	"github.com/ethereum/go-ethereum/metrics"
    31  	"github.com/ethereum/go-ethereum/trie"
    32  )
    33  
    34  const (
    35  	lightTimeout  = time.Millisecond       // Time allowance before an announced header is explicitly requested
    36  	arriveTimeout = 500 * time.Millisecond // Time allowance before an announced block/transaction is explicitly requested
    37  	gatherSlack   = 100 * time.Millisecond // Interval used to collate almost-expired announces with fetches
    38  	fetchTimeout  = 5 * time.Second        // Maximum allotted time to return an explicitly requested block/transaction
    39  )
    40  
    41  const (
    42  	maxUncleDist = 7   // Maximum allowed backward distance from the chain head
    43  	maxQueueDist = 32  // Maximum allowed distance from the chain head to queue
    44  	hashLimit    = 256 // Maximum number of unique blocks or headers a peer may have announced
    45  	blockLimit   = 64  // Maximum number of unique blocks a peer may have delivered
    46  )
    47  
    48  var (
    49  	blockAnnounceInMeter   = metrics.NewRegisteredMeter("eth/fetcher/block/announces/in", nil)
    50  	blockAnnounceOutTimer  = metrics.NewRegisteredTimer("eth/fetcher/block/announces/out", nil)
    51  	blockAnnounceDropMeter = metrics.NewRegisteredMeter("eth/fetcher/block/announces/drop", nil)
    52  	blockAnnounceDOSMeter  = metrics.NewRegisteredMeter("eth/fetcher/block/announces/dos", nil)
    53  
    54  	blockBroadcastInMeter   = metrics.NewRegisteredMeter("eth/fetcher/block/broadcasts/in", nil)
    55  	blockBroadcastOutTimer  = metrics.NewRegisteredTimer("eth/fetcher/block/broadcasts/out", nil)
    56  	blockBroadcastDropMeter = metrics.NewRegisteredMeter("eth/fetcher/block/broadcasts/drop", nil)
    57  	blockBroadcastDOSMeter  = metrics.NewRegisteredMeter("eth/fetcher/block/broadcasts/dos", nil)
    58  
    59  	headerFetchMeter = metrics.NewRegisteredMeter("eth/fetcher/block/headers", nil)
    60  	bodyFetchMeter   = metrics.NewRegisteredMeter("eth/fetcher/block/bodies", nil)
    61  
    62  	headerFilterInMeter  = metrics.NewRegisteredMeter("eth/fetcher/block/filter/headers/in", nil)
    63  	headerFilterOutMeter = metrics.NewRegisteredMeter("eth/fetcher/block/filter/headers/out", nil)
    64  	bodyFilterInMeter    = metrics.NewRegisteredMeter("eth/fetcher/block/filter/bodies/in", nil)
    65  	bodyFilterOutMeter   = metrics.NewRegisteredMeter("eth/fetcher/block/filter/bodies/out", nil)
    66  )
    67  
    68  var errTerminated = errors.New("terminated")
    69  
    70  // HeaderRetrievalFn is a callback type for retrieving a header from the local chain.
    71  type HeaderRetrievalFn func(common.Hash) *types.Header
    72  
    73  // blockRetrievalFn is a callback type for retrieving a block from the local chain.
    74  type blockRetrievalFn func(common.Hash) *types.Block
    75  
    76  // headerRequesterFn is a callback type for sending a header retrieval request.
    77  type headerRequesterFn func(common.Hash) error
    78  
    79  // bodyRequesterFn is a callback type for sending a body retrieval request.
    80  type bodyRequesterFn func([]common.Hash) error
    81  
    82  // headerVerifierFn is a callback type to verify a block's header for fast propagation.
    83  type headerVerifierFn func(header *types.Header) error
    84  
    85  // blockBroadcasterFn is a callback type for broadcasting a block to connected peers.
    86  type blockBroadcasterFn func(block *types.Block, propagate bool)
    87  
    88  // chainHeightFn is a callback type to retrieve the current chain height.
    89  type chainHeightFn func() uint64
    90  
    91  // headersInsertFn is a callback type to insert a batch of headers into the local chain.
    92  type headersInsertFn func(headers []*types.Header) (int, error)
    93  
    94  // chainInsertFn is a callback type to insert a batch of blocks into the local chain.
    95  type chainInsertFn func(types.Blocks) (int, error)
    96  
    97  // peerDropFn is a callback type for dropping a peer detected as malicious.
    98  type peerDropFn func(id string)
    99  
   100  // blockAnnounce is the hash notification of the availability of a new block in the
   101  // network.
   102  type blockAnnounce struct {
   103  	hash   common.Hash   // Hash of the block being announced
   104  	number uint64        // Number of the block being announced (0 = unknown | old protocol)
   105  	header *types.Header // Header of the block partially reassembled (new protocol)
   106  	time   time.Time     // Timestamp of the announcement
   107  
   108  	origin string // Identifier of the peer originating the notification
   109  
   110  	fetchHeader headerRequesterFn // Fetcher function to retrieve the header of an announced block
   111  	fetchBodies bodyRequesterFn   // Fetcher function to retrieve the body of an announced block
   112  }
   113  
   114  // headerFilterTask represents a batch of headers needing fetcher filtering.
   115  type headerFilterTask struct {
   116  	peer    string          // The source peer of block headers
   117  	headers []*types.Header // Collection of headers to filter
   118  	time    time.Time       // Arrival time of the headers
   119  }
   120  
   121  // bodyFilterTask represents a batch of block bodies (transactions and uncles)
   122  // needing fetcher filtering.
   123  type bodyFilterTask struct {
   124  	peer         string                 // The source peer of block bodies
   125  	transactions [][]*types.Transaction // Collection of transactions per block bodies
   126  	uncles       [][]*types.Header      // Collection of uncles per block bodies
   127  	time         time.Time              // Arrival time of the blocks' contents
   128  }
   129  
   130  // blockOrHeaderInject represents a schedules import operation.
   131  type blockOrHeaderInject struct {
   132  	origin string
   133  
   134  	header *types.Header // Used for light mode fetcher which only cares about header.
   135  	block  *types.Block  // Used for normal mode fetcher which imports full block.
   136  }
   137  
   138  // number returns the block number of the injected object.
   139  func (inject *blockOrHeaderInject) number() uint64 {
   140  	if inject.header != nil {
   141  		return inject.header.Number.Uint64()
   142  	}
   143  	return inject.block.NumberU64()
   144  }
   145  
   146  // number returns the block hash of the injected object.
   147  func (inject *blockOrHeaderInject) hash() common.Hash {
   148  	if inject.header != nil {
   149  		return inject.header.Hash()
   150  	}
   151  	return inject.block.Hash()
   152  }
   153  
   154  // BlockFetcher is responsible for accumulating block announcements from various peers
   155  // and scheduling them for retrieval.
   156  type BlockFetcher struct {
   157  	light bool // The indicator whether it's a light fetcher or normal one.
   158  
   159  	// Various event channels
   160  	notify chan *blockAnnounce
   161  	inject chan *blockOrHeaderInject
   162  
   163  	headerFilter chan chan *headerFilterTask
   164  	bodyFilter   chan chan *bodyFilterTask
   165  
   166  	done chan common.Hash
   167  	quit chan struct{}
   168  
   169  	// Announce states
   170  	announces  map[string]int                   // Per peer blockAnnounce counts to prevent memory exhaustion
   171  	announced  map[common.Hash][]*blockAnnounce // Announced blocks, scheduled for fetching
   172  	fetching   map[common.Hash]*blockAnnounce   // Announced blocks, currently fetching
   173  	fetched    map[common.Hash][]*blockAnnounce // Blocks with headers fetched, scheduled for body retrieval
   174  	completing map[common.Hash]*blockAnnounce   // Blocks with headers, currently body-completing
   175  
   176  	// Block cache
   177  	queue  *prque.Prque                         // Queue containing the import operations (block number sorted)
   178  	queues map[string]int                       // Per peer block counts to prevent memory exhaustion
   179  	queued map[common.Hash]*blockOrHeaderInject // Set of already queued blocks (to dedup imports)
   180  
   181  	// Callbacks
   182  	getHeader      HeaderRetrievalFn  // Retrieves a header from the local chain
   183  	getBlock       blockRetrievalFn   // Retrieves a block from the local chain
   184  	verifyHeader   headerVerifierFn   // Checks if a block's headers have a valid proof of work
   185  	broadcastBlock blockBroadcasterFn // Broadcasts a block to connected peers
   186  	chainHeight    chainHeightFn      // Retrieves the current chain's height
   187  	insertHeaders  headersInsertFn    // Injects a batch of headers into the chain
   188  	insertChain    chainInsertFn      // Injects a batch of blocks into the chain
   189  	dropPeer       peerDropFn         // Drops a peer for misbehaving
   190  
   191  	// Testing hooks
   192  	announceChangeHook func(common.Hash, bool)           // Method to call upon adding or deleting a hash from the blockAnnounce list
   193  	queueChangeHook    func(common.Hash, bool)           // Method to call upon adding or deleting a block from the import queue
   194  	fetchingHook       func([]common.Hash)               // Method to call upon starting a block (eth/61) or header (eth/62) fetch
   195  	completingHook     func([]common.Hash)               // Method to call upon starting a block body fetch (eth/62)
   196  	importedHook       func(*types.Header, *types.Block) // Method to call upon successful header or block import (both eth/61 and eth/62)
   197  }
   198  
   199  // NewBlockFetcher creates a block fetcher to retrieve blocks based on hash announcements.
   200  func NewBlockFetcher(light bool, getHeader HeaderRetrievalFn, getBlock blockRetrievalFn, verifyHeader headerVerifierFn, broadcastBlock blockBroadcasterFn, chainHeight chainHeightFn, insertHeaders headersInsertFn, insertChain chainInsertFn, dropPeer peerDropFn) *BlockFetcher {
   201  	return &BlockFetcher{
   202  		light:          light,
   203  		notify:         make(chan *blockAnnounce),
   204  		inject:         make(chan *blockOrHeaderInject),
   205  		headerFilter:   make(chan chan *headerFilterTask),
   206  		bodyFilter:     make(chan chan *bodyFilterTask),
   207  		done:           make(chan common.Hash),
   208  		quit:           make(chan struct{}),
   209  		announces:      make(map[string]int),
   210  		announced:      make(map[common.Hash][]*blockAnnounce),
   211  		fetching:       make(map[common.Hash]*blockAnnounce),
   212  		fetched:        make(map[common.Hash][]*blockAnnounce),
   213  		completing:     make(map[common.Hash]*blockAnnounce),
   214  		queue:          prque.New(nil),
   215  		queues:         make(map[string]int),
   216  		queued:         make(map[common.Hash]*blockOrHeaderInject),
   217  		getHeader:      getHeader,
   218  		getBlock:       getBlock,
   219  		verifyHeader:   verifyHeader,
   220  		broadcastBlock: broadcastBlock,
   221  		chainHeight:    chainHeight,
   222  		insertHeaders:  insertHeaders,
   223  		insertChain:    insertChain,
   224  		dropPeer:       dropPeer,
   225  	}
   226  }
   227  
   228  // Start boots up the announcement based synchroniser, accepting and processing
   229  // hash notifications and block fetches until termination requested.
   230  func (f *BlockFetcher) Start() {
   231  	go f.loop()
   232  }
   233  
   234  // Stop terminates the announcement based synchroniser, canceling all pending
   235  // operations.
   236  func (f *BlockFetcher) Stop() {
   237  	close(f.quit)
   238  }
   239  
   240  // Notify announces the fetcher of the potential availability of a new block in
   241  // the network.
   242  func (f *BlockFetcher) Notify(peer string, hash common.Hash, number uint64, time time.Time,
   243  	headerFetcher headerRequesterFn, bodyFetcher bodyRequesterFn) error {
   244  	block := &blockAnnounce{
   245  		hash:        hash,
   246  		number:      number,
   247  		time:        time,
   248  		origin:      peer,
   249  		fetchHeader: headerFetcher,
   250  		fetchBodies: bodyFetcher,
   251  	}
   252  	select {
   253  	case f.notify <- block:
   254  		return nil
   255  	case <-f.quit:
   256  		return errTerminated
   257  	}
   258  }
   259  
   260  // Enqueue tries to fill gaps the fetcher's future import queue.
   261  func (f *BlockFetcher) Enqueue(peer string, block *types.Block) error {
   262  	op := &blockOrHeaderInject{
   263  		origin: peer,
   264  		block:  block,
   265  	}
   266  	select {
   267  	case f.inject <- op:
   268  		return nil
   269  	case <-f.quit:
   270  		return errTerminated
   271  	}
   272  }
   273  
   274  // FilterHeaders extracts all the headers that were explicitly requested by the fetcher,
   275  // returning those that should be handled differently.
   276  func (f *BlockFetcher) FilterHeaders(peer string, headers []*types.Header, time time.Time) []*types.Header {
   277  	log.Trace("Filtering headers", "peer", peer, "headers", len(headers))
   278  
   279  	// Send the filter channel to the fetcher
   280  	filter := make(chan *headerFilterTask)
   281  
   282  	select {
   283  	case f.headerFilter <- filter:
   284  	case <-f.quit:
   285  		return nil
   286  	}
   287  	// Request the filtering of the header list
   288  	select {
   289  	case filter <- &headerFilterTask{peer: peer, headers: headers, time: time}:
   290  	case <-f.quit:
   291  		return nil
   292  	}
   293  	// Retrieve the headers remaining after filtering
   294  	select {
   295  	case task := <-filter:
   296  		return task.headers
   297  	case <-f.quit:
   298  		return nil
   299  	}
   300  }
   301  
   302  // FilterBodies extracts all the block bodies that were explicitly requested by
   303  // the fetcher, returning those that should be handled differently.
   304  func (f *BlockFetcher) FilterBodies(peer string, transactions [][]*types.Transaction, uncles [][]*types.Header, time time.Time) ([][]*types.Transaction, [][]*types.Header) {
   305  	log.Trace("Filtering bodies", "peer", peer, "txs", len(transactions), "uncles", len(uncles))
   306  
   307  	// Send the filter channel to the fetcher
   308  	filter := make(chan *bodyFilterTask)
   309  
   310  	select {
   311  	case f.bodyFilter <- filter:
   312  	case <-f.quit:
   313  		return nil, nil
   314  	}
   315  	// Request the filtering of the body list
   316  	select {
   317  	case filter <- &bodyFilterTask{peer: peer, transactions: transactions, uncles: uncles, time: time}:
   318  	case <-f.quit:
   319  		return nil, nil
   320  	}
   321  	// Retrieve the bodies remaining after filtering
   322  	select {
   323  	case task := <-filter:
   324  		return task.transactions, task.uncles
   325  	case <-f.quit:
   326  		return nil, nil
   327  	}
   328  }
   329  
   330  // Loop is the main fetcher loop, checking and processing various notification
   331  // events.
   332  func (f *BlockFetcher) loop() {
   333  	// Iterate the block fetching until a quit is requested
   334  	fetchTimer := time.NewTimer(0)
   335  	completeTimer := time.NewTimer(0)
   336  	defer fetchTimer.Stop()
   337  	defer completeTimer.Stop()
   338  
   339  	for {
   340  		// Clean up any expired block fetches
   341  		for hash, announce := range f.fetching {
   342  			if time.Since(announce.time) > fetchTimeout {
   343  				f.forgetHash(hash)
   344  			}
   345  		}
   346  		// Import any queued blocks that could potentially fit
   347  		height := f.chainHeight()
   348  		for !f.queue.Empty() {
   349  			op := f.queue.PopItem().(*blockOrHeaderInject)
   350  			hash := op.hash()
   351  			if f.queueChangeHook != nil {
   352  				f.queueChangeHook(hash, false)
   353  			}
   354  			// If too high up the chain or phase, continue later
   355  			number := op.number()
   356  			if number > height+1 {
   357  				f.queue.Push(op, -int64(number))
   358  				if f.queueChangeHook != nil {
   359  					f.queueChangeHook(hash, true)
   360  				}
   361  				break
   362  			}
   363  			// Otherwise if fresh and still unknown, try and import
   364  			if (number+maxUncleDist < height) || (f.light && f.getHeader(hash) != nil) || (!f.light && f.getBlock(hash) != nil) {
   365  				f.forgetBlock(hash)
   366  				continue
   367  			}
   368  			if f.light {
   369  				f.importHeaders(op.origin, op.header)
   370  			} else {
   371  				f.importBlocks(op.origin, op.block)
   372  			}
   373  		}
   374  		// Wait for an outside event to occur
   375  		select {
   376  		case <-f.quit:
   377  			// BlockFetcher terminating, abort all operations
   378  			return
   379  
   380  		case notification := <-f.notify:
   381  			// A block was announced, make sure the peer isn't DOSing us
   382  			blockAnnounceInMeter.Mark(1)
   383  
   384  			count := f.announces[notification.origin] + 1
   385  			if count > hashLimit {
   386  				log.Debug("Peer exceeded outstanding announces", "peer", notification.origin, "limit", hashLimit)
   387  				blockAnnounceDOSMeter.Mark(1)
   388  				break
   389  			}
   390  			// If we have a valid block number, check that it's potentially useful
   391  			if notification.number > 0 {
   392  				if dist := int64(notification.number) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist {
   393  					log.Debug("Peer discarded announcement", "peer", notification.origin, "number", notification.number, "hash", notification.hash, "distance", dist)
   394  					blockAnnounceDropMeter.Mark(1)
   395  					break
   396  				}
   397  			}
   398  			// All is well, schedule the announce if block's not yet downloading
   399  			if _, ok := f.fetching[notification.hash]; ok {
   400  				break
   401  			}
   402  			if _, ok := f.completing[notification.hash]; ok {
   403  				break
   404  			}
   405  			f.announces[notification.origin] = count
   406  			f.announced[notification.hash] = append(f.announced[notification.hash], notification)
   407  			if f.announceChangeHook != nil && len(f.announced[notification.hash]) == 1 {
   408  				f.announceChangeHook(notification.hash, true)
   409  			}
   410  			if len(f.announced) == 1 {
   411  				f.rescheduleFetch(fetchTimer)
   412  			}
   413  
   414  		case op := <-f.inject:
   415  			// A direct block insertion was requested, try and fill any pending gaps
   416  			blockBroadcastInMeter.Mark(1)
   417  
   418  			// Now only direct block injection is allowed, drop the header injection
   419  			// here silently if we receive.
   420  			if f.light {
   421  				continue
   422  			}
   423  			f.enqueue(op.origin, nil, op.block)
   424  
   425  		case hash := <-f.done:
   426  			// A pending import finished, remove all traces of the notification
   427  			f.forgetHash(hash)
   428  			f.forgetBlock(hash)
   429  
   430  		case <-fetchTimer.C:
   431  			// At least one block's timer ran out, check for needing retrieval
   432  			request := make(map[string][]common.Hash)
   433  
   434  			for hash, announces := range f.announced {
   435  				// In current LES protocol(les2/les3), only header announce is
   436  				// available, no need to wait too much time for header broadcast.
   437  				timeout := arriveTimeout - gatherSlack
   438  				if f.light {
   439  					timeout = 0
   440  				}
   441  				if time.Since(announces[0].time) > timeout {
   442  					// Pick a random peer to retrieve from, reset all others
   443  					announce := announces[rand.Intn(len(announces))]
   444  					f.forgetHash(hash)
   445  
   446  					// If the block still didn't arrive, queue for fetching
   447  					if (f.light && f.getHeader(hash) == nil) || (!f.light && f.getBlock(hash) == nil) {
   448  						request[announce.origin] = append(request[announce.origin], hash)
   449  						f.fetching[hash] = announce
   450  					}
   451  				}
   452  			}
   453  			// Send out all block header requests
   454  			for peer, hashes := range request {
   455  				log.Trace("Fetching scheduled headers", "peer", peer, "list", hashes)
   456  
   457  				// Create a closure of the fetch and schedule in on a new thread
   458  				fetchHeader, hashes := f.fetching[hashes[0]].fetchHeader, hashes
   459  				go func() {
   460  					if f.fetchingHook != nil {
   461  						f.fetchingHook(hashes)
   462  					}
   463  					for _, hash := range hashes {
   464  						headerFetchMeter.Mark(1)
   465  						fetchHeader(hash) // Suboptimal, but protocol doesn't allow batch header retrievals
   466  					}
   467  				}()
   468  			}
   469  			// Schedule the next fetch if blocks are still pending
   470  			f.rescheduleFetch(fetchTimer)
   471  
   472  		case <-completeTimer.C:
   473  			// At least one header's timer ran out, retrieve everything
   474  			request := make(map[string][]common.Hash)
   475  
   476  			for hash, announces := range f.fetched {
   477  				// Pick a random peer to retrieve from, reset all others
   478  				announce := announces[rand.Intn(len(announces))]
   479  				f.forgetHash(hash)
   480  
   481  				// If the block still didn't arrive, queue for completion
   482  				if f.getBlock(hash) == nil {
   483  					request[announce.origin] = append(request[announce.origin], hash)
   484  					f.completing[hash] = announce
   485  				}
   486  			}
   487  			// Send out all block body requests
   488  			for peer, hashes := range request {
   489  				log.Trace("Fetching scheduled bodies", "peer", peer, "list", hashes)
   490  
   491  				// Create a closure of the fetch and schedule in on a new thread
   492  				if f.completingHook != nil {
   493  					f.completingHook(hashes)
   494  				}
   495  				bodyFetchMeter.Mark(int64(len(hashes)))
   496  				go f.completing[hashes[0]].fetchBodies(hashes)
   497  			}
   498  			// Schedule the next fetch if blocks are still pending
   499  			f.rescheduleComplete(completeTimer)
   500  
   501  		case filter := <-f.headerFilter:
   502  			// Headers arrived from a remote peer. Extract those that were explicitly
   503  			// requested by the fetcher, and return everything else so it's delivered
   504  			// to other parts of the system.
   505  			var task *headerFilterTask
   506  			select {
   507  			case task = <-filter:
   508  			case <-f.quit:
   509  				return
   510  			}
   511  			headerFilterInMeter.Mark(int64(len(task.headers)))
   512  
   513  			// Split the batch of headers into unknown ones (to return to the caller),
   514  			// known incomplete ones (requiring body retrievals) and completed blocks.
   515  			unknown, incomplete, complete, lightHeaders := []*types.Header{}, []*blockAnnounce{}, []*types.Block{}, []*blockAnnounce{}
   516  			for _, header := range task.headers {
   517  				hash := header.Hash()
   518  
   519  				// Filter fetcher-requested headers from other synchronisation algorithms
   520  				if announce := f.fetching[hash]; announce != nil && announce.origin == task.peer && f.fetched[hash] == nil && f.completing[hash] == nil && f.queued[hash] == nil {
   521  					// If the delivered header does not match the promised number, drop the announcer
   522  					if header.Number.Uint64() != announce.number {
   523  						log.Trace("Invalid block number fetched", "peer", announce.origin, "hash", header.Hash(), "announced", announce.number, "provided", header.Number)
   524  						f.dropPeer(announce.origin)
   525  						f.forgetHash(hash)
   526  						continue
   527  					}
   528  					// Collect all headers only if we are running in light
   529  					// mode and the headers are not imported by other means.
   530  					if f.light {
   531  						if f.getHeader(hash) == nil {
   532  							announce.header = header
   533  							lightHeaders = append(lightHeaders, announce)
   534  						}
   535  						f.forgetHash(hash)
   536  						continue
   537  					}
   538  					// Only keep if not imported by other means
   539  					if f.getBlock(hash) == nil {
   540  						announce.header = header
   541  						announce.time = task.time
   542  
   543  						// If the block is empty (header only), short circuit into the final import queue
   544  						if header.TxHash == types.EmptyRootHash && header.UncleHash == types.EmptyUncleHash {
   545  							log.Trace("Block empty, skipping body retrieval", "peer", announce.origin, "number", header.Number, "hash", header.Hash())
   546  
   547  							block := types.NewBlockWithHeader(header)
   548  							block.ReceivedAt = task.time
   549  
   550  							complete = append(complete, block)
   551  							f.completing[hash] = announce
   552  							continue
   553  						}
   554  						// Otherwise add to the list of blocks needing completion
   555  						incomplete = append(incomplete, announce)
   556  					} else {
   557  						log.Trace("Block already imported, discarding header", "peer", announce.origin, "number", header.Number, "hash", header.Hash())
   558  						f.forgetHash(hash)
   559  					}
   560  				} else {
   561  					// BlockFetcher doesn't know about it, add to the return list
   562  					unknown = append(unknown, header)
   563  				}
   564  			}
   565  			headerFilterOutMeter.Mark(int64(len(unknown)))
   566  			select {
   567  			case filter <- &headerFilterTask{headers: unknown, time: task.time}:
   568  			case <-f.quit:
   569  				return
   570  			}
   571  			// Schedule the retrieved headers for body completion
   572  			for _, announce := range incomplete {
   573  				hash := announce.header.Hash()
   574  				if _, ok := f.completing[hash]; ok {
   575  					continue
   576  				}
   577  				f.fetched[hash] = append(f.fetched[hash], announce)
   578  				if len(f.fetched) == 1 {
   579  					f.rescheduleComplete(completeTimer)
   580  				}
   581  			}
   582  			// Schedule the header for light fetcher import
   583  			for _, announce := range lightHeaders {
   584  				f.enqueue(announce.origin, announce.header, nil)
   585  			}
   586  			// Schedule the header-only blocks for import
   587  			for _, block := range complete {
   588  				if announce := f.completing[block.Hash()]; announce != nil {
   589  					f.enqueue(announce.origin, nil, block)
   590  				}
   591  			}
   592  
   593  		case filter := <-f.bodyFilter:
   594  			// Block bodies arrived, extract any explicitly requested blocks, return the rest
   595  			var task *bodyFilterTask
   596  			select {
   597  			case task = <-filter:
   598  			case <-f.quit:
   599  				return
   600  			}
   601  			bodyFilterInMeter.Mark(int64(len(task.transactions)))
   602  			blocks := []*types.Block{}
   603  			// abort early if there's nothing explicitly requested
   604  			if len(f.completing) > 0 {
   605  				for i := 0; i < len(task.transactions) && i < len(task.uncles); i++ {
   606  					// Match up a body to any possible completion request
   607  					var (
   608  						matched   = false
   609  						uncleHash common.Hash // calculated lazily and reused
   610  						txnHash   common.Hash // calculated lazily and reused
   611  					)
   612  					for hash, announce := range f.completing {
   613  						if f.queued[hash] != nil || announce.origin != task.peer {
   614  							continue
   615  						}
   616  						if uncleHash == (common.Hash{}) {
   617  							uncleHash = types.CalcUncleHash(task.uncles[i])
   618  						}
   619  						if uncleHash != announce.header.UncleHash {
   620  							continue
   621  						}
   622  						if txnHash == (common.Hash{}) {
   623  							txnHash = types.DeriveSha(types.Transactions(task.transactions[i]), new(trie.Trie))
   624  						}
   625  						if txnHash != announce.header.TxHash {
   626  							continue
   627  						}
   628  						// Mark the body matched, reassemble if still unknown
   629  						matched = true
   630  						if f.getBlock(hash) == nil {
   631  							block := types.NewBlockWithHeader(announce.header).WithBody(task.transactions[i], task.uncles[i])
   632  							block.ReceivedAt = task.time
   633  							blocks = append(blocks, block)
   634  						} else {
   635  							f.forgetHash(hash)
   636  						}
   637  
   638  					}
   639  					if matched {
   640  						task.transactions = append(task.transactions[:i], task.transactions[i+1:]...)
   641  						task.uncles = append(task.uncles[:i], task.uncles[i+1:]...)
   642  						i--
   643  						continue
   644  					}
   645  				}
   646  			}
   647  			bodyFilterOutMeter.Mark(int64(len(task.transactions)))
   648  			select {
   649  			case filter <- task:
   650  			case <-f.quit:
   651  				return
   652  			}
   653  			// Schedule the retrieved blocks for ordered import
   654  			for _, block := range blocks {
   655  				if announce := f.completing[block.Hash()]; announce != nil {
   656  					f.enqueue(announce.origin, nil, block)
   657  				}
   658  			}
   659  		}
   660  	}
   661  }
   662  
   663  // rescheduleFetch resets the specified fetch timer to the next blockAnnounce timeout.
   664  func (f *BlockFetcher) rescheduleFetch(fetch *time.Timer) {
   665  	// Short circuit if no blocks are announced
   666  	if len(f.announced) == 0 {
   667  		return
   668  	}
   669  	// Schedule announcement retrieval quickly for light mode
   670  	// since server won't send any headers to client.
   671  	if f.light {
   672  		fetch.Reset(lightTimeout)
   673  		return
   674  	}
   675  	// Otherwise find the earliest expiring announcement
   676  	earliest := time.Now()
   677  	for _, announces := range f.announced {
   678  		if earliest.After(announces[0].time) {
   679  			earliest = announces[0].time
   680  		}
   681  	}
   682  	fetch.Reset(arriveTimeout - time.Since(earliest))
   683  }
   684  
   685  // rescheduleComplete resets the specified completion timer to the next fetch timeout.
   686  func (f *BlockFetcher) rescheduleComplete(complete *time.Timer) {
   687  	// Short circuit if no headers are fetched
   688  	if len(f.fetched) == 0 {
   689  		return
   690  	}
   691  	// Otherwise find the earliest expiring announcement
   692  	earliest := time.Now()
   693  	for _, announces := range f.fetched {
   694  		if earliest.After(announces[0].time) {
   695  			earliest = announces[0].time
   696  		}
   697  	}
   698  	complete.Reset(gatherSlack - time.Since(earliest))
   699  }
   700  
   701  // enqueue schedules a new header or block import operation, if the component
   702  // to be imported has not yet been seen.
   703  func (f *BlockFetcher) enqueue(peer string, header *types.Header, block *types.Block) {
   704  	var (
   705  		hash   common.Hash
   706  		number uint64
   707  	)
   708  	if header != nil {
   709  		hash, number = header.Hash(), header.Number.Uint64()
   710  	} else {
   711  		hash, number = block.Hash(), block.NumberU64()
   712  	}
   713  	// Ensure the peer isn't DOSing us
   714  	count := f.queues[peer] + 1
   715  	if count > blockLimit {
   716  		log.Debug("Discarded delivered header or block, exceeded allowance", "peer", peer, "number", number, "hash", hash, "limit", blockLimit)
   717  		blockBroadcastDOSMeter.Mark(1)
   718  		f.forgetHash(hash)
   719  		return
   720  	}
   721  	// Discard any past or too distant blocks
   722  	if dist := int64(number) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist {
   723  		log.Debug("Discarded delivered header or block, too far away", "peer", peer, "number", number, "hash", hash, "distance", dist)
   724  		blockBroadcastDropMeter.Mark(1)
   725  		f.forgetHash(hash)
   726  		return
   727  	}
   728  	// Schedule the block for future importing
   729  	if _, ok := f.queued[hash]; !ok {
   730  		op := &blockOrHeaderInject{origin: peer}
   731  		if header != nil {
   732  			op.header = header
   733  		} else {
   734  			op.block = block
   735  		}
   736  		f.queues[peer] = count
   737  		f.queued[hash] = op
   738  		f.queue.Push(op, -int64(number))
   739  		if f.queueChangeHook != nil {
   740  			f.queueChangeHook(hash, true)
   741  		}
   742  		log.Debug("Queued delivered header or block", "peer", peer, "number", number, "hash", hash, "queued", f.queue.Size())
   743  	}
   744  }
   745  
   746  // importHeaders spawns a new goroutine to run a header insertion into the chain.
   747  // If the header's number is at the same height as the current import phase, it
   748  // updates the phase states accordingly.
   749  func (f *BlockFetcher) importHeaders(peer string, header *types.Header) {
   750  	hash := header.Hash()
   751  	log.Debug("Importing propagated header", "peer", peer, "number", header.Number, "hash", hash)
   752  
   753  	go func() {
   754  		defer func() { f.done <- hash }()
   755  		// If the parent's unknown, abort insertion
   756  		parent := f.getHeader(header.ParentHash)
   757  		if parent == nil {
   758  			log.Debug("Unknown parent of propagated header", "peer", peer, "number", header.Number, "hash", hash, "parent", header.ParentHash)
   759  			return
   760  		}
   761  		// Validate the header and if something went wrong, drop the peer
   762  		if err := f.verifyHeader(header); err != nil && err != consensus.ErrFutureBlock {
   763  			log.Debug("Propagated header verification failed", "peer", peer, "number", header.Number, "hash", hash, "err", err)
   764  			f.dropPeer(peer)
   765  			return
   766  		}
   767  		// Run the actual import and log any issues
   768  		if _, err := f.insertHeaders([]*types.Header{header}); err != nil {
   769  			log.Debug("Propagated header import failed", "peer", peer, "number", header.Number, "hash", hash, "err", err)
   770  			return
   771  		}
   772  		// Invoke the testing hook if needed
   773  		if f.importedHook != nil {
   774  			f.importedHook(header, nil)
   775  		}
   776  	}()
   777  }
   778  
   779  // importBlocks spawns a new goroutine to run a block insertion into the chain. If the
   780  // block's number is at the same height as the current import phase, it updates
   781  // the phase states accordingly.
   782  func (f *BlockFetcher) importBlocks(peer string, block *types.Block) {
   783  	hash := block.Hash()
   784  
   785  	// Run the import on a new thread
   786  	log.Debug("Importing propagated block", "peer", peer, "number", block.Number(), "hash", hash)
   787  	go func() {
   788  		defer func() { f.done <- hash }()
   789  
   790  		// If the parent's unknown, abort insertion
   791  		parent := f.getBlock(block.ParentHash())
   792  		if parent == nil {
   793  			log.Debug("Unknown parent of propagated block", "peer", peer, "number", block.Number(), "hash", hash, "parent", block.ParentHash())
   794  			return
   795  		}
   796  		// Quickly validate the header and propagate the block if it passes
   797  		switch err := f.verifyHeader(block.Header()); err {
   798  		case nil:
   799  			// All ok, quickly propagate to our peers
   800  			blockBroadcastOutTimer.UpdateSince(block.ReceivedAt)
   801  			go f.broadcastBlock(block, true)
   802  
   803  		case consensus.ErrFutureBlock:
   804  			// Weird future block, don't fail, but neither propagate
   805  
   806  		default:
   807  			// Something went very wrong, drop the peer
   808  			log.Debug("Propagated block verification failed", "peer", peer, "number", block.Number(), "hash", hash, "err", err)
   809  			f.dropPeer(peer)
   810  			return
   811  		}
   812  		// Run the actual import and log any issues
   813  		if _, err := f.insertChain(types.Blocks{block}); err != nil {
   814  			log.Debug("Propagated block import failed", "peer", peer, "number", block.Number(), "hash", hash, "err", err)
   815  			return
   816  		}
   817  		// If import succeeded, broadcast the block
   818  		blockAnnounceOutTimer.UpdateSince(block.ReceivedAt)
   819  		go f.broadcastBlock(block, false)
   820  
   821  		// Invoke the testing hook if needed
   822  		if f.importedHook != nil {
   823  			f.importedHook(nil, block)
   824  		}
   825  	}()
   826  }
   827  
   828  // forgetHash removes all traces of a block announcement from the fetcher's
   829  // internal state.
   830  func (f *BlockFetcher) forgetHash(hash common.Hash) {
   831  	// Remove all pending announces and decrement DOS counters
   832  	for _, announce := range f.announced[hash] {
   833  		f.announces[announce.origin]--
   834  		if f.announces[announce.origin] <= 0 {
   835  			delete(f.announces, announce.origin)
   836  		}
   837  	}
   838  	delete(f.announced, hash)
   839  	if f.announceChangeHook != nil {
   840  		f.announceChangeHook(hash, false)
   841  	}
   842  	// Remove any pending fetches and decrement the DOS counters
   843  	if announce := f.fetching[hash]; announce != nil {
   844  		f.announces[announce.origin]--
   845  		if f.announces[announce.origin] <= 0 {
   846  			delete(f.announces, announce.origin)
   847  		}
   848  		delete(f.fetching, hash)
   849  	}
   850  
   851  	// Remove any pending completion requests and decrement the DOS counters
   852  	for _, announce := range f.fetched[hash] {
   853  		f.announces[announce.origin]--
   854  		if f.announces[announce.origin] <= 0 {
   855  			delete(f.announces, announce.origin)
   856  		}
   857  	}
   858  	delete(f.fetched, hash)
   859  
   860  	// Remove any pending completions and decrement the DOS counters
   861  	if announce := f.completing[hash]; announce != nil {
   862  		f.announces[announce.origin]--
   863  		if f.announces[announce.origin] <= 0 {
   864  			delete(f.announces, announce.origin)
   865  		}
   866  		delete(f.completing, hash)
   867  	}
   868  }
   869  
   870  // forgetBlock removes all traces of a queued block from the fetcher's internal
   871  // state.
   872  func (f *BlockFetcher) forgetBlock(hash common.Hash) {
   873  	if insert := f.queued[hash]; insert != nil {
   874  		f.queues[insert.origin]--
   875  		if f.queues[insert.origin] == 0 {
   876  			delete(f.queues, insert.origin)
   877  		}
   878  		delete(f.queued, hash)
   879  	}
   880  }