Skip to main content

zebra_network/peer_set/
set.rs

1//! Abstractions that represent "the rest of the network".
2//!
3//! # Implementation
4//!
5//! The [`PeerSet`] implementation is adapted from the one in [tower::Balance][tower-balance].
6//!
7//! As described in Tower's documentation, it:
8//!
9//! > Distributes requests across inner services using the [Power of Two Choices][p2c].
10//! >
11//! > As described in the [Finagle Guide][finagle]:
12//! >
13//! > > The algorithm randomly picks two services from the set of ready endpoints and
14//! > > selects the least loaded of the two. By repeatedly using this strategy, we can
15//! > > expect a manageable upper bound on the maximum load of any server.
16//! > >
17//! > > The maximum load variance between any two servers is bound by `ln(ln(n))` where
18//! > > `n` is the number of servers in the cluster.
19//!
20//! The Power of Two Choices should work well for many network requests, but not all of them.
21//! Some requests should only be made to a subset of connected peers.
22//! For example, a request for a particular inventory item
23//! should be made to a peer that has recently advertised that inventory hash.
24//! Other requests require broadcasts, such as transaction diffusion.
25//!
26//! Implementing this specialized routing logic inside the `PeerSet` -- so that
27//! it continues to abstract away "the rest of the network" into one endpoint --
28//! is not a problem, as the `PeerSet` can simply maintain more information on
29//! its peers and route requests appropriately. However, there is a problem with
30//! maintaining accurate backpressure information, because the `Service` trait
31//! requires that service readiness is independent of the data in the request.
32//!
33//! For this reason, in the future, this code will probably be refactored to
34//! address this backpressure mismatch. One possibility is to refactor the code
35//! so that one entity holds and maintains the peer set and metadata on the
36//! peers, and each "backpressure category" of request is assigned to different
37//! `Service` impls with specialized `poll_ready()` implementations. Another
38//! less-elegant solution (which might be useful as an intermediate step for the
39//! inventory case) is to provide a way to borrow a particular backing service,
40//! say by address.
41//!
42//! [finagle]: https://twitter.github.io/finagle/guide/Clients.html#power-of-two-choices-p2c-least-loaded
43//! [p2c]: http://www.eecs.harvard.edu/~michaelm/postscripts/handbook2001.pdf
44//! [tower-balance]: https://github.com/tower-rs/tower/tree/master/tower/src/balance
45//!
46//! # Behavior During Network Upgrades
47//!
48//! [ZIP-201] specifies peer behavior during network upgrades:
49//!
50//! > With scheduled network upgrades, at the activation height, nodes on each consensus branch
51//! > should disconnect from nodes on other consensus branches and only accept new incoming
52//! > connections from nodes on the same consensus branch.
53//!
54//! Zebra handles this with the help of [`MinimumPeerVersion`], which determines the minimum peer
55//! protocol version to accept based on the current best chain tip height. The minimum version is
56//! therefore automatically increased when the block height reaches a network upgrade's activation
57//! height. The helper type is then used to:
58//!
59//! - cancel handshakes to outdated peers, in `handshake::negotiate_version`
60//! - cancel requests to and disconnect from peers that have become outdated, in
61//!   [`PeerSet::push_unready`]
62//! - disconnect from peers that have just responded and became outdated, in
63//!   [`PeerSet::poll_unready`]
64//! - disconnect from ready or busy peers whose authorization was revoked, in
65//!   [`PeerSet::disconnect_from_ineligible_peers`]
66//!
67//! ## Network Coalescence
68//!
69//! [ZIP-201] also specifies how Zcashd behaves [leading up to a activation
70//! height][1]. Since Zcashd limits the number of connections to at most eight
71//! peers, it will gradually migrate its connections to up-to-date peers as it
72//! approaches the activation height.
73//!
74//! The motivation for this behavior is to avoid an abrupt partitioning the network, which can lead
75//! to isolated peers and increases the chance of an eclipse attack on some peers of the network.
76//!
77//! Zebra does not gradually migrate its peers as it approaches an activation height. This is
78//! because Zebra by default can connect to up to 75 peers, as can be seen in [`Config::default`].
79//! Since this is a lot larger than the 8 peers Zcashd connects to, an eclipse attack becomes a lot
80//! more costly to execute, and the probability of an abrupt network partition that isolates peers
81//! is lower.
82//!
83//! Even if a Zebra node is manually configured to connect to a smaller number
84//! of peers, the [`AddressBook`][2] is configured to hold a large number of
85//! peer addresses ([`MAX_ADDRS_IN_ADDRESS_BOOK`][3]). Since the address book
86//! prioritizes addresses it trusts (like those that it has successfully
87//! connected to before), the node should be able to recover and rejoin the
88//! network by itself, as long as the address book is populated with enough
89//! entries.
90//!
91//! [1]: https://zips.z.cash/zip-0201#network-coalescence
92//! [2]: crate::AddressBook
93//! [3]: crate::constants::MAX_ADDRS_IN_ADDRESS_BOOK
94//! [ZIP-201]: https://zips.z.cash/zip-0201
95
96use std::{
97    collections::{HashMap, HashSet, VecDeque},
98    convert,
99    fmt::Debug,
100    marker::PhantomData,
101    net::IpAddr,
102    pin::Pin,
103    sync::Arc,
104    task::{Context, Poll, Waker},
105    time::Instant,
106};
107
108use futures::{
109    channel::{mpsc, oneshot},
110    future::{FutureExt, TryFutureExt},
111    prelude::*,
112    stream::FuturesUnordered,
113    task::noop_waker,
114};
115use itertools::Itertools;
116use tokio::{
117    sync::{broadcast, mpsc as tokio_mpsc, watch},
118    task::JoinHandle,
119};
120use tower::{
121    buffer::Buffer,
122    discover::{Change, Discover},
123    load::Load,
124    util::BoxService,
125    Service, ServiceExt,
126};
127use tracing::Instrument;
128
129use zebra_chain::{chain_tip::ChainTip, parameters::Network};
130
131use crate::{
132    address_book::AddressMetrics,
133    connection_metrics::network_kind_label,
134    constants::{
135        FIND_BUSY_SERVING_PEER_WAIT_TIMEOUT, INVENTORY_BUSY_PEER_WAIT_TIMEOUT,
136        MIN_PEER_SET_LOG_INTERVAL,
137    },
138    peer::{ConnectionInfo, LoadTrackedClient, MinimumPeerVersion},
139    peer_set::{
140        stall_tracker::FindResponseStallTracker,
141        unready_service::{Error as UnreadyError, UnreadyService},
142        InventoryChange, InventoryRegistry,
143    },
144    protocol::{
145        external::{connection_limit_key, InventoryHash},
146        internal::{Request, Response},
147    },
148    BanList, BoxError, Config, PeerError, PeerSocketAddr, SharedPeerError,
149};
150
151#[cfg(any(test, feature = "proptest-impl"))]
152pub(crate) mod tests;
153
154/// A signal sent by the [`PeerSet`] when it has no ready peers, and gets a request from Zebra.
155///
156/// In response to this signal, the crawler tries to open more peer connections.
157#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
158pub struct MorePeers;
159
160/// A signal sent by the [`PeerSet`] to cancel a [`Client`][1]'s current request
161/// or response.
162///
163/// When it receives this signal, the [`Client`][1] stops processing and exits.
164///
165/// [1]: crate::peer::Client
166#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
167pub struct CancelClientWork;
168
169type ResponseFuture = Pin<Box<dyn Future<Output = Result<Response, BoxError>> + Send + 'static>>;
170
171/// A block request that no ready peer could serve, waiting for a busy peer that might have the
172/// block to become ready.
173struct QueuedInvRequest {
174    /// The request to route.
175    request: Request,
176
177    /// The requested inventory.
178    hash: InventoryHash,
179
180    /// The enqueue-time refusal deadline; downloaders enforce their own operation deadline.
181    deadline: Option<tokio::time::Instant>,
182
183    /// The original request's tracing context.
184    span: tracing::Span,
185
186    /// Receives the response future of the peer the request is routed to.
187    ///
188    /// Dropping the sender refuses the request.
189    response_sender: oneshot::Sender<ResponseFuture>,
190}
191
192/// Bounds queued discovery requests; overflow falls back to any ready peer.
193const MAX_QUEUED_FIND_REQUESTS: usize = 16;
194
195/// A find request waiting for a serving peer, with a bounded serving-only preference.
196struct QueuedFindRequest {
197    /// The request to route.
198    request: Request,
199
200    /// When this request may fall back to any ready peer.
201    deadline: tokio::time::Instant,
202
203    /// Receives the selected peer's response future; cancellation abandons the queued request.
204    response_sender: oneshot::Sender<ResponseFuture>,
205}
206
207/// Where the peer set routes an inventory request.
208enum InvRoute<K> {
209    /// Send the request to this ready peer.
210    Peer {
211        /// The peer to send the request to.
212        peer: K,
213
214        /// Whether the peer was chosen because it advertised the inventory.
215        advertised: bool,
216    },
217
218    /// Queue the request until a busy peer that might have the inventory becomes ready.
219    Wait,
220
221    /// Refuse the request, because no connected peer might have the inventory.
222    Refuse,
223}
224
225/// Returns the synthetic error for an inventory request that the peer set refuses.
226///
227/// # Security
228///
229/// Avoid routing requests to peers that are missing inventory.
230/// If we kept trying doomed requests, peers that are missing our requested inventory
231/// could take up a large amount of our bandwidth and retry limits.
232fn not_found_registry_error(hash: InventoryHash) -> BoxError {
233    SharedPeerError::from(PeerError::NotFoundRegistry(vec![hash])).into()
234}
235
236/// Classification of a `FindBlocks`/`FindHeaders` response, sent from a
237/// response-wrapping future to [`PeerSet::poll_ready`] via an mpsc channel so
238/// the stall tracker can be updated and the peer disconnected if needed.
239#[derive(Copy, Clone, Debug, PartialEq, Eq)]
240enum StallOutcome {
241    Stall,
242    Clear,
243}
244
245type StallEvent = (PeerSocketAddr, Arc<ConnectionInfo>, StallOutcome);
246
247/// How a routed block request ended, for the [`InventoryRegistry`].
248#[derive(Copy, Clone, Debug, Eq, PartialEq)]
249enum InvOutcome {
250    /// The peer failed to return the block.
251    Failed,
252
253    /// The peer answered the request with a `notfound` that lists the block.
254    Refused,
255
256    /// The peer returned a block, after it was chosen because the block was advertised, or in a
257    /// repeat request for the block.
258    Served,
259}
260
261/// The peer and connection that got a block request, the block, and how the request ended.
262type InvOutcomeEvent = (
263    PeerSocketAddr,
264    Arc<ConnectionInfo>,
265    InventoryHash,
266    InvOutcome,
267);
268
269/// Empty replies are valid when the locator reaches the remote tip. Neither a local wall-clock
270/// estimate nor an untrusted, frozen handshake height proves otherwise. Fair discovery routing
271/// prevents fast empty replies from monopolizing requests.
272fn classify_find_response<E>(result: &Result<Response, E>) -> Option<StallOutcome> {
273    match result {
274        Ok(Response::BlockHashes(_) | Response::BlockHeaders(_)) => Some(StallOutcome::Clear),
275        Ok(_) => None,
276        Err(_) => Some(StallOutcome::Stall),
277    }
278}
279
280/// A [`tower::Service`] that abstractly represents "the rest of the network".
281///
282/// # Security
283///
284/// The `Discover::Key` must be the transient remote address of each peer. This
285/// address may only be valid for the duration of a single connection. (For
286/// example, inbound connections have an ephemeral remote port, and proxy
287/// connections have an ephemeral local or proxy port.)
288///
289/// Otherwise, malicious peers could interfere with other peers' `PeerSet` state.
290pub struct PeerSet<D, C>
291where
292    D: Discover<Key = PeerSocketAddr, Service = LoadTrackedClient> + Unpin,
293    D::Error: Into<BoxError>,
294    C: ChainTip,
295{
296    // Peer Tracking: New Peers
297    //
298    /// Provides new and deleted peer [`Change`]s to the peer set,
299    /// via the [`Discover`] trait implementation.
300    discover: D,
301
302    /// A channel that asks the peer crawler task to connect to more peers.
303    demand_signal: mpsc::Sender<MorePeers>,
304
305    /// A watch channel receiver with a snapshot of the banned peer groups.
306    bans_receiver: watch::Receiver<BanList>,
307
308    /// Tracks peers returning failed `FindBlocks`/`FindHeaders` responses.
309    /// Mutated only from [`Self::poll_ready`] via [`Self::stall_event_rx`].
310    find_response_stalls: FindResponseStallTracker,
311
312    /// Receives stall/clear events from tracked routing futures in
313    /// [`Self::call_ready_peer`]. The channel keeps the tracker single-owner (no
314    /// `Mutex`) and confines mutation to `poll_ready`, where the peer set can
315    /// call [`Self::remove`] directly.
316    stall_event_rx: tokio_mpsc::UnboundedReceiver<StallEvent>,
317
318    /// Producer clones handed to each tracked request's response wrapper.
319    stall_event_tx: tokio_mpsc::UnboundedSender<StallEvent>,
320
321    /// Receives completed block request errors, and blocks that peers returned after they were
322    /// chosen for an advertisement or in a repeat request, from response futures and records them
323    /// in the [`InventoryRegistry`]. Caller cancellation is not evidence of a peer failure.
324    ///
325    /// Each routed block request sends at most one outcome, so the channel is limited by the
326    /// number of block requests in flight.
327    inv_failure_rx: tokio_mpsc::UnboundedReceiver<InvOutcomeEvent>,
328
329    /// Producer clones handed to each block request's response future.
330    inv_failure_tx: tokio_mpsc::UnboundedSender<InvOutcomeEvent>,
331
332    // Peer Tracking: Ready Peers
333    //
334    /// Connected peers that are ready to receive requests from Zebra,
335    /// or send requests to Zebra.
336    ready_services: HashMap<D::Key, D::Service>,
337
338    // Request Routing
339    //
340    /// Connection identities in find-request order, preserved while peers are busy.
341    ///
342    /// New connections join at the back; disconnected connections are pruned in
343    /// [`Self::poll_peers`]. The metadata allocation identifies a connection even if
344    /// a later connection reuses its address.
345    find_peer_queue: VecDeque<(D::Key, Arc<ConnectionInfo>)>,
346
347    /// Find requests waiting for a serving peer, in request order.
348    ///
349    /// After [`FIND_BUSY_SERVING_PEER_WAIT_TIMEOUT`], any ready peer can receive the request.
350    queued_find_requests: VecDeque<QueuedFindRequest>,
351
352    /// Wakes the peer set at the next unexpired queued find request deadline.
353    ///
354    /// Expired requests wait for peer events rather than repeatedly waking a completed timer.
355    queued_find_request_timer: Option<Pin<Box<tokio::time::Sleep>>>,
356
357    /// Stores gossiped inventory hashes from connected peers.
358    ///
359    /// Used to route inventory requests to peers that are likely to have it.
360    inventory_registry: InventoryRegistry,
361
362    /// Block advert channels and remote versions for every connected peer, including busy peers.
363    block_advert_senders: watch::Sender<super::AdvertPeers>,
364
365    /// Coalesced discovery wakeups and bounded advert-maintenance completion requests.
366    maintenance_waker: Arc<super::PeerSetWaker>,
367    maintenance_tx: tokio_mpsc::Sender<tokio::sync::oneshot::Sender<()>>,
368    maintenance_rx: tokio_mpsc::Receiver<tokio::sync::oneshot::Sender<()>>,
369
370    /// Only waiters captured before reconciliation can complete afterward. Retain the fixed batch
371    /// across partial discovery drains and while no advert peer is eligible; later arrivals wait
372    /// in the bounded channel.
373    maintenance_batch:
374        [Option<tokio::sync::oneshot::Sender<()>>; crate::constants::PEERSET_BUFFER_SIZE],
375
376    /// Inbound peer IPs that must always receive block inventory broadcasts.
377    block_gossip_peer_ips: HashSet<IpAddr>,
378
379    /// The keys of connected peers that matched [`Self::block_gossip_peer_ips`]
380    /// when they were inserted into the peer set.
381    ///
382    /// Stale keys of disconnected peers are pruned by
383    /// [`Self::prune_disconnected_sidecar_keys`].
384    zcashd_compat_peer_keys: HashSet<D::Key>,
385
386    /// The keys of connected peers whose services
387    /// [serve full history](crate::types::PeerServices::serves_full_history).
388    ///
389    /// Busy peers' services are not otherwise accessible, but block and find routing need to
390    /// know whether a busy peer can serve blocks. Stale keys of disconnected peers are pruned by
391    /// [`Self::retain_connected_keys`].
392    serving_peer_keys: HashSet<D::Key>,
393
394    /// Block requests that are waiting for a busy peer that might have the block, in the order
395    /// they were made.
396    ///
397    /// Each request is routed to the first of those peers that becomes ready, or refused once
398    /// [`INVENTORY_BUSY_PEER_WAIT_TIMEOUT`] expires, or once no busy peer might have the block.
399    queued_inv_requests: VecDeque<QueuedInvRequest>,
400
401    /// Whether queued block requests took the last ready peer from the request the [`Buffer`] is
402    /// holding, so that request gets the next ready peer before the rest of the queue.
403    ///
404    /// The Buffer only calls the peer set with that request once the peer set is ready. Queued
405    /// block requests can usually use every ready serving peer, so without a turn, the held
406    /// request, which can be discovery, would wait until the whole queue drains.
407    ///
408    /// Only [`Self::call`] clears it, so it survives readiness passes where a queued find or
409    /// sidecar broadcast takes the kept peer.
410    queued_inv_requests_took_last_peer: bool,
411
412    /// The most recent pushed transaction owed to busy sidecars.
413    /// A newer transaction supersedes it. Block adverts use the separate acknowledged channels.
414    queued_sidecar_broadcast: Option<(Request, HashSet<D::Key>)>,
415
416    // Peer Tracking: Busy Peers
417    //
418    /// Connected peers that are handling a Zebra request,
419    /// or Zebra is handling one of their requests.
420    unready_services: FuturesUnordered<UnreadyService<D::Key, D::Service, Request>>,
421
422    /// Channels used to cancel the request that an unready service is doing.
423    cancel_handles: HashMap<D::Key, oneshot::Sender<CancelClientWork>>,
424
425    // Peer Validation
426    //
427    /// An endpoint to see the minimum peer protocol version in real time.
428    ///
429    /// The minimum version depends on the block height, and [`MinimumPeerVersion`] listens for
430    /// height changes and determines the correct minimum version.
431    minimum_peer_version: MinimumPeerVersion<C>,
432
433    /// The configured limit for inbound and outbound connections.
434    ///
435    /// The peer set panics if this size is exceeded.
436    /// If that happens, our connection limit code has a bug.
437    peerset_total_connection_limit: usize,
438
439    // Background Tasks
440    //
441    /// Channel for passing ownership of tokio JoinHandles from PeerSet's background tasks
442    ///
443    /// The join handles passed into the PeerSet are used populate the `guards` member
444    handle_rx: tokio::sync::oneshot::Receiver<Vec<JoinHandle<Result<(), BoxError>>>>,
445
446    /// Unordered set of handles to background tasks associated with the `PeerSet`
447    ///
448    /// These guards are checked for errors as part of `poll_ready` which lets
449    /// the `PeerSet` propagate errors from background tasks back to the user
450    guards: futures::stream::FuturesUnordered<JoinHandle<Result<(), BoxError>>>,
451
452    // Metrics and Logging
453    //
454    /// Address book metrics watch channel.
455    ///
456    /// Used for logging diagnostics.
457    address_metrics: watch::Receiver<AddressMetrics>,
458
459    /// The last time we logged a message about the peer set size
460    last_peer_log: Option<Instant>,
461
462    /// The configured maximum number of peers that can be in the
463    /// peer set per connection limit key, defaults to [`crate::constants::DEFAULT_MAX_CONNS_PER_IP`]
464    max_conns_per_ip: usize,
465
466    /// The network of this peer set.
467    network: Network,
468}
469
470impl<D, C> Drop for PeerSet<D, C>
471where
472    D: Discover<Key = PeerSocketAddr, Service = LoadTrackedClient> + Unpin,
473    D::Error: Into<BoxError>,
474    C: ChainTip,
475{
476    fn drop(&mut self) {
477        // We don't have access to the current task (if any), so we just drop everything we can.
478        let waker = noop_waker();
479        let mut cx = Context::from_waker(&waker);
480
481        self.shut_down_tasks_and_channels(&mut cx);
482    }
483}
484
485impl<D, C> PeerSet<D, C>
486where
487    D: Discover<Key = PeerSocketAddr, Service = LoadTrackedClient> + Unpin,
488    D::Error: Into<BoxError>,
489    C: ChainTip,
490{
491    #[allow(clippy::too_many_arguments)]
492    /// Construct a peerset which uses `discover` to manage peer connections.
493    ///
494    /// Arguments:
495    /// - `config`: configures the peer set connection limit;
496    /// - `block_gossip_peer_ips`: inbound peer IPs that must always receive block inventory broadcasts.
497    /// - `discover`: handles peer connects and disconnects;
498    /// - `demand_signal`: requests more peers when all peers are busy (unready);
499    /// - `handle_rx`: receives background task handles,
500    ///   monitors them to make sure they're still running,
501    ///   and shuts down all the tasks as soon as one task exits;
502    /// - `inv_stream`: receives inventory changes from peers,
503    ///   allowing the peer set to direct inventory requests;
504    /// - `bans_receiver`: receives a map of banned IP addresses that should be dropped;
505    /// - `address_book`: when peer set is busy, it logs address book diagnostics.
506    /// - `minimum_peer_version`: endpoint to see the minimum peer protocol version in real time.
507    /// - `max_conns_per_ip`: configured maximum number of peers that can be in the
508    ///   peer set per connection limit key, defaults to the config value or to
509    ///   [`crate::constants::DEFAULT_MAX_CONNS_PER_IP`].
510    pub fn new(
511        config: &Config,
512        block_gossip_peer_ips: Vec<IpAddr>,
513        discover: D,
514        demand_signal: mpsc::Sender<MorePeers>,
515        handle_rx: tokio::sync::oneshot::Receiver<Vec<JoinHandle<Result<(), BoxError>>>>,
516        inv_stream: broadcast::Receiver<InventoryChange>,
517        bans_receiver: watch::Receiver<BanList>,
518        address_metrics: watch::Receiver<AddressMetrics>,
519        minimum_peer_version: MinimumPeerVersion<C>,
520        max_conns_per_ip: Option<usize>,
521    ) -> Self {
522        let (stall_event_tx, stall_event_rx) = tokio_mpsc::unbounded_channel();
523        let (inv_failure_tx, inv_failure_rx) = tokio_mpsc::unbounded_channel();
524        let (maintenance_tx, maintenance_rx) =
525            tokio_mpsc::channel(crate::constants::PEERSET_BUFFER_SIZE);
526        Self {
527            // New peers
528            discover,
529            demand_signal,
530            // Banned peers
531            bans_receiver,
532
533            // Stall tracking
534            find_response_stalls: FindResponseStallTracker::new(),
535            stall_event_rx,
536            stall_event_tx,
537
538            // Failed block request tracking
539            inv_failure_rx,
540            inv_failure_tx,
541
542            // Ready peers
543            ready_services: HashMap::new(),
544            // Request Routing
545            find_peer_queue: VecDeque::new(),
546            queued_find_requests: VecDeque::new(),
547            queued_find_request_timer: None,
548            inventory_registry: InventoryRegistry::new(inv_stream),
549            block_advert_senders: watch::channel(HashMap::new()).0,
550            maintenance_waker: Arc::default(),
551            maintenance_tx,
552            maintenance_rx,
553            maintenance_batch: std::array::from_fn(|_| None),
554            block_gossip_peer_ips: block_gossip_peer_ips.into_iter().collect(),
555            zcashd_compat_peer_keys: HashSet::new(),
556            serving_peer_keys: HashSet::new(),
557            queued_inv_requests: VecDeque::new(),
558            queued_inv_requests_took_last_peer: false,
559            queued_sidecar_broadcast: None,
560
561            // Busy peers
562            unready_services: FuturesUnordered::new(),
563            cancel_handles: HashMap::new(),
564
565            // Peer validation
566            minimum_peer_version,
567            peerset_total_connection_limit: config.peerset_total_connection_limit(),
568
569            // Background tasks
570            handle_rx,
571            guards: futures::stream::FuturesUnordered::new(),
572
573            // Metrics
574            last_peer_log: None,
575            address_metrics,
576
577            max_conns_per_ip: max_conns_per_ip.unwrap_or(config.max_connections_per_ip),
578
579            network: config.network.clone(),
580        }
581    }
582
583    /// Return the independently bounded block advertiser for this peer set.
584    pub(crate) fn block_advertiser(&self) -> super::BlockAdvertiser<C>
585    where
586        C: Clone + Send + 'static,
587    {
588        super::BlockAdvertiser {
589            inner: tower::limit::ConcurrencyLimit::new(
590                super::AdvertisePeers {
591                    peers: self.block_advert_senders.subscribe(),
592                    bans: self.bans_receiver.clone(),
593                    minimum_version: self.minimum_peer_version.clone(),
594                    network: self.network.clone(),
595                    maintenance: tokio_util::sync::PollSender::new(self.maintenance_tx.clone()),
596                    wake: self.maintenance_waker.clone(),
597                    completion: None,
598                    maintained: false,
599                },
600                crate::constants::PEERSET_BUFFER_SIZE,
601            ),
602        }
603    }
604
605    /// Check background task handles to make sure they're still running.
606    ///
607    /// Never returns `Ok`.
608    ///
609    /// If any background task exits, shuts down all other background tasks,
610    /// and returns an error. Otherwise, returns `Pending`, and registers a wakeup for
611    /// receiving the background tasks, or the background tasks exiting.
612    fn poll_background_errors(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
613        futures::ready!(self.receive_tasks_if_needed(cx))?;
614
615        // Return Pending if all background tasks are still running.
616        match futures::ready!(Pin::new(&mut self.guards).poll_next(cx)) {
617            Some(res) => {
618                info!(
619                    background_tasks = %self.guards.len(),
620                    "a peer set background task exited, shutting down other peer set tasks"
621                );
622
623                self.shut_down_tasks_and_channels(cx);
624
625                // Flatten the join result and inner result, and return any errors.
626                res.map_err(Into::into)
627                    // TODO: replace with Result::flatten when it stabilises (#70142)
628                    .and_then(convert::identity)?;
629
630                // Turn Ok() task exits into errors.
631                Poll::Ready(Err("a peer set background task exited".into()))
632            }
633
634            None => {
635                self.shut_down_tasks_and_channels(cx);
636                Poll::Ready(Err("all peer set background tasks have exited".into()))
637            }
638        }
639    }
640
641    /// Receive background tasks, if they've been sent on the channel, but not consumed yet.
642    ///
643    /// Returns a result representing the current task state, or `Poll::Pending` if the background
644    /// tasks should be polled again to check their state.
645    fn receive_tasks_if_needed(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
646        if self.guards.is_empty() {
647            // Return Pending if the tasks have not been sent yet.
648            let handles = futures::ready!(Pin::new(&mut self.handle_rx).poll(cx));
649
650            match handles {
651                // The tasks have been sent, but not consumed yet.
652                Ok(handles) => {
653                    // Currently, the peer set treats an empty background task set as an error.
654                    //
655                    // TODO: refactor `handle_rx` and `guards` into an enum
656                    //       for the background task state: Waiting/Running/Shutdown.
657                    assert!(
658                        !handles.is_empty(),
659                        "the peer set requires at least one background task"
660                    );
661
662                    self.guards.extend(handles);
663
664                    Poll::Ready(Ok(()))
665                }
666
667                // The sender was dropped without sending the tasks.
668                Err(_) => Poll::Ready(Err(
669                    "sender did not send peer background tasks before it was dropped".into(),
670                )),
671            }
672        } else {
673            Poll::Ready(Ok(()))
674        }
675    }
676
677    /// Shut down:
678    /// - services by dropping the service lists
679    /// - background tasks via their join handles or cancel handles
680    /// - channels by closing the channel
681    fn shut_down_tasks_and_channels(&mut self, cx: &mut Context<'_>) {
682        // Drop services and cancel their background tasks.
683        self.ready_services = HashMap::new();
684        self.block_advert_senders.send_modify(HashMap::clear);
685
686        for (_peer_key, handle) in self.cancel_handles.drain() {
687            let _ = handle.send(CancelClientWork);
688        }
689        self.unready_services = FuturesUnordered::new();
690
691        // Refuse queued requests, because there are no peers left to route them to.
692        self.queued_inv_requests.clear();
693        self.queued_find_requests.clear();
694        self.queued_find_request_timer = None;
695
696        // Close the MorePeers channel for all senders,
697        // so we don't add more peers to a shut down peer set.
698        self.demand_signal.close_channel();
699
700        // Shut down background tasks, ignoring pending polls.
701        self.handle_rx.close();
702        let _ = self.receive_tasks_if_needed(cx);
703        for guard in self.guards.iter() {
704            guard.abort();
705        }
706    }
707
708    /// Checks for newly ready, disconnects from outdated peers, and polls ready peer errors.
709    fn poll_peers(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
710        // Busy connections must remain eligible too: neither a ban nor an upgrade waits for
711        // their request channel to regain capacity.
712        self.disconnect_from_ineligible_peers();
713
714        // Check for newly ready peers, including newly added peers (which are added as unready).
715        // So it needs to run after `poll_discover()`. Registers a wakeup if there are any unready
716        // peers.
717        //
718        // Request-channel backpressure is bounded independently of the wire response timeout.
719        let _poll_pending_or_ready: Poll<Option<()>> = self.poll_unready(cx)?;
720
721        // Check for failures in ready peers, removing newly errored or disconnected peers.
722        // So it needs to run after `poll_unready()`.
723        let ready_peers = self.poll_ready_peer_errors(cx);
724        self.find_peer_queue.retain(|(key, _)| {
725            let connected =
726                self.ready_services.contains_key(key) || self.cancel_handles.contains_key(key);
727            if !connected {
728                self.find_response_stalls.clear(*key);
729            }
730            connected
731        });
732        ready_peers.map(Ok)
733    }
734
735    /// Check busy peer services for request completion or errors.
736    ///
737    /// Move newly ready services to the ready list if they are for peers with supported protocol
738    /// versions, otherwise they are dropped. Also drop failed services.
739    ///
740    /// Never returns an error.
741    ///
742    /// Returns `Ok(Some(())` if at least one peer became ready, `Poll::Pending` if there are
743    /// unready peers, but none became ready, and `Ok(None)` if the unready peers were empty.
744    ///
745    /// If there are any remaining unready peers, registers a wakeup for the next time one becomes
746    /// ready. If there are no unready peers, doesn't register any wakeups. (Since wakeups come
747    /// from peers, there needs to be at least one peer to register a wakeup.)
748    fn poll_unready(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<()>, BoxError>> {
749        let mut result = Poll::Pending;
750
751        // # Correctness
752        //
753        // `poll_next()` must always be called, because `self.unready_services` could have been
754        // empty before the call to `self.poll_ready()`.
755        //
756        // > When new futures are added, `poll_next` must be called in order to begin receiving
757        // > wake-ups for new futures.
758        //
759        // <https://docs.rs/futures/latest/futures/stream/futures_unordered/struct.FuturesUnordered.html>
760        //
761        // Returns Pending if we've finished processing the unready service changes,
762        // but there are still some unready services.
763        loop {
764            // No ready peers left, but there are some unready peers pending.
765            let Poll::Ready(ready_peer) = Pin::new(&mut self.unready_services).poll_next(cx) else {
766                break;
767            };
768
769            match ready_peer {
770                // No unready peers in the list.
771                None => {
772                    // If we've finished processing the unready service changes, and there are no
773                    // unready services left, it doesn't make sense to return Pending, because
774                    // their stream is terminated. But when we add more unready peers and call
775                    // `poll_next()`, its termination status will be reset, and it will receive
776                    // wakeups again.
777                    if result.is_pending() {
778                        result = Poll::Ready(Ok(None));
779                    }
780
781                    break;
782                }
783
784                // Unready -> Ready
785                Some(Ok((key, svc))) => {
786                    trace!(?key, "service became ready");
787
788                    if self.bans_receiver.borrow().is_banned(key.ip()) {
789                        warn!(?key, "service is banned, dropping service");
790                        self.block_advert_senders.send_modify(|peers| {
791                            peers.remove(&key);
792                        });
793                        std::mem::drop(svc);
794                        let cancel = self.cancel_handles.remove(&key);
795                        debug_assert!(
796                            cancel.is_some(),
797                            "missing cancel handle for banned unready peer"
798                        );
799                        continue;
800                    }
801
802                    self.push_ready(true, key, svc);
803
804                    // Return Ok if at least one peer became ready.
805                    result = Poll::Ready(Ok(Some(())));
806                }
807
808                // Unready -> Canceled
809                Some(Err((key, UnreadyError::Canceled))) => {
810                    // A service be canceled because we've connected to the same service twice.
811                    // In that case, there is a cancel handle for the peer address,
812                    // but it belongs to the service for the newer connection.
813                    trace!(
814                        ?key,
815                        duplicate_connection = self.cancel_handles.contains_key(&key),
816                        "service was canceled, dropping service"
817                    );
818                }
819                Some(Err((key, UnreadyError::CancelHandleDropped(_)))) => {
820                    // Similarly, services with dropped cancel handes can have duplicates.
821                    trace!(
822                        ?key,
823                        duplicate_connection = self.cancel_handles.contains_key(&key),
824                        "cancel handle was dropped, dropping service"
825                    );
826                }
827                Some(Err((key, UnreadyError::TimedOut))) => {
828                    debug!(?key, "service readiness timed out, dropping service");
829                    self.block_advert_senders.send_modify(|peers| {
830                        peers.remove(&key);
831                    });
832                    let cancel = self.cancel_handles.remove(&key);
833                    assert!(
834                        cancel.is_some(),
835                        "timed-out unready service has a cancel handle"
836                    );
837                }
838
839                // Unready -> Errored
840                Some(Err((key, UnreadyError::Inner(error)))) => {
841                    debug!(%error, "service failed while unready, dropping service");
842                    self.block_advert_senders.send_modify(|peers| {
843                        peers.remove(&key);
844                    });
845
846                    let cancel = self.cancel_handles.remove(&key);
847                    assert!(cancel.is_some(), "missing cancel handle");
848                }
849            }
850        }
851
852        result
853    }
854
855    /// Checks previously ready peer services for errors.
856    ///
857    /// The only way these peer `Client`s can become unready is when we send them a request,
858    /// because the peer set has exclusive access to send requests to each peer. (If an inbound
859    /// request is in progress, it will be handled, then our request will be sent by the connection
860    /// task.)
861    ///
862    /// Returns `Poll::Ready` if there are some ready peers, and `Poll::Pending` if there are no
863    /// ready peers. Registers a wakeup if any peer has failed due to a disconnection, hang, or protocol error.
864    ///
865    /// # Panics
866    ///
867    /// If any peers somehow became unready without being sent a request. This indicates a bug in the peer set, where requests
868    /// are sent to peers without putting them in `unready_peers`.
869    fn poll_ready_peer_errors(&mut self, cx: &mut Context<'_>) -> Poll<()> {
870        let mut previous = HashMap::new();
871        std::mem::swap(&mut previous, &mut self.ready_services);
872
873        // TODO: consider only checking some peers each poll (for performance reasons),
874        //       but make sure we eventually check all of them.
875        for (key, mut svc) in previous.drain() {
876            let Poll::Ready(peer_readiness) = Pin::new(&mut svc).poll_ready(cx) else {
877                unreachable!(
878                    "unexpected unready peer: peers must be put into the unready_peers list \
879                     after sending them a request"
880                );
881            };
882
883            match peer_readiness {
884                // Still ready, add it back to the list.
885                Ok(()) => {
886                    if self.bans_receiver.borrow().is_banned(key.ip()) {
887                        debug!(?key, "service ip is banned, dropping service");
888                        self.block_advert_senders.send_modify(|peers| {
889                            peers.remove(&key);
890                        });
891                        std::mem::drop(svc);
892                        continue;
893                    }
894
895                    self.push_ready(false, key, svc)
896                }
897
898                // Ready -> Errored
899                Err(error) => {
900                    debug!(%error, "service failed while ready, dropping service");
901
902                    self.block_advert_senders.send_modify(|peers| {
903                        peers.remove(&key);
904                    });
905                    std::mem::drop(svc);
906                }
907            }
908        }
909
910        if self.ready_services.is_empty() {
911            Poll::Pending
912        } else {
913            Poll::Ready(())
914        }
915    }
916
917    /// Returns the number of peer connections Zebra already has with the
918    /// provided IPv4 address, or in the same IPv6 `/64` subnet.
919    ///
920    /// Peer set admission uses this count to enforce
921    /// [`Config::max_connections_per_ip`](crate::config::Config).
922    ///
923    /// # Performance
924    ///
925    /// This method is `O(connected peers)`, so it should not be called from a loop
926    /// that is already iterating through the peer set.
927    fn num_peers_with_ip(&self, ip: IpAddr) -> usize {
928        let limit_key = connection_limit_key(ip);
929        self.ready_services
930            .keys()
931            .chain(self.cancel_handles.keys())
932            .filter(|addr| connection_limit_key(addr.ip()) == limit_key)
933            .count()
934    }
935
936    /// Returns `true` if Zebra is already connected to the IP and port in `addr`.
937    fn has_peer_with_addr(&self, addr: PeerSocketAddr) -> bool {
938        self.ready_services.contains_key(&addr) || self.cancel_handles.contains_key(&addr)
939    }
940
941    /// Processes the entire list of newly inserted or removed services.
942    ///
943    /// Puts inserted services in the unready list.
944    /// Drops removed services, after cancelling any pending requests.
945    ///
946    /// If the peer connector channel is closed, returns an error.
947    ///
948    /// Returns true once pending discovery is drained. A connection-limit-sized batch bounds
949    /// each poll; exhausted batches schedule another poll before acknowledging maintenance.
950    fn poll_discover(&mut self, cx: &mut Context<'_>) -> Result<bool, BoxError> {
951        for _ in 0..self.peerset_total_connection_limit.max(1) {
952            // If we've emptied the list, finish looping, otherwise process the new peer.
953            let Poll::Ready(discovered) = Pin::new(&mut self.discover).poll_discover(cx) else {
954                return Ok(true);
955            };
956
957            // If the change channel has a permanent error, return that error.
958            let change = discovered
959                .ok_or("discovery stream closed")?
960                .map_err(Into::into)?;
961
962            // Process each change.
963            match change {
964                Change::Remove(key) => {
965                    trace!(?key, "got Change::Remove from Discover");
966                    self.remove(&key);
967                }
968                Change::Insert(key, svc) => {
969                    // We add peers as unready, so that we:
970                    // - always do the same checks on every ready peer, and
971                    // - check for any errors that happened right after the handshake
972                    trace!(?key, "got Change::Insert from Discover");
973
974                    // # Security
975                    //
976                    // Drop the new peer if we are already connected to it.
977                    // Preferring old connections avoids connection thrashing.
978                    if self.has_peer_with_addr(key) {
979                        std::mem::drop(svc);
980                        continue;
981                    }
982
983                    // Classify sidecars before the per-IP cap: a trusted sidecar
984                    // reconnecting from a new ephemeral port must not be blocked
985                    // by its own not-yet-swept dead connection still counting
986                    // against `max_conns_per_ip` (which defaults to 1), or the
987                    // wallet would silently stop following the chain.
988                    let is_sidecar = self.is_zcashd_compat_peer(&svc);
989
990                    // # Security
991                    //
992                    // drop the new peer if there are already `max_conns_per_ip` peers with
993                    // the same IPv4 address, or in the same IPv6 `/64` subnet. Sidecars are
994                    // exempt: they are trusted, and the listener already caps their inbound
995                    // slots.
996                    if !is_sidecar && self.num_peers_with_ip(key.ip()) >= self.max_conns_per_ip {
997                        std::mem::drop(svc);
998                        continue;
999                    }
1000
1001                    if is_sidecar {
1002                        self.zcashd_compat_peer_keys.insert(key);
1003                    }
1004
1005                    if svc.remote_services().serves_full_history() {
1006                        self.serving_peer_keys.insert(key);
1007                    } else {
1008                        self.serving_peer_keys.remove(&key);
1009                    }
1010                    self.inventory_registry.clear_peer_failures(key);
1011
1012                    self.find_peer_queue
1013                        .push_back((key, svc.connection_info().clone()));
1014                    self.block_advert_senders.send_modify(|peers| {
1015                        peers.insert(
1016                            key,
1017                            (
1018                                svc.remote_version(),
1019                                is_sidecar,
1020                                svc.block_advert_tx.clone(),
1021                            ),
1022                        );
1023                    });
1024                    self.push_unready(key, svc);
1025                }
1026            }
1027        }
1028
1029        cx.waker().wake_by_ref();
1030        Ok(false)
1031    }
1032
1033    /// Disconnects banned and outdated connections, whether ready or backpressured.
1034    fn disconnect_from_ineligible_peers(&mut self) {
1035        let minimum_version = self.minimum_peer_version.current();
1036        let bans = self.bans_receiver.borrow();
1037        self.find_peer_queue.retain(|(key, info)| {
1038            !bans.is_banned(key.ip()) && info.remote.version >= minimum_version
1039        });
1040        self.ready_services.retain(|key, service| {
1041            let eligible = !bans.is_banned(key.ip()) && service.remote_version() >= minimum_version;
1042            if !eligible {
1043                self.find_response_stalls.clear(*key);
1044                self.block_advert_senders.send_modify(|peers| {
1045                    peers.remove(key);
1046                });
1047            }
1048            eligible
1049        });
1050        for pending in Pin::new(&self.unready_services).iter_pin_ref() {
1051            let pending = pending.get_ref();
1052            let key = pending
1053                .key
1054                .as_ref()
1055                .expect("unready services retain their key until completion");
1056            // Canceled futures can outlive their connection and share a replacement's address.
1057            if !self
1058                .cancel_handles
1059                .get(key)
1060                .is_some_and(|cancel| cancel.is_connected_to(&pending.cancel))
1061            {
1062                continue;
1063            }
1064            let service = pending
1065                .service
1066                .as_ref()
1067                .expect("unready services retain their client until completion");
1068            if bans.is_banned(key.ip()) || service.remote_version() < minimum_version {
1069                self.find_response_stalls.clear(*key);
1070                self.block_advert_senders.send_modify(|peers| {
1071                    peers.remove(key);
1072                });
1073                if let Some(cancel) = self.cancel_handles.remove(key) {
1074                    let _ = cancel.send(CancelClientWork);
1075                }
1076            }
1077        }
1078    }
1079
1080    /// Takes a ready service by key.
1081    fn take_ready_service(&mut self, key: &D::Key) -> Option<D::Service> {
1082        if let Some(svc) = self.ready_services.remove(key) {
1083            assert!(
1084                !self.cancel_handles.contains_key(key),
1085                "cancel handles are only used for unready service work"
1086            );
1087
1088            Some(svc)
1089        } else {
1090            None
1091        }
1092    }
1093
1094    /// Whether an event belongs to the currently connected incarnation of an address.
1095    fn is_current_connection(&self, addr: PeerSocketAddr, info: &Arc<ConnectionInfo>) -> bool {
1096        self.find_peer_queue
1097            .iter()
1098            .any(|(key, current)| *key == addr && Arc::ptr_eq(current, info))
1099    }
1100
1101    /// Drains pending stall/clear events from tracked routing futures and
1102    /// disconnects peers that have exceeded the stall threshold. The peer's
1103    /// TCP connection is closed when its service is dropped; address book and
1104    /// ban list are untouched, so the peer is free to reconnect.
1105    fn drain_stall_events(&mut self, cx: &mut Context<'_>) {
1106        while let Poll::Ready(Some((addr, connection_info, outcome))) =
1107            self.stall_event_rx.poll_recv(cx)
1108        {
1109            // A delayed response from an old connection must not affect its replacement.
1110            if !self.is_current_connection(addr, &connection_info) {
1111                continue;
1112            }
1113            match outcome {
1114                StallOutcome::Stall => {
1115                    if self.find_response_stalls.record_stall(addr) {
1116                        info!(
1117                            ?addr,
1118                            "dropping stalled peer: exceeded FindBlocks/FindHeaders stall threshold",
1119                        );
1120                        self.remove(&addr);
1121                    }
1122                }
1123                StallOutcome::Clear => self.find_response_stalls.clear(addr),
1124            }
1125        }
1126    }
1127
1128    /// Records block requests that peers failed to answer or answered with `notfound`, and blocks
1129    /// that peers returned after they were chosen for an advertisement or in a repeat request, in
1130    /// the inventory registry.
1131    ///
1132    /// Peers declare their own services, and request timeouts don't mark inventory as missing. So
1133    /// otherwise a peer that falsely claims to serve blocks, and withholds them, could get every
1134    /// retry for a block.
1135    ///
1136    /// # Security
1137    ///
1138    /// A response future sends its outcome before it returns the block to its caller, and
1139    /// `poll_ready()` calls this before a request is routed. So if a caller rejects a block and
1140    /// asks for it again, that request is always routed after the block is recorded as served.
1141    /// A retry after a `notfound` is likewise routed after the refusal is recorded.
1142    fn drain_inv_failures(&mut self, cx: &mut Context<'_>) {
1143        while let Poll::Ready(Some((peer, connection_info, hash, outcome))) =
1144            self.inv_failure_rx.poll_recv(cx)
1145        {
1146            match outcome {
1147                InvOutcome::Failed => {
1148                    // Security: this record is about the block, so keep it even if the peer
1149                    // was disconnected. Otherwise, peers that advertise a block and disconnect
1150                    // when they are asked for it would keep their routing preference.
1151                    self.inventory_registry.register_unanswered(hash);
1152                    if self.is_current_connection(peer, &connection_info) {
1153                        self.inventory_registry.register_failed(hash, peer);
1154                    }
1155                }
1156                // Like the inventory collector's markers, this one is about the peer's address,
1157                // not its connection, so reconnecting doesn't clear it.
1158                //
1159                // Security: a `notfound` also leaves the request unanswered. Otherwise, peers
1160                // that advertise a block and refuse it would keep their routing preference.
1161                InvOutcome::Refused => {
1162                    self.inventory_registry.register_unanswered(hash);
1163                    self.inventory_registry.register_refused(hash, peer);
1164                }
1165                // The record is about the block, so keep it even if the peer was disconnected,
1166                // for example because the caller rejected the block and got the peer banned.
1167                InvOutcome::Served => {
1168                    self.inventory_registry.register_served(hash, peer);
1169                }
1170            }
1171        }
1172    }
1173
1174    /// Remove the service corresponding to `key` from the peer set.
1175    ///
1176    /// Drops the service, cancelling any pending request or response to that peer.
1177    /// If the peer does not exist, does nothing.
1178    fn remove(&mut self, key: &D::Key) {
1179        self.find_response_stalls.clear(*key);
1180        self.find_peer_queue.retain(|(addr, _)| addr != key);
1181        self.zcashd_compat_peer_keys.remove(key);
1182        self.serving_peer_keys.remove(key);
1183        self.block_advert_senders.send_modify(|peers| {
1184            peers.remove(key);
1185        });
1186        if let Some((_, remaining_sidecars)) = self.queued_sidecar_broadcast.as_mut() {
1187            remaining_sidecars.remove(key);
1188            if remaining_sidecars.is_empty() {
1189                self.queued_sidecar_broadcast = None;
1190            }
1191        }
1192
1193        if let Some(ready_service) = self.take_ready_service(key) {
1194            // A ready service has no work to cancel, so just drop it.
1195            std::mem::drop(ready_service);
1196        } else if let Some(handle) = self.cancel_handles.remove(key) {
1197            // Cancel the work, implicitly dropping the cancel handle.
1198            // The service future returns a `Canceled` error,
1199            // making `poll_unready` drop the service.
1200            let _ = handle.send(CancelClientWork);
1201        }
1202    }
1203
1204    /// Adds a ready service to the ready list if it's for a peer with a supported version.
1205    /// If `was_unready` is true, also removes the peer's cancel handle.
1206    ///
1207    /// If the service is for a connection to an outdated peer, the service is dropped.
1208    fn push_ready(&mut self, was_unready: bool, key: D::Key, svc: D::Service) {
1209        let cancel = self.cancel_handles.remove(&key);
1210        assert_eq!(
1211            cancel.is_some(),
1212            was_unready,
1213            "missing or unexpected cancel handle"
1214        );
1215
1216        if svc.remote_version() >= self.minimum_peer_version.current() {
1217            self.ready_services.insert(key, svc);
1218        } else {
1219            self.block_advert_senders.send_modify(|peers| {
1220                peers.remove(&key);
1221            });
1222            std::mem::drop(svc);
1223        }
1224    }
1225
1226    /// Adds a busy service to the unready list if it's for a peer with a supported version,
1227    /// and adds a cancel handle for the service's current request.
1228    ///
1229    /// If the service is for a connection to an outdated peer, the request is cancelled and the
1230    /// service is dropped.
1231    fn push_unready(&mut self, key: D::Key, svc: D::Service) {
1232        let peer_version = svc.remote_version();
1233        let (tx, rx) = oneshot::channel();
1234
1235        self.unready_services.push(UnreadyService {
1236            key: Some(key),
1237            service: Some(svc),
1238            cancel: rx,
1239            readiness_timeout: tokio::time::sleep(crate::constants::REQUEST_TIMEOUT),
1240            _req: PhantomData,
1241        });
1242
1243        if peer_version >= self.minimum_peer_version.current() {
1244            self.cancel_handles.insert(key, tx);
1245        } else {
1246            self.find_response_stalls.clear(key);
1247            // Reject delayed response events before the next peer-set poll.
1248            self.find_peer_queue.retain(|(addr, _)| *addr != key);
1249            self.block_advert_senders.send_modify(|peers| {
1250                peers.remove(&key);
1251            });
1252            // Cancel any request made to the service because it is using an outdated protocol
1253            // version.
1254            let _ = tx.send(CancelClientWork);
1255        }
1256    }
1257
1258    /// Performs P2C on `self.ready_services` to randomly select a less-loaded ready service.
1259    fn select_ready_p2c_peer(&self) -> Option<D::Key> {
1260        self.select_p2c_peer_from_list(&self.ready_services.keys().copied().collect())
1261    }
1262
1263    /// Rotates find requests across ready connections, restricting them to serving peers until
1264    /// the queued wait expires, unless no serving peers are connected.
1265    fn select_ready_find_peer(&mut self, allow_non_serving: bool) -> Option<D::Key> {
1266        if self.ready_services.is_empty() {
1267            return None;
1268        }
1269
1270        let serving_only = !allow_non_serving && !self.serving_peer_keys.is_empty();
1271        let (index, (key, _)) = self
1272            .find_peer_queue
1273            .iter()
1274            .enumerate()
1275            .find(|(_, (key, _))| {
1276                self.ready_services.contains_key(key)
1277                    && (!serving_only || self.serving_peer_keys.contains(key))
1278            })?;
1279        let key = *key;
1280        self.find_peer_queue.rotate_left(index + 1);
1281        Some(key)
1282    }
1283
1284    /// Performs P2C on `ready_service_list` to randomly select a less-loaded ready service.
1285    #[allow(clippy::unwrap_in_result)]
1286    fn select_p2c_peer_from_list(&self, ready_service_list: &HashSet<D::Key>) -> Option<D::Key> {
1287        match ready_service_list.len() {
1288            0 => None,
1289            1 => Some(
1290                *ready_service_list
1291                    .iter()
1292                    .next()
1293                    .expect("just checked there is one service"),
1294            ),
1295            len => {
1296                // Choose 2 random peers, then return the least loaded of those 2 peers.
1297                let (a, b) = {
1298                    let idxs = rand::seq::index::sample(&mut rand::rng(), len, 2);
1299                    let a = idxs.index(0);
1300                    let b = idxs.index(1);
1301
1302                    let a = *ready_service_list
1303                        .iter()
1304                        .nth(a)
1305                        .expect("sample returns valid indexes");
1306                    let b = *ready_service_list
1307                        .iter()
1308                        .nth(b)
1309                        .expect("sample returns valid indexes");
1310
1311                    (a, b)
1312                };
1313
1314                let a_load = self.query_load(&a).expect("supplied services are ready");
1315                let b_load = self.query_load(&b).expect("supplied services are ready");
1316
1317                let selected = if a_load <= b_load { a } else { b };
1318
1319                trace!(
1320                    a.key = ?a,
1321                    a.load = ?a_load,
1322                    b.key = ?b,
1323                    b.load = ?b_load,
1324                    selected = ?selected,
1325                    ?len,
1326                    "selected service by p2c"
1327                );
1328
1329                Some(selected)
1330            }
1331        }
1332    }
1333
1334    /// Randomly chooses `max_peers` ready services, ignoring service load.
1335    ///
1336    /// The chosen peers are unique, but their order is not fully random.
1337    fn select_random_ready_peers(&self, max_peers: usize) -> Vec<D::Key> {
1338        use rand::seq::IteratorRandom;
1339
1340        self.ready_services
1341            .keys()
1342            .copied()
1343            .sample(&mut rand::rng(), max_peers)
1344    }
1345
1346    /// Randomly chooses ready peers for a sidecar broadcast, always including
1347    /// configured zcashd compat sidecar peers.
1348    fn select_sidecar_broadcast_peers(&self, max_peers: usize) -> Vec<D::Key> {
1349        use rand::seq::IteratorRandom;
1350
1351        let mut selected_peers: Vec<_> = self
1352            .zcashd_compat_peer_keys
1353            .iter()
1354            .filter(|key| self.ready_services.contains_key(*key))
1355            .copied()
1356            .collect();
1357
1358        selected_peers.extend(
1359            self.ready_services
1360                .keys()
1361                .filter(|key| !self.zcashd_compat_peer_keys.contains(key))
1362                .copied()
1363                .sample(&mut rand::rng(), max_peers),
1364        );
1365
1366        selected_peers
1367    }
1368
1369    /// Returns true if `service` is a configured zcashd sidecar peer.
1370    ///
1371    /// Only used to classify peers once, when they are inserted into the peer
1372    /// set; every later check uses the O(1) [`Self::zcashd_compat_peer_keys`]
1373    /// set instead.
1374    fn is_zcashd_compat_peer(&self, service: &D::Service) -> bool {
1375        self.block_gossip_peer_ips
1376            .iter()
1377            .any(|ip| service.is_inbound_direct_from_ip(ip))
1378    }
1379
1380    /// Forgets sidecar keys whose peer has disconnected.
1381    ///
1382    /// Sidecars reconnect from new ephemeral ports, and services are dropped on many
1383    /// paths (bans, version downgrades, cancelled requests), so this runs every
1384    /// poll cycle to keep the set from accumulating stale keys — otherwise a
1385    /// reused port could inherit a stale sidecar's stall-tracking exemption.
1386    fn prune_disconnected_sidecar_keys(&mut self) {
1387        Self::retain_connected_keys(
1388            &mut self.zcashd_compat_peer_keys,
1389            &self.ready_services,
1390            &self.cancel_handles,
1391        );
1392    }
1393
1394    /// Removes the keys of disconnected peers from `keys`.
1395    ///
1396    /// A connected peer is either ready or unready with a registered cancel
1397    /// handle; a key in neither map belongs to a dropped connection.
1398    fn retain_connected_keys(
1399        keys: &mut HashSet<D::Key>,
1400        ready_services: &HashMap<D::Key, D::Service>,
1401        cancel_handles: &HashMap<D::Key, oneshot::Sender<CancelClientWork>>,
1402    ) {
1403        if keys.is_empty() {
1404            return;
1405        }
1406
1407        keys.retain(|key| ready_services.contains_key(key) || cancel_handles.contains_key(key));
1408    }
1409
1410    /// Accesses a ready endpoint by `key` and returns its current load.
1411    ///
1412    /// Returns `None` if the service is not in the ready service list.
1413    fn query_load(&self, key: &D::Key) -> Option<<D::Service as Load>::Metric> {
1414        let svc = self.ready_services.get(key);
1415        svc.map(|svc| svc.load())
1416    }
1417
1418    /// Routes find requests fairly and other requests using P2C load-balancing.
1419    fn route_request(&mut self, req: Request) -> <Self as tower::Service<Request>>::Future {
1420        let is_find_request = matches!(
1421            &req,
1422            Request::FindBlocks { .. } | Request::FindHeaders { .. }
1423        );
1424        let peer_key = if is_find_request {
1425            // Fast empty responses must not gain a latency-based routing advantage.
1426            self.select_ready_find_peer(false)
1427        } else {
1428            self.select_ready_p2c_peer()
1429        };
1430
1431        if let Some(peer_key) = peer_key {
1432            if is_find_request && !self.serving_peer_keys.contains(&peer_key) {
1433                metrics::counter!(
1434                    "zcash.net.peer_set.find_fallback",
1435                    "reason" => "no_serving_peer",
1436                    "network" => network_kind_label(&self.network)
1437                )
1438                .increment(1);
1439            }
1440            return self.call_ready_peer(peer_key, req);
1441        }
1442
1443        if is_find_request {
1444            self.queued_find_requests
1445                .retain(|queued| !queued.response_sender.is_canceled());
1446            if self.queued_find_requests.len() < MAX_QUEUED_FIND_REQUESTS {
1447                return self.queue_find_request(req);
1448            }
1449            if let Some(peer_key) = self.select_ready_find_peer(true) {
1450                metrics::counter!(
1451                    "zcash.net.peer_set.find_fallback",
1452                    "reason" => "queue_full",
1453                    "network" => network_kind_label(&self.network)
1454                )
1455                .increment(1);
1456                return self.call_ready_peer(peer_key, req);
1457            }
1458        }
1459
1460        async move {
1461            // Let other tasks run, so a retry request might get different ready peers.
1462            tokio::task::yield_now().await;
1463            Err(SharedPeerError::from(PeerError::NoReadyPeers))
1464        }
1465        .map_err(Into::into)
1466        .boxed()
1467    }
1468
1469    /// Tries to route a request to a ready peer that advertised that inventory,
1470    /// falling back to a ready peer that isn't missing the inventory.
1471    ///
1472    /// If no ready peer can be used, but a busy peer might have the block, queues the request
1473    /// until one of those busy peers becomes ready. See [`Self::route_queued_inv_requests`].
1474    ///
1475    /// Otherwise, returns a synthetic [`NotFoundRegistry`](PeerError::NotFoundRegistry) error.
1476    ///
1477    /// See [`Self::select_inv_route`] for details.
1478    fn route_inv(
1479        &mut self,
1480        req: Request,
1481        hash: InventoryHash,
1482    ) -> <Self as tower::Service<Request>>::Future {
1483        match self.select_inv_route(&req, hash) {
1484            InvRoute::Peer { peer, advertised } => self.call_inv_peer(peer, req, hash, advertised),
1485            InvRoute::Wait => self.queue_inv_request(req, hash),
1486            InvRoute::Refuse => {
1487                tracing::debug!(
1488                    ?hash,
1489                    "no peer that might have the inventory can take the request, failing request"
1490                );
1491                metrics::counter!(
1492                    "zcash.net.peer_set.inventory_refusal",
1493                    "kind" => "instant",
1494                    "network" => network_kind_label(&self.network)
1495                )
1496                .increment(1);
1497
1498                async move {
1499                    // Let other tasks run, so a retry request might get different ready peers.
1500                    tokio::task::yield_now().await;
1501
1502                    Err(not_found_registry_error(hash))
1503                }
1504                .boxed()
1505            }
1506        }
1507    }
1508
1509    /// Returns where to route an inventory request for `hash`.
1510    ///
1511    /// Prefers a ready peer that advertised the inventory, then a ready peer that isn't missing it.
1512    /// For blocks, that fallback prefers peers that [serve full history](crate::types::PeerServices::serves_full_history).
1513    /// Non-serving peers usually answer `notfound` for historic blocks, so they only get a block
1514    /// if no connected serving peer might have it, or if some peer advertised it (so it is recent).
1515    ///
1516    /// Only block requests wait for busy peers: transaction downloads don't retry, so waiting
1517    /// would only slow them down.
1518    ///
1519    /// Peers that recently failed to return a block are skipped for that block, unless no other
1520    /// peer might have it.
1521    ///
1522    /// A block that a peer already failed to return or refused, or returned because it was
1523    /// advertised, is being asked for again. The peers that returned it are skipped like failed peers. The other peers that
1524    /// advertised it take turns with the peers that didn't, starting with the peers that didn't.
1525    /// If the group whose turn it is has no ready peer, the other group gets the request, and
1526    /// the next turn goes back to the group that missed out.
1527    ///
1528    /// The first request for a block goes to the peer that announced it, if the request carries
1529    /// that peer, it is ready, and its connection negotiated compact block relay.
1530    ///
1531    /// Uses P2C to choose the least loaded peer in each list.
1532    fn select_inv_route(&self, request: &Request, hash: InventoryHash) -> InvRoute<D::Key> {
1533        // # Security
1534        //
1535        // Peers that recently failed to return this block lose any preference for it, and are only
1536        // asked again as a last resort. Otherwise, a peer that falsely claims to serve blocks and
1537        // withholds them could get every retry.
1538        let failed_peer_list: HashSet<PeerSocketAddr> = self
1539            .inventory_registry
1540            .failed_peers(hash)
1541            .copied()
1542            .collect();
1543
1544        // # Security
1545        //
1546        // A block hash only commits to the header, so a peer can advertise a block, and then
1547        // serve its header with other transactions. The caller rejects that block and asks for
1548        // it again (GHSA-g9rc-89v4-hhvf). So once an advertised block was returned, the peers
1549        // that returned it are only asked for it as a last resort, like peers that failed to
1550        // return it.
1551        let served_peer_list: HashSet<PeerSocketAddr> = self
1552            .inventory_registry
1553            .served_peers(hash)
1554            .copied()
1555            .collect();
1556        //
1557        // Advertising a block is also free, so many addresses can advertise a block, and never
1558        // answer requests for it or answer `notfound`. Each address is skipped afterwards, but
1559        // the others would still get every retry (GHSA-g9wm-xjq3-x3c2). So a request is also a
1560        // repeat once any peer failed to return the block, or refused it.
1561        let is_repeat = self.inventory_registry.is_repeat_request(hash);
1562
1563        // # Security
1564        //
1565        // The other advertisers can't be told apart: a few addresses of the same peer could
1566        // advertise the block to take every retry in turn, but near the tip most advertisers are
1567        // honest, and the peers that didn't advertise the block might not have it, or might not
1568        // answer. So in repeat requests, the peers that didn't advertise the block and the other
1569        // advertisers take turns to be asked first. The caller only retries a few times, so the
1570        // first turn goes to the peers that didn't advertise the block: the first request went
1571        // to an advertiser.
1572        //
1573        // Each group's turn depends on how many repeat requests were sent to it. So concurrent
1574        // repeat requests go to both groups, and a group that had no ready peer on its turn gets
1575        // the next one.
1576        let ask_other_peers_first = is_repeat && {
1577            let repeats = self.inventory_registry.repeat_requests(hash);
1578            repeats.other_peers <= repeats.advertisers
1579        };
1580
1581        let has_failed = |addr: &PeerSocketAddr| {
1582            failed_peer_list.contains(addr) || served_peer_list.contains(addr)
1583        };
1584        let advertiser = match request {
1585            Request::BlockDownload { advertiser, .. } => advertiser.filter(|addr| {
1586                // Registry advertisements already exclude missing peers. Apply the same rule
1587                // to carried provenance without allocating a fallback set on the fast path.
1588                !self
1589                    .inventory_registry
1590                    .missing_peers(hash)
1591                    .any(|missing| missing == addr)
1592            }),
1593            _ => None,
1594        };
1595
1596        // # Correctness
1597        //
1598        // A peer that negotiated compact block relay announces blocks in compact form, and the
1599        // carried advertiser is the connection whose announcement the downloader admitted. Only
1600        // that connection holds the announcement, so only it can rebuild the block from the
1601        // mempool, and any other peer is asked for the full block. So the first request for the
1602        // block goes to the advertiser, if it is ready.
1603        //
1604        // # Security
1605        //
1606        // The advertiser gets no preference in a repeat request, or after it failed to return
1607        // the block, like the other advertisers. An advertiser that didn't negotiate compact
1608        // block relay gets no preference either: it can only send the full block, so the choice
1609        // among the block's advertisers stays random, and one peer can't take every first
1610        // request by announcing each block first.
1611        if !is_repeat {
1612            if let Some(peer) = advertiser.filter(|addr| {
1613                !has_failed(addr)
1614                    && self
1615                        .ready_services
1616                        .get(addr)
1617                        .is_some_and(|peer| peer.connection_info().early_block_relay)
1618            }) {
1619                tracing::trace!(?hash, ?peer, "routing to the peer that announced the block");
1620                return InvRoute::Peer {
1621                    peer,
1622                    advertised: true,
1623                };
1624            }
1625        }
1626
1627        let advertising_peers: Vec<PeerSocketAddr> = self
1628            .inventory_registry
1629            .advertising_peers(hash)
1630            .copied()
1631            .chain(advertiser)
1632            .collect();
1633        let advertising_peer_list = advertising_peers
1634            .iter()
1635            .filter(|addr| self.ready_services.contains_key(addr) && !has_failed(addr))
1636            .copied()
1637            .collect();
1638
1639        let missing_peer_list: HashSet<PeerSocketAddr> = self
1640            .inventory_registry
1641            .missing_peers(hash)
1642            .copied()
1643            .collect();
1644
1645        // Only block routing depends on peer services: non-serving peers can still serve
1646        // mempool transactions.
1647        let is_block = matches!(hash, InventoryHash::Block(_));
1648        let ready_peers_with_services = |serving: bool| -> HashSet<PeerSocketAddr> {
1649            self.ready_services
1650                .keys()
1651                .filter(|addr| {
1652                    !missing_peer_list.contains(addr)
1653                        && !has_failed(addr)
1654                        && (!is_block || self.serving_peer_keys.contains(addr) == serving)
1655                })
1656                .copied()
1657                .collect()
1658        };
1659
1660        if ask_other_peers_first {
1661            let other_peer_list = ready_peers_with_services(true)
1662                .into_iter()
1663                .filter(|addr| !advertising_peers.contains(addr))
1664                .collect();
1665
1666            // Security: choose a random, less-loaded peer, like the other lists.
1667            if let Some(peer) = self.select_p2c_peer_from_list(&other_peer_list) {
1668                tracing::trace!(
1669                    ?hash,
1670                    ?peer,
1671                    "routing a repeat request to a peer that didn't advertise inventory"
1672                );
1673                return InvRoute::Peer {
1674                    peer,
1675                    advertised: false,
1676                };
1677            }
1678        }
1679
1680        // # Security
1681        //
1682        // Choose a random, less-loaded peer with the inventory.
1683        //
1684        // If we chose the first peer in HashMap order,
1685        // peers would be able to influence our choice by switching addresses.
1686        // But we need the choice to be random,
1687        // so that a peer can't provide all our inventory responses.
1688        if let Some(peer) = self.select_p2c_peer_from_list(&advertising_peer_list) {
1689            tracing::trace!(?hash, ?peer, "routing to a peer which advertised inventory");
1690            return InvRoute::Peer {
1691                peer,
1692                advertised: true,
1693            };
1694        }
1695
1696        let preferred_peer_list = ready_peers_with_services(true);
1697
1698        // Security: choose a random, less-loaded peer that might have the inventory.
1699        if let Some(peer) = self.select_p2c_peer_from_list(&preferred_peer_list) {
1700            tracing::trace!(?hash, ?peer, "routing to a peer that might have inventory");
1701            return InvRoute::Peer {
1702                peer,
1703                advertised: false,
1704            };
1705        }
1706
1707        if !is_block {
1708            return InvRoute::Refuse;
1709        }
1710
1711        // Peers only advertise recent blocks, which non-serving peers can usually serve. So any
1712        // busy peer might have an advertised block, but only busy serving peers might have a
1713        // historic block.
1714        //
1715        // Downloaders carry their known advertiser separately from this lossy registry.
1716        //
1717        // A disconnected or failed advertiser must not enable speculative non-serving fallback.
1718        let is_advertised = advertising_peers
1719            .iter()
1720            .any(|addr| self.has_peer_with_addr(*addr) && !has_failed(addr));
1721        let busy_peer_might_have = |failed: bool| {
1722            self.cancel_handles.keys().any(|key| {
1723                !missing_peer_list.contains(key)
1724                    && has_failed(key) == failed
1725                    && (failed || is_advertised || self.serving_peer_keys.contains(key))
1726            })
1727        };
1728        let other_busy_peer_might_have = busy_peer_might_have(false);
1729
1730        // Waiting for a busy serving peer is better than asking a non-serving peer, which would
1731        // most likely answer `notfound` for a historic block, and get marked as missing it.
1732        if is_advertised || !other_busy_peer_might_have {
1733            if let Some(peer) = self.select_p2c_peer_from_list(&ready_peers_with_services(false)) {
1734                tracing::trace!(?hash, ?peer, "routing to a non-serving peer");
1735                return InvRoute::Peer {
1736                    peer,
1737                    advertised: false,
1738                };
1739            }
1740        }
1741
1742        if other_busy_peer_might_have {
1743            return InvRoute::Wait;
1744        }
1745
1746        // As a last resort, ask a peer that failed to return this block again, or wait for it.
1747        let failed_ready_peer_list = self
1748            .ready_services
1749            .keys()
1750            .filter(|addr| has_failed(addr) && !missing_peer_list.contains(addr))
1751            .copied()
1752            .collect();
1753        if let Some(peer) = self.select_p2c_peer_from_list(&failed_ready_peer_list) {
1754            tracing::trace!(
1755                ?hash,
1756                ?peer,
1757                "routing to a peer that failed to return the block"
1758            );
1759            return InvRoute::Peer {
1760                peer,
1761                advertised: false,
1762            };
1763        }
1764
1765        if busy_peer_might_have(true) {
1766            InvRoute::Wait
1767        } else {
1768            InvRoute::Refuse
1769        }
1770    }
1771
1772    /// Sends the inventory request `req` for `hash` to the ready peer `key`, and returns its
1773    /// response future.
1774    ///
1775    /// If a block request fails, reports the failure or the peer's `notfound` to the peer set. If
1776    /// `advertised` is true, the peer was chosen because it advertised the block, so a returned
1777    /// block is reported too.
1778    /// A repeat request is counted when it is sent, see [`Self::select_inv_route()`].
1779    fn call_inv_peer(
1780        &mut self,
1781        key: D::Key,
1782        req: Request,
1783        hash: InventoryHash,
1784        advertised: bool,
1785    ) -> <Self as tower::Service<Request>>::Future {
1786        // Transaction requests don't wait for busy peers, so there is no preference to lose.
1787        if !matches!(hash, InventoryHash::Block(_)) {
1788            return self.call_ready_peer(key, req);
1789        }
1790
1791        let connection_info = self
1792            .ready_services
1793            .get(&key)
1794            .expect("inventory routing selected a ready connection")
1795            .connection_info()
1796            .clone();
1797        let is_repeat = self.inventory_registry.is_repeat_request(hash);
1798        if is_repeat {
1799            self.inventory_registry
1800                .register_repeat_request(hash, advertised);
1801        }
1802        let fut = self.call_ready_peer(key, req);
1803
1804        let failure_tx = self.inv_failure_tx.clone();
1805        async move {
1806            let result = fut.await;
1807            let outcome = match &result {
1808                Err(error) => {
1809                    let missing = error
1810                        .downcast_ref::<SharedPeerError>()
1811                        .is_some_and(|error| error.inner_debug().contains("NotFoundResponse"));
1812                    // Only a completed peer error, including its response timeout, is failure
1813                    // evidence. Dropping a caller, losing hedge or sync reset remains neutral.
1814                    //
1815                    // # Security
1816                    //
1817                    // A `notfound` isn't a failure, but the peer must not get the retry. The
1818                    // inventory collector can't be relied on to record it: it drops hashes after
1819                    // the first `MAX_INV_PER_MAP`, and peers can evict its records.
1820                    Some(if missing {
1821                        InvOutcome::Refused
1822                    } else {
1823                        InvOutcome::Failed
1824                    })
1825                }
1826                Ok(Response::Blocks(blocks) | Response::EarlyBlocks(blocks))
1827                    if (advertised || is_repeat)
1828                        && blocks.iter().any(|block| block.available().is_some()) =>
1829                {
1830                    Some(InvOutcome::Served)
1831                }
1832                Ok(_) => None,
1833            };
1834            // Security: send this before the caller gets the block, see `drain_inv_failures()`.
1835            if let Some(outcome) = outcome {
1836                let _ = failure_tx.send((key, connection_info, hash, outcome));
1837            }
1838            result
1839        }
1840        .boxed()
1841    }
1842
1843    /// Sends `req` to the ready peer `key`, and returns its response future.
1844    fn call_ready_peer(
1845        &mut self,
1846        key: D::Key,
1847        req: Request,
1848    ) -> <Self as tower::Service<Request>>::Future {
1849        let is_find_request = matches!(
1850            &req,
1851            Request::FindBlocks { .. } | Request::FindHeaders { .. }
1852        );
1853        tracing::trace!(peer_key = ?key, is_find_request, "routing request to peer");
1854        let mut svc = self
1855            .take_ready_service(&key)
1856            .expect("callers select `key` from the ready services just before calling");
1857
1858        // Configured sidecars are trusted downstream consumers, not upstream sync sources.
1859        let track_stalls = is_find_request && !self.zcashd_compat_peer_keys.contains(&key);
1860        let fut = svc.call(req);
1861        let response = if track_stalls {
1862            let connection_info = svc.connection_info().clone();
1863            let stall_tx = self.stall_event_tx.clone();
1864            async move {
1865                // Cancellation is not evidence of failure: a caught-up peer can
1866                // legitimately send no getblocks reply before the caller times out.
1867                let result = fut.await;
1868                if let Some(outcome) = classify_find_response(&result) {
1869                    let _ = stall_tx.send((key, connection_info, outcome));
1870                }
1871                result.map_err(Into::into)
1872            }
1873            .boxed()
1874        } else {
1875            fut.map_err(Into::into).boxed()
1876        };
1877        self.push_unready(key, svc);
1878        response
1879    }
1880
1881    /// Waits for a serving peer, falling back to any ready peer once the bounded wait expires.
1882    fn queue_find_request(&mut self, request: Request) -> ResponseFuture {
1883        metrics::counter!(
1884            "zcash.net.peer_set.find_queued",
1885            "network" => network_kind_label(&self.network)
1886        )
1887        .increment(1);
1888        let (response_sender, response_receiver) = oneshot::channel();
1889        self.queued_find_requests.push_back(QueuedFindRequest {
1890            request,
1891            deadline: tokio::time::Instant::now() + FIND_BUSY_SERVING_PEER_WAIT_TIMEOUT,
1892            response_sender,
1893        });
1894
1895        // Register peer, timer, and cancellation wakeups even if the response is never polled.
1896        self.maintenance_waker.notify.notify_one();
1897
1898        async move {
1899            let response_fut = response_receiver
1900                .await
1901                .map_err(|_| SharedPeerError::from(PeerError::NoReadyPeers))?;
1902            response_fut.await
1903        }
1904        .boxed()
1905    }
1906
1907    /// Routes queued discovery before inventory, and registers deadline and cancellation wakeups.
1908    ///
1909    /// This also runs with no ready peers, so abandoned requests are removed and expired
1910    /// serving-only waits stop arming the timer.
1911    fn route_queued_find_requests(&mut self, cx: &mut Context<'_>) {
1912        if self.queued_find_requests.is_empty() {
1913            return;
1914        }
1915
1916        let now = tokio::time::Instant::now();
1917        let mut next_deadline = None;
1918        for _ in 0..self.queued_find_requests.len() {
1919            let mut queued = self
1920                .queued_find_requests
1921                .pop_front()
1922                .expect("the loop visits only requests that were already queued");
1923            if queued.response_sender.poll_canceled(cx).is_ready() {
1924                continue;
1925            }
1926
1927            let expired = queued.deadline <= now;
1928            if let Some(peer) = self.select_ready_find_peer(expired) {
1929                if !self.serving_peer_keys.contains(&peer) {
1930                    let reason = if self.serving_peer_keys.is_empty() {
1931                        "no_serving_peer"
1932                    } else {
1933                        "expired"
1934                    };
1935                    metrics::counter!(
1936                        "zcash.net.peer_set.find_fallback",
1937                        "reason" => reason,
1938                        "network" => network_kind_label(&self.network)
1939                    )
1940                    .increment(1);
1941                }
1942                let response_fut = self.call_ready_peer(peer, queued.request);
1943                // A concurrent cancellation drops the response future, cancelling peer work.
1944                let _ = queued.response_sender.send(response_fut);
1945                // Register the newly unready service even if an unrelated peer remains ready.
1946                // Otherwise an idle Buffer can leave later queued downloads without a wakeup.
1947                cx.waker().wake_by_ref();
1948            } else {
1949                if !expired {
1950                    // Requests enter this FIFO with monotonically increasing deadlines.
1951                    next_deadline.get_or_insert(queued.deadline);
1952                }
1953                self.queued_find_requests.push_back(queued);
1954            }
1955        }
1956
1957        if let Some(deadline) = next_deadline {
1958            let timer = self
1959                .queued_find_request_timer
1960                .get_or_insert_with(|| Box::pin(tokio::time::sleep_until(deadline)));
1961            if timer.deadline() != deadline {
1962                timer.as_mut().reset(deadline);
1963            }
1964            if timer.as_mut().poll(cx).is_ready() {
1965                // The deadline might have passed while routing; retry with a fresh `now`.
1966                cx.waker().wake_by_ref();
1967            }
1968        } else {
1969            self.queued_find_request_timer = None;
1970        }
1971    }
1972
1973    /// Queues an inventory request until a busy peer that might have `hash` becomes ready.
1974    ///
1975    /// The returned future resolves to that peer's response, or to a synthetic
1976    /// [`NotFoundRegistry`](PeerError::NotFoundRegistry) error if the request is refused.
1977    fn queue_inv_request(
1978        &mut self,
1979        request: Request,
1980        hash: InventoryHash,
1981    ) -> <Self as tower::Service<Request>>::Future {
1982        tracing::debug!(
1983            ?hash,
1984            "no ready peer can serve the inventory, waiting for a busy peer"
1985        );
1986        let network = network_kind_label(&self.network);
1987        metrics::counter!("zcash.net.peer_set.inventory_queued", "network" => network).increment(1);
1988
1989        let deadline = (!matches!(request, Request::BlockDownload { .. }))
1990            .then(|| tokio::time::Instant::now() + INVENTORY_BUSY_PEER_WAIT_TIMEOUT);
1991
1992        let (response_sender, response_receiver) = oneshot::channel();
1993        self.queued_inv_requests.push_back(QueuedInvRequest {
1994            request,
1995            hash,
1996            deadline,
1997            span: tracing::Span::current(),
1998            response_sender,
1999        });
2000
2001        // Poll the peer set again, so peer events wake `poll_peer_set_on_notify()` while this
2002        // request is queued.
2003        self.maintenance_waker.notify.notify_one();
2004
2005        async move {
2006            let response = if let Some(deadline) = deadline {
2007                tokio::time::timeout_at(deadline, response_receiver)
2008                    .await
2009                    .ok()
2010                    .and_then(Result::ok)
2011            } else {
2012                // Capacity waiting is not a peer attempt. The downloader bounds the complete
2013                // operation, including readiness, queueing, retries, and the response.
2014                response_receiver.await.ok()
2015            };
2016            match response {
2017                Some(response_fut) => response_fut.await,
2018                None => {
2019                    tracing::debug!(
2020                        ?hash,
2021                        "no busy peer that might have the inventory became ready, failing request"
2022                    );
2023                    metrics::counter!(
2024                        "zcash.net.peer_set.inventory_refusal",
2025                        "kind" => "waited",
2026                        "network" => network
2027                    )
2028                    .increment(1);
2029
2030                    Err(not_found_registry_error(hash))
2031                }
2032            }
2033        }
2034        .boxed()
2035    }
2036
2037    /// Routes queued inventory requests to ready peers that might have their inventory, in the
2038    /// order they were queued. Refuses queued requests once no busy peer might have their
2039    /// inventory.
2040    ///
2041    /// Queued requests are only routed when the peer set is polled. While requests are queued,
2042    /// peer events notify [`poll_peer_set_on_notify`], which polls the peer set.
2043    ///
2044    /// Reconsiders candidates on every poll, including advertisements, failures and removals.
2045    ///
2046    /// While [`Self::queued_inv_requests_took_last_peer`] is set, doesn't route a queued request
2047    /// to the last ready peer, so the request the Buffer is holding can use it. Sets it when
2048    /// queued requests take the last ready peer.
2049    fn route_queued_inv_requests(&mut self, cx: &mut Context<'_>) {
2050        // Register caller cancellation too, so an expired operation releases its queue entry
2051        // even when no connection or inventory event follows it.
2052        self.queued_inv_requests.retain_mut(|queued| {
2053            queued
2054                .deadline
2055                .is_none_or(|deadline| deadline > tokio::time::Instant::now())
2056                && queued.response_sender.poll_canceled(cx).is_pending()
2057        });
2058
2059        let keep_last_peer = self.queued_inv_requests_took_last_peer;
2060        let mut routed_any = false;
2061        for _ in 0..self.queued_inv_requests.len() {
2062            let queued = self
2063                .queued_inv_requests
2064                .pop_front()
2065                .expect("each original queue entry is visited once");
2066
2067            match self.select_inv_route(&queued.request, queued.hash) {
2068                InvRoute::Peer { .. } if keep_last_peer && self.ready_services.len() == 1 => {
2069                    self.queued_inv_requests.push_back(queued);
2070                }
2071                InvRoute::Peer { peer, advertised } => {
2072                    let _span = queued.span.enter();
2073                    let response_fut =
2074                        self.call_inv_peer(peer, queued.request, queued.hash, advertised);
2075                    routed_any = true;
2076                    // If the receiver was dropped since the check above, dropping the response
2077                    // future cancels the peer's request.
2078                    let _ = queued.response_sender.send(response_fut);
2079                }
2080                InvRoute::Wait => self.queued_inv_requests.push_back(queued),
2081                // Dropping the sender refuses the request.
2082                InvRoute::Refuse => {}
2083            }
2084        }
2085
2086        // The request the Buffer is holding gets the next ready peer, see `call()`.
2087        if routed_any && self.ready_services.is_empty() {
2088            self.queued_inv_requests_took_last_peer = true;
2089        }
2090        // Poll the newly busy peer's readiness future even if another peer stays ready.
2091        if routed_any && !self.queued_inv_requests.is_empty() {
2092            self.maintenance_waker.notify.notify_one();
2093        }
2094    }
2095
2096    /// Routes the same request to up to `max_peers` ready peers, ignoring return values.
2097    ///
2098    /// `max_peers` must be at least one, and at most the number of ready peers.
2099    fn route_multiple(
2100        &mut self,
2101        req: Request,
2102        max_peers: usize,
2103    ) -> <Self as tower::Service<Request>>::Future {
2104        assert!(
2105            max_peers > 0,
2106            "requests must be routed to at least one peer"
2107        );
2108        assert!(
2109            max_peers <= self.ready_services.len(),
2110            "requests can only be routed to ready peers"
2111        );
2112
2113        let selected_peers = self.select_random_ready_peers(max_peers);
2114        self.send_multiple(req, selected_peers)
2115    }
2116
2117    /// Sends the same request to the provided ready peers, ignoring return values.
2118    ///
2119    /// # Security
2120    ///
2121    /// Callers should choose peers randomly, ignoring load.
2122    /// This avoids favouring malicious peers, because peers can influence their own load.
2123    ///
2124    /// The order of peers isn't completely random,
2125    /// but peer request order is not security-sensitive.
2126    fn send_multiple(
2127        &mut self,
2128        req: Request,
2129        peers: Vec<D::Key>,
2130    ) -> <Self as tower::Service<Request>>::Future {
2131        let mut futs = FuturesUnordered::new();
2132        for key in peers {
2133            let mut svc = self
2134                .take_ready_service(&key)
2135                .expect("selected peers are ready");
2136            futs.push(svc.call(req.clone()).map_err(|_| ()));
2137            self.push_unready(key, svc);
2138        }
2139
2140        async move {
2141            let mut succeeded = 0;
2142            let mut failed = 0;
2143            while let Some(result) = futs.next().await {
2144                match result {
2145                    Ok(_) => succeeded += 1,
2146                    Err(_) => failed += 1,
2147                }
2148            }
2149            tracing::debug!(
2150                ok.len = succeeded,
2151                err.len = failed,
2152                "sent peer request to multiple peers"
2153            );
2154            Ok(Response::Nil)
2155        }
2156        .boxed()
2157    }
2158
2159    /// Broadcasts the same request to lots of ready peers, ignoring return values.
2160    fn route_broadcast(&mut self, req: Request) -> <Self as tower::Service<Request>>::Future {
2161        // Broadcasts ignore the response
2162        self.route_multiple(req, self.number_of_peers_to_broadcast())
2163    }
2164
2165    /// Broadcasts a request to sampled peers and all configured sidecars.
2166    ///
2167    /// Used for pushed transactions. Busy sidecars receive the latest queued transaction through
2168    /// [`Self::send_queued_sidecar_broadcast`] when their ordinary service becomes ready.
2169    fn route_sidecar_broadcast(
2170        &mut self,
2171        req: Request,
2172    ) -> <Self as tower::Service<Request>>::Future {
2173        self.prune_disconnected_sidecar_keys();
2174
2175        let selected_peers =
2176            self.select_sidecar_broadcast_peers(self.number_of_peers_to_broadcast());
2177
2178        // Preserve the latest pushed transaction for busy sidecars.
2179        let busy_sidecars: HashSet<D::Key> = self
2180            .zcashd_compat_peer_keys
2181            .iter()
2182            .filter(|key| !self.ready_services.contains_key(*key))
2183            .copied()
2184            .collect();
2185        self.queued_sidecar_broadcast =
2186            (!busy_sidecars.is_empty()).then(|| (req.clone(), busy_sidecars));
2187
2188        self.send_multiple(req, selected_peers)
2189    }
2190
2191    /// Delivers the queued sidecar broadcast to any owed sidecar peers that
2192    /// have become ready. See [`Self::route_sidecar_broadcast`].
2193    fn send_queued_sidecar_broadcast(&mut self) {
2194        let Some((req, mut remaining_sidecars)) = self.queued_sidecar_broadcast.take() else {
2195            return;
2196        };
2197
2198        // Don't deliver to peers that were banned while the request was queued.
2199        let bans = self.bans_receiver.borrow().clone();
2200        remaining_sidecars.retain(|key| !bans.is_banned(key.ip()));
2201
2202        let ready_sidecars: Vec<D::Key> = remaining_sidecars
2203            .iter()
2204            .filter(|key| self.ready_services.contains_key(*key))
2205            .copied()
2206            .collect();
2207        for key in ready_sidecars {
2208            remaining_sidecars.remove(&key);
2209
2210            let mut svc = self
2211                .take_ready_service(&key)
2212                .expect("sidecars are ready because they were filtered from ready_services above");
2213            let req_fut = svc.call(req.clone());
2214            self.push_unready(key, svc);
2215
2216            // Detach the response future: the connection cancels requests whose
2217            // response channel is dropped, and there is no caller left to drive
2218            // this delivery.
2219            tokio::spawn(req_fut.map(|_| ()));
2220        }
2221
2222        // Drop sidecars that disconnected while the request was queued.
2223        Self::retain_connected_keys(
2224            &mut remaining_sidecars,
2225            &self.ready_services,
2226            &self.cancel_handles,
2227        );
2228
2229        if !remaining_sidecars.is_empty() {
2230            self.queued_sidecar_broadcast = Some((req, remaining_sidecars));
2231        }
2232    }
2233
2234    /// Given a number of ready peers calculate to how many of them Zebra will
2235    /// actually send the request to. Return this number.
2236    pub(crate) fn number_of_peers_to_broadcast(&self) -> usize {
2237        super::broadcast_peer_count(&self.network, self.ready_services.len())
2238    }
2239
2240    /// Returns the list of addresses in the peer set.
2241    fn peer_set_addresses(&self) -> Vec<PeerSocketAddr> {
2242        self.ready_services
2243            .keys()
2244            .chain(self.cancel_handles.keys())
2245            .cloned()
2246            .collect()
2247    }
2248
2249    /// Logs the peer set size, and any potential connectivity issues.
2250    fn log_peer_set_size(&mut self) {
2251        let ready_services_len = self.ready_services.len();
2252        let unready_services_len = self.unready_services.len();
2253        trace!(ready_peers = ?ready_services_len, unready_peers = ?unready_services_len);
2254
2255        let now = Instant::now();
2256
2257        // These logs are designed to be human-readable in a terminal, at the
2258        // default Zebra log level. If you need to know the peer set size for
2259        // every request, use the trace-level logs, or the metrics exporter.
2260        if let Some(last_peer_log) = self.last_peer_log {
2261            // Avoid duplicate peer set logs
2262            if now.duration_since(last_peer_log) < MIN_PEER_SET_LOG_INTERVAL {
2263                return;
2264            }
2265        } else {
2266            // Suppress initial logs until the peer set has started up.
2267            // There can be multiple initial requests before the first peer is
2268            // ready.
2269            self.last_peer_log = Some(now);
2270            return;
2271        }
2272
2273        self.last_peer_log = Some(now);
2274
2275        // Log potential duplicate connections.
2276        let peers = self.peer_set_addresses();
2277
2278        // Check for duplicates by address and port: these are unexpected and represent a bug.
2279        let duplicates: Vec<PeerSocketAddr> = peers.iter().duplicates().cloned().collect();
2280
2281        let mut peer_counts = peers.iter().counts();
2282        peer_counts.retain(|peer, _count| duplicates.contains(peer));
2283
2284        if !peer_counts.is_empty() {
2285            let duplicate_connections: usize = peer_counts.values().sum();
2286
2287            warn!(
2288                ?duplicate_connections,
2289                duplicated_peers = ?peer_counts.len(),
2290                peers = ?peers.len(),
2291                "duplicate peer connections in peer set"
2292            );
2293        }
2294
2295        // Check for duplicates by address: these can happen if there are multiple nodes
2296        // behind a NAT or on a single server.
2297        let peers: Vec<IpAddr> = peers.iter().map(|addr| addr.ip()).collect();
2298        let duplicates: Vec<IpAddr> = peers.iter().duplicates().cloned().collect();
2299
2300        let mut peer_counts = peers.iter().counts();
2301        peer_counts.retain(|peer, _count| duplicates.contains(peer));
2302
2303        if !peer_counts.is_empty() {
2304            let duplicate_connections: usize = peer_counts.values().sum();
2305
2306            info!(
2307                ?duplicate_connections,
2308                duplicated_peers = ?peer_counts.len(),
2309                peers = ?peers.len(),
2310                "duplicate IP addresses in peer set"
2311            );
2312        }
2313
2314        // Only log connectivity warnings if all our peers are busy (or there are no peers).
2315        if ready_services_len > 0 {
2316            return;
2317        }
2318
2319        let address_metrics = *self.address_metrics.borrow();
2320        if unready_services_len == 0 {
2321            warn!(
2322                ?address_metrics,
2323                "network request with no peer connections. Hint: check your network connection"
2324            );
2325        } else {
2326            info!(?address_metrics, "network request with no ready peers: finding more peers, waiting for {} peers to answer requests",
2327                  unready_services_len);
2328        }
2329    }
2330
2331    /// Updates the peer set metrics.
2332    ///
2333    /// # Panics
2334    ///
2335    /// If the peer set size exceeds the connection limit.
2336    fn update_metrics(&self) {
2337        let num_ready = self.ready_services.len();
2338        let num_unready = self.unready_services.len();
2339        let num_peers = num_ready + num_unready;
2340        let network = network_kind_label(&self.network);
2341        metrics::gauge!("pool.num_ready", "network" => network).set(num_ready as f64);
2342        metrics::gauge!("pool.num_unready", "network" => network).set(num_unready as f64);
2343        metrics::gauge!("zcash.net.peers", "network" => network).set(num_peers as f64);
2344
2345        // Security: make sure we haven't exceeded the connection limit
2346        if num_peers > self.peerset_total_connection_limit {
2347            let address_metrics = *self.address_metrics.borrow();
2348            panic!(
2349                "unexpectedly exceeded configured peer set connection limit: \n\
2350                 peers: {num_peers:?}, ready: {num_ready:?}, unready: {num_unready:?}, \n\
2351                 address_metrics: {address_metrics:?}",
2352            );
2353        }
2354    }
2355}
2356
2357/// Keep the raw buffer non-owning: the external NetworkService aborts this task and its worker.
2358async fn poll_peer_set_on_notify<S>(
2359    mut peer_set: S,
2360    wake: Arc<super::PeerSetWaker>,
2361) -> Result<(), BoxError>
2362where
2363    S: Service<Request, Response = Response, Error = BoxError> + Send + Clone + 'static,
2364    S::Future: Send + 'static,
2365{
2366    loop {
2367        wake.notify.notified().await;
2368        peer_set.ready().await?.call(Request::PollPeerSet).await?;
2369    }
2370}
2371
2372impl<D, C> PeerSet<D, C>
2373where
2374    D: Discover<Key = PeerSocketAddr, Service = LoadTrackedClient> + Unpin + Send + 'static,
2375    D::Error: Into<BoxError>,
2376    C: ChainTip + Send + 'static,
2377{
2378    /// Own the buffer worker and its idle-discovery poller in external service handles.
2379    pub(crate) fn into_buffer(
2380        self,
2381        bound: usize,
2382    ) -> (crate::NetworkService, JoinHandle<Result<(), BoxError>>) {
2383        let wake = self.maintenance_waker.clone();
2384        // Register discovery wakeups even if no ordinary request or advert is ever submitted.
2385        wake.notify.notify_one();
2386        let (peer_set, worker) = Buffer::pair(BoxService::new(self), bound);
2387        let worker = tokio::spawn(worker.in_current_span());
2388        let poll_task =
2389            tokio::spawn(poll_peer_set_on_notify(peer_set.clone(), wake).in_current_span());
2390        let network = crate::NetworkService::new(
2391            peer_set,
2392            vec![worker.abort_handle(), poll_task.abort_handle()],
2393        );
2394        (network, poll_task)
2395    }
2396}
2397
2398impl<D, C> Service<Request> for PeerSet<D, C>
2399where
2400    D: Discover<Key = PeerSocketAddr, Service = LoadTrackedClient> + Unpin,
2401    D::Error: Into<BoxError>,
2402    C: ChainTip,
2403{
2404    type Response = Response;
2405    type Error = BoxError;
2406    type Future =
2407        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
2408
2409    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
2410        // Update service and peer statuses.
2411        //
2412        // # Correctness
2413        //
2414        // All of the futures that receive a context from this method can wake the peer set buffer
2415        // task. If there are no ready peers, and no new peers, network requests will pause until:
2416        // - an unready peer becomes ready, or
2417        // - a new peer arrives.
2418        self.maintenance_waker.worker.register(cx.waker());
2419        let peer_waker = Waker::from(self.maintenance_waker.clone());
2420        let mut peer_cx = Context::from_waker(&peer_waker);
2421
2422        // Capture before observing discovery or revocation. Requests arriving during this pass
2423        // need a subsequent pass, even if the current discovery poll reports a drained stream.
2424        for completed in &mut self.maintenance_batch {
2425            if completed.is_none() {
2426                let Ok(waiter) = self.maintenance_rx.try_recv() else {
2427                    break;
2428                };
2429                *completed = Some(waiter);
2430            }
2431        }
2432
2433        // Drain stall events first, so disconnects free up slots that
2434        // `poll_discover` can fill in the same poll cycle.
2435        self.drain_stall_events(&mut peer_cx);
2436
2437        // Remove banned and outdated connections before they can block admission
2438        // of eligible replacements in the same connection-limit group.
2439        self.disconnect_from_ineligible_peers();
2440
2441        // Check for new peers, and register a task wakeup when the next new peers arrive. New peers
2442        // can be infrequent if our connection slots are full, or we're connected to all
2443        // available/useful peers.
2444        let discovery_drained = self.poll_discover(&mut peer_cx)?;
2445
2446        // These tasks don't provide new peers or newly ready peers.
2447        let _poll_pending: Poll<()> = self.poll_background_errors(&mut peer_cx)?;
2448        let _poll_pending_or_ready: Poll<()> =
2449            self.inventory_registry.poll_inventory(&mut peer_cx)?;
2450        // Register failures after rotation so they survive a full interval before aging.
2451        self.drain_inv_failures(&mut peer_cx);
2452
2453        let ready_peers = self.poll_peers(&mut peer_cx)?;
2454
2455        self.prune_disconnected_sidecar_keys();
2456        Self::retain_connected_keys(
2457            &mut self.serving_peer_keys,
2458            &self.ready_services,
2459            &self.cancel_handles,
2460        );
2461        // Discovery gets newly ready serving peers before queued block downloads can take them.
2462        // Even without ready peers, poll deadlines and cancellations to keep the queue live.
2463        self.route_queued_find_requests(&mut peer_cx);
2464
2465        // These metrics should run last, to report the most up-to-date information.
2466        self.log_peer_set_size();
2467        self.update_metrics();
2468
2469        // Waiting block requests still take priority over broadcasts.
2470        self.route_queued_inv_requests(&mut peer_cx);
2471
2472        // Acknowledge reconciled discovery and bans only when an eligible advert peer exists.
2473        if discovery_drained
2474            && (self.maintenance_batch.iter().all(Option::is_none) || {
2475                let minimum = self.minimum_peer_version.current();
2476                let bans = self.bans_receiver.borrow();
2477                self.block_advert_senders
2478                    .borrow()
2479                    .iter()
2480                    .any(|(addr, (version, _, sender))| {
2481                        *version >= minimum && !bans.is_banned(addr.ip()) && !sender.is_closed()
2482                    })
2483            })
2484        {
2485            for completed in &mut self.maintenance_batch {
2486                if let Some(completed) = completed.take() {
2487                    let _ = completed.send(());
2488                }
2489            }
2490            if !self.maintenance_rx.is_empty() {
2491                // Earlier notifications may have driven this pass while its captured batch
2492                // was still full. Schedule the remaining waiters even with an idle Buffer.
2493                peer_waker.wake_by_ref();
2494            }
2495        }
2496
2497        if ready_peers.is_pending() {
2498            // # Correctness
2499            //
2500            // If the channel is full, drop the demand signal rather than waiting. If we waited
2501            // here, the crawler could deadlock sending a request to fetch more peers, because it
2502            // also empties the channel.
2503            trace!("no ready services, sending demand signal");
2504            let _ = self.demand_signal.try_send(MorePeers);
2505
2506            // # Correctness
2507            //
2508            // The current task must be scheduled for wakeup every time we return `Poll::Pending`.
2509            //
2510            // As long as there are unready or new peers, this task will run, because:
2511            // - `poll_discover` schedules this task for wakeup when new peers arrive.
2512            // - if there are unready peers, `poll_unready` or `poll_ready_peers` schedule this
2513            //   task for wakeup when peer services become ready.
2514            //
2515            // To avoid peers blocking on a full peer status/error channel:
2516            // - `poll_background_errors` schedules this task for wakeup when the peer status
2517            //   update task exits.
2518            return Poll::Pending;
2519        }
2520
2521        self.send_queued_sidecar_broadcast();
2522
2523        if self.ready_services.is_empty() {
2524            if self.poll_peers(&mut peer_cx)?.is_pending() {
2525                return Poll::Pending;
2526            }
2527            // A peer can recover capacity while the first queued request is dispatched.
2528            // Queued discovery gets that capacity before the Buffer's held request. Queued block
2529            // requests do too, but leave it the last ready peer once they took the last one.
2530            self.route_queued_find_requests(&mut peer_cx);
2531            self.route_queued_inv_requests(&mut peer_cx);
2532            if self.ready_services.is_empty() {
2533                // Newly inserted readiness futures need a first poll even with an idle Buffer.
2534                cx.waker().wake_by_ref();
2535                Poll::Pending
2536            } else {
2537                Poll::Ready(Ok(()))
2538            }
2539        } else {
2540            Poll::Ready(Ok(()))
2541        }
2542    }
2543
2544    fn call(&mut self, req: Request) -> Self::Future {
2545        // If a peer was kept, it was kept for this request, whether or not the request uses it.
2546        let had_turn = std::mem::take(&mut self.queued_inv_requests_took_last_peer);
2547
2548        let fut = match req {
2549            Request::BlockDownload { hash, .. } => self.route_inv(req, hash.into()),
2550            // Only do inventory-aware routing on individual items.
2551            Request::BlocksByHash(ref hashes) if hashes.len() == 1 => {
2552                let hash = InventoryHash::from(*hashes.iter().next().unwrap());
2553                self.route_inv(req, hash)
2554            }
2555            Request::TransactionsById(ref hashes) if hashes.len() == 1 => {
2556                let hash = InventoryHash::from(*hashes.iter().next().unwrap());
2557                self.route_inv(req, hash)
2558            }
2559
2560            // Broadcast advertisements to lots of peers
2561            Request::AdvertiseTransactionIds(_, _) => self.route_broadcast(req),
2562            Request::AdvertiseBlockToAll(_) | Request::AdvertiseBlock(_, _) => {
2563                future::ready(Err(PeerError::AdvertRequiresDedicatedService.into())).boxed()
2564            }
2565
2566            // Broadcasts that must always reach the configured zcashd-compat sidecar peers
2567            Request::PushTransaction(_, _) => self.route_sidecar_broadcast(req),
2568
2569            // Queued requests were already routed by `poll_ready()`.
2570            Request::PollPeerSet => async { Ok(Response::Nil) }.boxed(),
2571
2572            // Find requests rotate across serving peers with a bounded wait; others use P2C.
2573            _ => self.route_request(req),
2574        };
2575
2576        // Queued requests can use a peer that was kept for this request and left unused. Peer
2577        // events don't wake them for an already ready peer, so poll the peer set again.
2578        if had_turn && !self.ready_services.is_empty() && !self.queued_inv_requests.is_empty() {
2579            self.maintenance_waker.notify.notify_one();
2580        }
2581
2582        self.update_metrics();
2583
2584        fut
2585    }
2586}