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