github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/eth/handler.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 eth
    18  
    19  import (
    20  	"errors"
    21  	"math"
    22  	"math/big"
    23  	"sync"
    24  	"sync/atomic"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/consensus"
    29  	"github.com/ethereum/go-ethereum/consensus/beacon"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/core/forkid"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/eth/downloader"
    34  	"github.com/ethereum/go-ethereum/eth/fetcher"
    35  	"github.com/ethereum/go-ethereum/eth/protocols/eth"
    36  	"github.com/ethereum/go-ethereum/eth/protocols/snap"
    37  	"github.com/ethereum/go-ethereum/ethdb"
    38  	"github.com/ethereum/go-ethereum/event"
    39  	"github.com/ethereum/go-ethereum/log"
    40  	"github.com/ethereum/go-ethereum/p2p"
    41  	"github.com/ethereum/go-ethereum/params"
    42  )
    43  
    44  const (
    45  	// txChanSize is the size of channel listening to NewTxsEvent.
    46  	// The number is referenced from the size of tx pool.
    47  	txChanSize = 4096
    48  )
    49  
    50  var (
    51  	syncChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the sync progress challenge
    52  )
    53  
    54  // txPool defines the methods needed from a transaction pool implementation to
    55  // support all the operations needed by the Ethereum chain protocols.
    56  type txPool interface {
    57  	// Has returns an indicator whether txpool has a transaction
    58  	// cached with the given hash.
    59  	Has(hash common.Hash) bool
    60  
    61  	// Get retrieves the transaction from local txpool with given
    62  	// tx hash.
    63  	Get(hash common.Hash) *types.Transaction
    64  
    65  	// AddRemotes should add the given transactions to the pool.
    66  	AddRemotes([]*types.Transaction) []error
    67  
    68  	// Pending should return pending transactions.
    69  	// The slice should be modifiable by the caller.
    70  	Pending(enforceTips bool) map[common.Address]types.Transactions
    71  
    72  	// SubscribeNewTxsEvent should return an event subscription of
    73  	// NewTxsEvent and send events to the given channel.
    74  	SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
    75  }
    76  
    77  // handlerConfig is the collection of initialization parameters to create a full
    78  // node network handler.
    79  type handlerConfig struct {
    80  	Database   ethdb.Database            // Database for direct sync insertions
    81  	Chain      *core.BlockChain          // Blockchain to serve data from
    82  	TxPool     txPool                    // Transaction pool to propagate from
    83  	Merger     *consensus.Merger         // The manager for eth1/2 transition
    84  	Network    uint64                    // Network identifier to adfvertise
    85  	Sync       downloader.SyncMode       // Whether to snap or full sync
    86  	BloomCache uint64                    // Megabytes to alloc for snap sync bloom
    87  	EventMux   *event.TypeMux            // Legacy event mux, deprecate for `feed`
    88  	Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges
    89  
    90  	PeerRequiredBlocks map[uint64]common.Hash // Hard coded map of required block hashes for sync challenges
    91  }
    92  
    93  type handler struct {
    94  	networkID  uint64
    95  	forkFilter forkid.Filter // Fork ID filter, constant across the lifetime of the node
    96  
    97  	snapSync  uint32 // Flag whether snap sync is enabled (gets disabled if we already have blocks)
    98  	acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
    99  
   100  	checkpointNumber uint64      // Block number for the sync progress validator to cross reference
   101  	checkpointHash   common.Hash // Block hash for the sync progress validator to cross reference
   102  
   103  	database ethdb.Database
   104  	txpool   txPool
   105  	chain    *core.BlockChain
   106  	maxPeers int
   107  
   108  	downloader   *downloader.Downloader
   109  	blockFetcher *fetcher.BlockFetcher
   110  	txFetcher    *fetcher.TxFetcher
   111  	peers        *peerSet
   112  	merger       *consensus.Merger
   113  
   114  	eventMux      *event.TypeMux
   115  	txsCh         chan core.NewTxsEvent
   116  	txsSub        event.Subscription
   117  	minedBlockSub *event.TypeMuxSubscription
   118  
   119  	peerRequiredBlocks map[uint64]common.Hash
   120  
   121  	// channels for fetcher, syncer, txsyncLoop
   122  	quitSync chan struct{}
   123  
   124  	chainSync *chainSyncer
   125  	wg        sync.WaitGroup
   126  	peerWG    sync.WaitGroup
   127  }
   128  
   129  // newHandler returns a handler for all Ethereum chain management protocol.
   130  func newHandler(config *handlerConfig) (*handler, error) {
   131  	// Create the protocol manager with the base fields
   132  	if config.EventMux == nil {
   133  		config.EventMux = new(event.TypeMux) // Nicety initialization for tests
   134  	}
   135  	h := &handler{
   136  		networkID:          config.Network,
   137  		forkFilter:         forkid.NewFilter(config.Chain),
   138  		eventMux:           config.EventMux,
   139  		database:           config.Database,
   140  		txpool:             config.TxPool,
   141  		chain:              config.Chain,
   142  		peers:              newPeerSet(),
   143  		merger:             config.Merger,
   144  		peerRequiredBlocks: config.PeerRequiredBlocks,
   145  		quitSync:           make(chan struct{}),
   146  	}
   147  	if config.Sync == downloader.FullSync {
   148  		// The database seems empty as the current block is the genesis. Yet the snap
   149  		// block is ahead, so snap sync was enabled for this node at a certain point.
   150  		// The scenarios where this can happen is
   151  		// * if the user manually (or via a bad block) rolled back a snap sync node
   152  		//   below the sync point.
   153  		// * the last snap sync is not finished while user specifies a full sync this
   154  		//   time. But we don't have any recent state for full sync.
   155  		// In these cases however it's safe to reenable snap sync.
   156  		fullBlock, fastBlock := h.chain.CurrentBlock(), h.chain.CurrentFastBlock()
   157  		if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 {
   158  			h.snapSync = uint32(1)
   159  			log.Warn("Switch sync mode from full sync to snap sync")
   160  		}
   161  	} else {
   162  		if h.chain.CurrentBlock().NumberU64() > 0 {
   163  			// Print warning log if database is not empty to run snap sync.
   164  			log.Warn("Switch sync mode from snap sync to full sync")
   165  		} else {
   166  			// If snap sync was requested and our database is empty, grant it
   167  			h.snapSync = uint32(1)
   168  		}
   169  	}
   170  	// If we have trusted checkpoints, enforce them on the chain
   171  	if config.Checkpoint != nil {
   172  		h.checkpointNumber = (config.Checkpoint.SectionIndex+1)*params.CHTFrequency - 1
   173  		h.checkpointHash = config.Checkpoint.SectionHead
   174  	}
   175  	// If sync succeeds, pass a callback to potentially disable snap sync mode
   176  	// and enable transaction propagation.
   177  	success := func() {
   178  		// If we were running snap sync and it finished, disable doing another
   179  		// round on next sync cycle
   180  		if atomic.LoadUint32(&h.snapSync) == 1 {
   181  			log.Info("Snap sync complete, auto disabling")
   182  			atomic.StoreUint32(&h.snapSync, 0)
   183  		}
   184  		// If we've successfully finished a sync cycle and passed any required
   185  		// checkpoint, enable accepting transactions from the network
   186  		head := h.chain.CurrentBlock()
   187  		if head.NumberU64() >= h.checkpointNumber {
   188  			// Checkpoint passed, sanity check the timestamp to have a fallback mechanism
   189  			// for non-checkpointed (number = 0) private networks.
   190  			if head.Time() >= uint64(time.Now().AddDate(0, -1, 0).Unix()) {
   191  				atomic.StoreUint32(&h.acceptTxs, 1)
   192  			}
   193  		}
   194  	}
   195  	// Construct the downloader (long sync) and its backing state bloom if snap
   196  	// sync is requested. The downloader is responsible for deallocating the state
   197  	// bloom when it's done.
   198  	h.downloader = downloader.New(h.checkpointNumber, config.Database, h.eventMux, h.chain, nil, h.removePeer, success)
   199  
   200  	// Construct the fetcher (short sync)
   201  	validator := func(header *types.Header) error {
   202  		// All the block fetcher activities should be disabled
   203  		// after the transition. Print the warning log.
   204  		if h.merger.PoSFinalized() {
   205  			log.Warn("Unexpected validation activity", "hash", header.Hash(), "number", header.Number)
   206  			return errors.New("unexpected behavior after transition")
   207  		}
   208  		// Reject all the PoS style headers in the first place. No matter
   209  		// the chain has finished the transition or not, the PoS headers
   210  		// should only come from the trusted consensus layer instead of
   211  		// p2p network.
   212  		if beacon, ok := h.chain.Engine().(*beacon.Beacon); ok {
   213  			if beacon.IsPoSHeader(header) {
   214  				return errors.New("unexpected post-merge header")
   215  			}
   216  		}
   217  		return h.chain.Engine().VerifyHeader(h.chain, header, true)
   218  	}
   219  	heighter := func() uint64 {
   220  		return h.chain.CurrentBlock().NumberU64()
   221  	}
   222  	inserter := func(blocks types.Blocks) (int, error) {
   223  		// All the block fetcher activities should be disabled
   224  		// after the transition. Print the warning log.
   225  		if h.merger.PoSFinalized() {
   226  			var ctx []interface{}
   227  			ctx = append(ctx, "blocks", len(blocks))
   228  			if len(blocks) > 0 {
   229  				ctx = append(ctx, "firsthash", blocks[0].Hash())
   230  				ctx = append(ctx, "firstnumber", blocks[0].Number())
   231  				ctx = append(ctx, "lasthash", blocks[len(blocks)-1].Hash())
   232  				ctx = append(ctx, "lastnumber", blocks[len(blocks)-1].Number())
   233  			}
   234  			log.Warn("Unexpected insertion activity", ctx...)
   235  			return 0, errors.New("unexpected behavior after transition")
   236  		}
   237  		// If sync hasn't reached the checkpoint yet, deny importing weird blocks.
   238  		//
   239  		// Ideally we would also compare the head block's timestamp and similarly reject
   240  		// the propagated block if the head is too old. Unfortunately there is a corner
   241  		// case when starting new networks, where the genesis might be ancient (0 unix)
   242  		// which would prevent full nodes from accepting it.
   243  		if h.chain.CurrentBlock().NumberU64() < h.checkpointNumber {
   244  			log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   245  			return 0, nil
   246  		}
   247  		// If snap sync is running, deny importing weird blocks. This is a problematic
   248  		// clause when starting up a new network, because snap-syncing miners might not
   249  		// accept each others' blocks until a restart. Unfortunately we haven't figured
   250  		// out a way yet where nodes can decide unilaterally whether the network is new
   251  		// or not. This should be fixed if we figure out a solution.
   252  		if atomic.LoadUint32(&h.snapSync) == 1 {
   253  			log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   254  			return 0, nil
   255  		}
   256  		if h.merger.TDDReached() {
   257  			// The blocks from the p2p network is regarded as untrusted
   258  			// after the transition. In theory block gossip should be disabled
   259  			// entirely whenever the transition is started. But in order to
   260  			// handle the transition boundary reorg in the consensus-layer,
   261  			// the legacy blocks are still accepted, but only for the terminal
   262  			// pow blocks. Spec: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3675.md#halt-the-importing-of-pow-blocks
   263  			for i, block := range blocks {
   264  				ptd := h.chain.GetTd(block.ParentHash(), block.NumberU64()-1)
   265  				if ptd == nil {
   266  					return 0, nil
   267  				}
   268  				td := new(big.Int).Add(ptd, block.Difficulty())
   269  				if !h.chain.Config().IsTerminalPoWBlock(ptd, td) {
   270  					log.Info("Filtered out non-termimal pow block", "number", block.NumberU64(), "hash", block.Hash())
   271  					return 0, nil
   272  				}
   273  				if err := h.chain.InsertBlockWithoutSetHead(block); err != nil {
   274  					return i, err
   275  				}
   276  			}
   277  			return 0, nil
   278  		}
   279  		n, err := h.chain.InsertChain(blocks)
   280  		if err == nil {
   281  			atomic.StoreUint32(&h.acceptTxs, 1) // Mark initial sync done on any fetcher import
   282  		}
   283  		return n, err
   284  	}
   285  	h.blockFetcher = fetcher.NewBlockFetcher(false, nil, h.chain.GetBlockByHash, validator, h.BroadcastBlock, heighter, nil, inserter, h.removePeer)
   286  
   287  	fetchTx := func(peer string, hashes []common.Hash) error {
   288  		p := h.peers.peer(peer)
   289  		if p == nil {
   290  			return errors.New("unknown peer")
   291  		}
   292  		return p.RequestTxs(hashes)
   293  	}
   294  	h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, h.txpool.AddRemotes, fetchTx)
   295  	h.chainSync = newChainSyncer(h)
   296  	return h, nil
   297  }
   298  
   299  // runEthPeer registers an eth peer into the joint eth/snap peerset, adds it to
   300  // various subsistems and starts handling messages.
   301  func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error {
   302  	// If the peer has a `snap` extension, wait for it to connect so we can have
   303  	// a uniform initialization/teardown mechanism
   304  	snap, err := h.peers.waitSnapExtension(peer)
   305  	if err != nil {
   306  		peer.Log().Error("Snapshot extension barrier failed", "err", err)
   307  		return err
   308  	}
   309  	// TODO(karalabe): Not sure why this is needed
   310  	if !h.chainSync.handlePeerEvent(peer) {
   311  		return p2p.DiscQuitting
   312  	}
   313  	h.peerWG.Add(1)
   314  	defer h.peerWG.Done()
   315  
   316  	// Execute the Ethereum handshake
   317  	var (
   318  		genesis = h.chain.Genesis()
   319  		head    = h.chain.CurrentHeader()
   320  		hash    = head.Hash()
   321  		number  = head.Number.Uint64()
   322  		td      = h.chain.GetTd(hash, number)
   323  	)
   324  	forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64())
   325  	if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil {
   326  		peer.Log().Debug("Ethereum handshake failed", "err", err)
   327  		return err
   328  	}
   329  	reject := false // reserved peer slots
   330  	if atomic.LoadUint32(&h.snapSync) == 1 {
   331  		if snap == nil {
   332  			// If we are running snap-sync, we want to reserve roughly half the peer
   333  			// slots for peers supporting the snap protocol.
   334  			// The logic here is; we only allow up to 5 more non-snap peers than snap-peers.
   335  			if all, snp := h.peers.len(), h.peers.snapLen(); all-snp > snp+5 {
   336  				reject = true
   337  			}
   338  		}
   339  	}
   340  	// Ignore maxPeers if this is a trusted peer
   341  	if !peer.Peer.Info().Network.Trusted {
   342  		if reject || h.peers.len() >= h.maxPeers {
   343  			return p2p.DiscTooManyPeers
   344  		}
   345  	}
   346  	peer.Log().Debug("Ethereum peer connected", "name", peer.Name())
   347  
   348  	// Register the peer locally
   349  	if err := h.peers.registerPeer(peer, snap); err != nil {
   350  		peer.Log().Error("Ethereum peer registration failed", "err", err)
   351  		return err
   352  	}
   353  	defer h.unregisterPeer(peer.ID())
   354  
   355  	p := h.peers.peer(peer.ID())
   356  	if p == nil {
   357  		return errors.New("peer dropped during handling")
   358  	}
   359  	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
   360  	if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil {
   361  		peer.Log().Error("Failed to register peer in eth syncer", "err", err)
   362  		return err
   363  	}
   364  	if snap != nil {
   365  		if err := h.downloader.SnapSyncer.Register(snap); err != nil {
   366  			peer.Log().Error("Failed to register peer in snap syncer", "err", err)
   367  			return err
   368  		}
   369  	}
   370  	h.chainSync.handlePeerEvent(peer)
   371  
   372  	// Propagate existing transactions. new transactions appearing
   373  	// after this will be sent via broadcasts.
   374  	h.syncTransactions(peer)
   375  
   376  	// Create a notification channel for pending requests if the peer goes down
   377  	dead := make(chan struct{})
   378  	defer close(dead)
   379  
   380  	// If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
   381  	if h.checkpointHash != (common.Hash{}) {
   382  		// Request the peer's checkpoint header for chain height/weight validation
   383  		resCh := make(chan *eth.Response)
   384  		if _, err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false, resCh); err != nil {
   385  			return err
   386  		}
   387  		// Start a timer to disconnect if the peer doesn't reply in time
   388  		go func() {
   389  			timeout := time.NewTimer(syncChallengeTimeout)
   390  			defer timeout.Stop()
   391  
   392  			select {
   393  			case res := <-resCh:
   394  				headers := ([]*types.Header)(*res.Res.(*eth.BlockHeadersPacket))
   395  				if len(headers) == 0 {
   396  					// If we're doing a snap sync, we must enforce the checkpoint
   397  					// block to avoid eclipse attacks. Unsynced nodes are welcome
   398  					// to connect after we're done joining the network.
   399  					if atomic.LoadUint32(&h.snapSync) == 1 {
   400  						peer.Log().Warn("Dropping unsynced node during sync", "addr", peer.RemoteAddr(), "type", peer.Name())
   401  						res.Done <- errors.New("unsynced node cannot serve sync")
   402  						return
   403  					}
   404  					res.Done <- nil
   405  					return
   406  				}
   407  				// Validate the header and either drop the peer or continue
   408  				if len(headers) > 1 {
   409  					res.Done <- errors.New("too many headers in checkpoint response")
   410  					return
   411  				}
   412  				if headers[0].Hash() != h.checkpointHash {
   413  					res.Done <- errors.New("checkpoint hash mismatch")
   414  					return
   415  				}
   416  				res.Done <- nil
   417  
   418  			case <-timeout.C:
   419  				peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
   420  				h.removePeer(peer.ID())
   421  
   422  			case <-dead:
   423  				// Peer handler terminated, abort all goroutines
   424  			}
   425  		}()
   426  	}
   427  	// If we have any explicit peer required block hashes, request them
   428  	for number := range h.peerRequiredBlocks {
   429  		resCh := make(chan *eth.Response)
   430  		if _, err := peer.RequestHeadersByNumber(number, 1, 0, false, resCh); err != nil {
   431  			return err
   432  		}
   433  		go func(number uint64, hash common.Hash) {
   434  			timeout := time.NewTimer(syncChallengeTimeout)
   435  			defer timeout.Stop()
   436  
   437  			select {
   438  			case res := <-resCh:
   439  				headers := ([]*types.Header)(*res.Res.(*eth.BlockHeadersPacket))
   440  				if len(headers) == 0 {
   441  					// Required blocks are allowed to be missing if the remote
   442  					// node is not yet synced
   443  					res.Done <- nil
   444  					return
   445  				}
   446  				// Validate the header and either drop the peer or continue
   447  				if len(headers) > 1 {
   448  					res.Done <- errors.New("too many headers in required block response")
   449  					return
   450  				}
   451  				if headers[0].Number.Uint64() != number || headers[0].Hash() != hash {
   452  					peer.Log().Info("Required block mismatch, dropping peer", "number", number, "hash", headers[0].Hash(), "want", hash)
   453  					res.Done <- errors.New("required block mismatch")
   454  					return
   455  				}
   456  				peer.Log().Debug("Peer required block verified", "number", number, "hash", hash)
   457  				res.Done <- nil
   458  			case <-timeout.C:
   459  				peer.Log().Warn("Required block challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
   460  				h.removePeer(peer.ID())
   461  			}
   462  		}(number, hash)
   463  	}
   464  	// Handle incoming messages until the connection is torn down
   465  	return handler(peer)
   466  }
   467  
   468  // runSnapExtension registers a `snap` peer into the joint eth/snap peerset and
   469  // starts handling inbound messages. As `snap` is only a satellite protocol to
   470  // `eth`, all subsystem registrations and lifecycle management will be done by
   471  // the main `eth` handler to prevent strange races.
   472  func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error {
   473  	h.peerWG.Add(1)
   474  	defer h.peerWG.Done()
   475  
   476  	if err := h.peers.registerSnapExtension(peer); err != nil {
   477  		peer.Log().Warn("Snapshot extension registration failed", "err", err)
   478  		return err
   479  	}
   480  	return handler(peer)
   481  }
   482  
   483  // removePeer requests disconnection of a peer.
   484  func (h *handler) removePeer(id string) {
   485  	peer := h.peers.peer(id)
   486  	if peer != nil {
   487  		peer.Peer.Disconnect(p2p.DiscUselessPeer)
   488  	}
   489  }
   490  
   491  // unregisterPeer removes a peer from the downloader, fetchers and main peer set.
   492  func (h *handler) unregisterPeer(id string) {
   493  	// Create a custom logger to avoid printing the entire id
   494  	var logger log.Logger
   495  	if len(id) < 16 {
   496  		// Tests use short IDs, don't choke on them
   497  		logger = log.New("peer", id)
   498  	} else {
   499  		logger = log.New("peer", id[:8])
   500  	}
   501  	// Abort if the peer does not exist
   502  	peer := h.peers.peer(id)
   503  	if peer == nil {
   504  		logger.Error("Ethereum peer removal failed", "err", errPeerNotRegistered)
   505  		return
   506  	}
   507  	// Remove the `eth` peer if it exists
   508  	logger.Debug("Removing Ethereum peer", "snap", peer.snapExt != nil)
   509  
   510  	// Remove the `snap` extension if it exists
   511  	if peer.snapExt != nil {
   512  		h.downloader.SnapSyncer.Unregister(id)
   513  	}
   514  	h.downloader.UnregisterPeer(id)
   515  	h.txFetcher.Drop(id)
   516  
   517  	if err := h.peers.unregisterPeer(id); err != nil {
   518  		logger.Error("Ethereum peer removal failed", "err", err)
   519  	}
   520  }
   521  
   522  func (h *handler) Start(maxPeers int) {
   523  	h.maxPeers = maxPeers
   524  
   525  	// broadcast transactions
   526  	h.wg.Add(1)
   527  	h.txsCh = make(chan core.NewTxsEvent, txChanSize)
   528  	h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh)
   529  	go h.txBroadcastLoop()
   530  
   531  	// broadcast mined blocks
   532  	h.wg.Add(1)
   533  	h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{})
   534  	go h.minedBroadcastLoop()
   535  
   536  	// start sync handlers
   537  	h.wg.Add(1)
   538  	go h.chainSync.loop()
   539  }
   540  
   541  func (h *handler) Stop() {
   542  	h.txsSub.Unsubscribe()        // quits txBroadcastLoop
   543  	h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
   544  
   545  	// Quit chainSync and txsync64.
   546  	// After this is done, no new peers will be accepted.
   547  	close(h.quitSync)
   548  	h.wg.Wait()
   549  
   550  	// Disconnect existing sessions.
   551  	// This also closes the gate for any new registrations on the peer set.
   552  	// sessions which are already established but not added to h.peers yet
   553  	// will exit when they try to register.
   554  	h.peers.close()
   555  	h.peerWG.Wait()
   556  
   557  	log.Info("Ethereum protocol stopped")
   558  }
   559  
   560  // BroadcastBlock will either propagate a block to a subset of its peers, or
   561  // will only announce its availability (depending what's requested).
   562  func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
   563  	// Disable the block propagation if the chain has already entered the PoS
   564  	// stage. The block propagation is delegated to the consensus layer.
   565  	if h.merger.PoSFinalized() {
   566  		return
   567  	}
   568  	// Disable the block propagation if it's the post-merge block.
   569  	if beacon, ok := h.chain.Engine().(*beacon.Beacon); ok {
   570  		if beacon.IsPoSHeader(block.Header()) {
   571  			return
   572  		}
   573  	}
   574  	hash := block.Hash()
   575  	peers := h.peers.peersWithoutBlock(hash)
   576  
   577  	// If propagation is requested, send to a subset of the peer
   578  	if propagate {
   579  		// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
   580  		var td *big.Int
   581  		if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
   582  			td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1))
   583  		} else {
   584  			log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
   585  			return
   586  		}
   587  		// Send the block to a subset of our peers
   588  		transfer := peers[:int(math.Sqrt(float64(len(peers))))]
   589  		for _, peer := range transfer {
   590  			peer.AsyncSendNewBlock(block, td)
   591  		}
   592  		log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   593  		return
   594  	}
   595  	// Otherwise if the block is indeed in out own chain, announce it
   596  	if h.chain.HasBlock(hash, block.NumberU64()) {
   597  		for _, peer := range peers {
   598  			peer.AsyncSendNewBlockHash(block)
   599  		}
   600  		log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   601  	}
   602  }
   603  
   604  // BroadcastTransactions will propagate a batch of transactions
   605  // - To a square root of all peers
   606  // - And, separately, as announcements to all peers which are not known to
   607  // already have the given transaction.
   608  func (h *handler) BroadcastTransactions(txs types.Transactions) {
   609  	var (
   610  		annoCount   int // Count of announcements made
   611  		annoPeers   int
   612  		directCount int // Count of the txs sent directly to peers
   613  		directPeers int // Count of the peers that were sent transactions directly
   614  
   615  		txset = make(map[*ethPeer][]common.Hash) // Set peer->hash to transfer directly
   616  		annos = make(map[*ethPeer][]common.Hash) // Set peer->hash to announce
   617  
   618  	)
   619  	// Broadcast transactions to a batch of peers not knowing about it
   620  	for _, tx := range txs {
   621  		peers := h.peers.peersWithoutTransaction(tx.Hash())
   622  		// Send the tx unconditionally to a subset of our peers
   623  		numDirect := int(math.Sqrt(float64(len(peers))))
   624  		for _, peer := range peers[:numDirect] {
   625  			txset[peer] = append(txset[peer], tx.Hash())
   626  		}
   627  		// For the remaining peers, send announcement only
   628  		for _, peer := range peers[numDirect:] {
   629  			annos[peer] = append(annos[peer], tx.Hash())
   630  		}
   631  	}
   632  	for peer, hashes := range txset {
   633  		directPeers++
   634  		directCount += len(hashes)
   635  		peer.AsyncSendTransactions(hashes)
   636  	}
   637  	for peer, hashes := range annos {
   638  		annoPeers++
   639  		annoCount += len(hashes)
   640  		peer.AsyncSendPooledTransactionHashes(hashes)
   641  	}
   642  	log.Debug("Transaction broadcast", "txs", len(txs),
   643  		"announce packs", annoPeers, "announced hashes", annoCount,
   644  		"tx packs", directPeers, "broadcast txs", directCount)
   645  }
   646  
   647  // minedBroadcastLoop sends mined blocks to connected peers.
   648  func (h *handler) minedBroadcastLoop() {
   649  	defer h.wg.Done()
   650  
   651  	for obj := range h.minedBlockSub.Chan() {
   652  		if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
   653  			h.BroadcastBlock(ev.Block, true)  // First propagate block to peers
   654  			h.BroadcastBlock(ev.Block, false) // Only then announce to the rest
   655  		}
   656  	}
   657  }
   658  
   659  // txBroadcastLoop announces new transactions to connected peers.
   660  func (h *handler) txBroadcastLoop() {
   661  	defer h.wg.Done()
   662  	for {
   663  		select {
   664  		case event := <-h.txsCh:
   665  			h.BroadcastTransactions(event.Txs)
   666  		case <-h.txsSub.Err():
   667  			return
   668  		}
   669  	}
   670  }