Skip to main content

zebra_network/peer/
handshake.rs

1//! Initial [`Handshake`]s with Zebra peers over a `PeerTransport`.
2
3use std::{
4    cmp::min,
5    fmt,
6    future::Future,
7    net::{Ipv4Addr, SocketAddr},
8    panic,
9    pin::Pin,
10    sync::Arc,
11    task::{Context, Poll},
12    time::Duration,
13};
14
15use chrono::{TimeZone, Utc};
16use futures::{channel::oneshot, future, pin_mut, FutureExt, SinkExt, StreamExt};
17use indexmap::IndexSet;
18use tokio::{
19    io::{AsyncRead, AsyncWrite},
20    sync::broadcast,
21    task::JoinError,
22    time::{error, timeout, Instant},
23};
24use tokio_stream::wrappers::IntervalStream;
25use tokio_util::{codec::Framed, task::AbortOnDropHandle};
26use tower::Service;
27use tracing::{span, Instrument, Level, Span};
28
29use zebra_chain::{
30    block,
31    chain_tip::{ChainTip, NoChainTip},
32    parameters::Network,
33    serialization::{DateTime32, SerializationError},
34};
35
36use crate::{
37    address_book_updater::{self, AddressBookChangeSender},
38    connection_metrics::RemoteVersionOutcomeGuard,
39    constants,
40    peer::{
41        CancelHeartbeatTask, Client, ClientRequest, Connection, ErrorSlot, HandshakeError,
42        MinimumPeerVersion, PeerError,
43    },
44    peer_set::{ConnectionTracker, InventoryChange},
45    protocol::{
46        external::{types::*, AddrInVersion, Codec, InventoryHash, Message},
47        internal::{Request, Response},
48    },
49    types::MetaAddr,
50    BoxError, Config, PeerSocketAddr, VersionMessage,
51};
52
53#[cfg(test)]
54mod tests;
55
56/// A [`Service`] that handshakes with a remote peer and constructs a
57/// client/server pair.
58///
59/// CORRECTNESS
60///
61/// To avoid hangs, each handshake (or its connector) should be:
62/// - launched in a separate task, and
63/// - wrapped in a timeout.
64pub struct Handshake<S, C = NoChainTip>
65where
66    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
67    S::Future: Send,
68    C: ChainTip + Clone + Send + 'static,
69{
70    config: Config,
71    user_agent: String,
72    our_services: PeerServices,
73    relay: bool,
74
75    inbound_service: S,
76    address_book_updater: AddressBookChangeSender,
77    inv_collector: broadcast::Sender<InventoryChange>,
78    minimum_peer_version: MinimumPeerVersion<C>,
79    bans_receiver: tokio::sync::watch::Receiver<crate::BanList>,
80    nonces: Arc<futures::lock::Mutex<IndexSet<Nonce>>>,
81
82    parent_span: Span,
83}
84
85impl<S, C> fmt::Debug for Handshake<S, C>
86where
87    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
88    S::Future: Send,
89    C: ChainTip + Clone + Send + 'static,
90{
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        // skip the channels, they don't tell us anything useful
93        f.debug_struct(std::any::type_name::<Handshake<S, C>>())
94            .field("config", &self.config)
95            .field("user_agent", &self.user_agent)
96            .field("our_services", &self.our_services)
97            .field("relay", &self.relay)
98            .field("minimum_peer_version", &self.minimum_peer_version)
99            .field("parent_span", &self.parent_span)
100            .finish()
101    }
102}
103
104impl<S, C> Clone for Handshake<S, C>
105where
106    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
107    S::Future: Send,
108    C: ChainTip + Clone + Send + 'static,
109{
110    fn clone(&self) -> Self {
111        Self {
112            config: self.config.clone(),
113            user_agent: self.user_agent.clone(),
114            our_services: self.our_services,
115            relay: self.relay,
116            inbound_service: self.inbound_service.clone(),
117            address_book_updater: self.address_book_updater.clone(),
118            inv_collector: self.inv_collector.clone(),
119            minimum_peer_version: self.minimum_peer_version.clone(),
120            bans_receiver: self.bans_receiver.clone(),
121            nonces: self.nonces.clone(),
122            parent_span: self.parent_span.clone(),
123        }
124    }
125}
126
127/// The metadata for a peer connection.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct ConnectionInfo {
130    /// The connected peer address, if known.
131    /// This address might not be valid for outbound connections.
132    ///
133    /// Peers can be connected via a transient inbound or proxy address,
134    /// which will appear as the connected address to the OS and Zebra.
135    pub connected_addr: ConnectedAddr,
136
137    /// The network protocol [`VersionMessage`] sent by the remote peer.
138    pub remote: VersionMessage,
139
140    /// The network protocol version negotiated with the remote peer.
141    ///
142    /// Derived from `remote.version` and the
143    /// [current `zebra_network` protocol version](constants::CURRENT_NETWORK_PROTOCOL_VERSION).
144    pub negotiated_version: Version,
145
146    /// Whether both ends advertised the compact block relay service bit.
147    ///
148    /// Derived from this connection's version exchange, not gossiped services or user agents.
149    /// This permits compact block relay but does not authenticate or validate any received block.
150    pub early_block_relay: bool,
151}
152
153/// The peer address that we are handshaking with.
154///
155/// Typically, we can rely on outbound addresses, but inbound addresses don't
156/// give us enough information to reconnect to that peer.
157#[derive(Copy, Clone, PartialEq, Eq)]
158pub enum ConnectedAddr {
159    /// The address we used to make a direct outbound connection.
160    ///
161    /// In an honest network, a Zcash peer is listening on this exact address
162    /// and port.
163    OutboundDirect {
164        /// The connected outbound remote address and port.
165        addr: PeerSocketAddr,
166    },
167
168    /// The address we received from the OS, when a remote peer directly
169    /// connected to our Zcash listener port.
170    ///
171    /// In an honest network, a Zcash peer might be listening on this address,
172    /// if its outbound address is the same as its listener address. But the port
173    /// is an ephemeral outbound TCP port, not a listener port.
174    InboundDirect {
175        /// The connected inbound remote address and ephemeral port.
176        ///
177        /// The IP address might be the address of a Zcash peer, but the port is an ephemeral port.
178        addr: PeerSocketAddr,
179    },
180
181    /// The proxy address we used to make an outbound connection.
182    ///
183    /// The proxy address can be used by many connections, but our own ephemeral
184    /// outbound address and port can be used as an identifier for the duration
185    /// of this connection.
186    OutboundProxy {
187        /// The remote address and port of the proxy.
188        proxy_addr: SocketAddr,
189
190        /// The local address and transient port we used to connect to the proxy.
191        transient_local_addr: SocketAddr,
192    },
193
194    /// The address we received from the OS, when a remote peer connected via an
195    /// inbound proxy.
196    ///
197    /// The proxy's ephemeral outbound address can be used as an identifier for
198    /// the duration of this connection.
199    InboundProxy {
200        /// The local address and transient port we used to connect to the proxy.
201        transient_addr: SocketAddr,
202    },
203
204    /// An isolated connection, where we deliberately don't have any connection metadata.
205    Isolated,
206    //
207    // TODO: handle Tor onion addresses
208}
209
210/// Get an unspecified IPv4 address for `network`
211pub fn get_unspecified_ipv4_addr(network: Network) -> SocketAddr {
212    (Ipv4Addr::UNSPECIFIED, network.default_port()).into()
213}
214
215use ConnectedAddr::*;
216
217impl ConnectedAddr {
218    /// Returns a new outbound directly connected addr.
219    pub fn new_outbound_direct(addr: PeerSocketAddr) -> ConnectedAddr {
220        OutboundDirect { addr }
221    }
222
223    /// Returns a new inbound directly connected addr.
224    pub fn new_inbound_direct(addr: PeerSocketAddr) -> ConnectedAddr {
225        InboundDirect { addr }
226    }
227
228    /// Returns a new outbound connected addr via `proxy`.
229    ///
230    /// `local_addr` is the ephemeral local address of the connection.
231    #[allow(unused)]
232    pub fn new_outbound_proxy(proxy: SocketAddr, local_addr: SocketAddr) -> ConnectedAddr {
233        OutboundProxy {
234            proxy_addr: proxy,
235            transient_local_addr: local_addr,
236        }
237    }
238
239    /// Returns a new inbound connected addr from `proxy`.
240    //
241    // TODO: distinguish between direct listeners and proxy listeners in the
242    //       rest of zebra-network
243    #[allow(unused)]
244    pub fn new_inbound_proxy(proxy: SocketAddr) -> ConnectedAddr {
245        InboundProxy {
246            transient_addr: proxy,
247        }
248    }
249
250    /// Returns a new isolated connected addr, with no metadata.
251    pub fn new_isolated() -> ConnectedAddr {
252        Isolated
253    }
254
255    /// Returns a `PeerSocketAddr` that can be used to track this connection in the
256    /// `AddressBook`.
257    ///
258    /// `None` for inbound connections, proxy connections, and isolated
259    /// connections.
260    ///
261    /// # Correctness
262    ///
263    /// This address can be used for reconnection attempts, or as a permanent
264    /// identifier.
265    ///
266    /// # Security
267    ///
268    /// This address must not depend on the canonical address from the `Version`
269    /// message. Otherwise, malicious peers could interfere with other peers
270    /// `AddressBook` state.
271    ///
272    /// TODO: remove the `get_` from these methods (Rust style avoids `get` prefixes)
273    pub fn get_address_book_addr(&self) -> Option<PeerSocketAddr> {
274        match self {
275            OutboundDirect { addr } | InboundDirect { addr } => Some(*addr),
276            // TODO: consider using the canonical address of the peer to track
277            //       outbound proxy connections
278            OutboundProxy { .. } | InboundProxy { .. } | Isolated => None,
279        }
280    }
281
282    /// Returns a `PeerSocketAddr` that can be used to temporarily identify a
283    /// connection.
284    ///
285    /// Isolated connections must not change Zebra's peer set or address book
286    /// state, so they do not have an identifier.
287    ///
288    /// # Correctness
289    ///
290    /// The returned address is only valid while the original connection is
291    /// open. It must not be used in the `AddressBook`, for outbound connection
292    /// attempts, or as a permanent identifier.
293    ///
294    /// # Security
295    ///
296    /// This address must not depend on the canonical address from the `Version`
297    /// message. Otherwise, malicious peers could interfere with other peers'
298    /// `PeerSet` state.
299    pub fn get_transient_addr(&self) -> Option<PeerSocketAddr> {
300        match self {
301            OutboundDirect { addr } => Some(*addr),
302            InboundDirect { addr } => Some(*addr),
303            OutboundProxy {
304                transient_local_addr,
305                ..
306            } => Some(PeerSocketAddr::from(*transient_local_addr)),
307            InboundProxy { transient_addr } => Some(PeerSocketAddr::from(*transient_addr)),
308            Isolated => None,
309        }
310    }
311
312    /// Returns the log label for this connection's address.
313    pub fn get_transient_addr_label(&self) -> String {
314        self.get_transient_addr()
315            .map_or_else(|| "isolated".to_string(), |addr| addr.to_string())
316    }
317
318    /// Returns a short label for the kind of connection.
319    pub fn get_short_kind_label(&self) -> &'static str {
320        match self {
321            OutboundDirect { .. } => "Out",
322            InboundDirect { .. } => "In",
323            OutboundProxy { .. } => "ProxOut",
324            InboundProxy { .. } => "ProxIn",
325            Isolated => "Isol",
326        }
327    }
328
329    /// Returns a list of alternate remote peer addresses, which can be used for
330    /// reconnection attempts.
331    ///
332    /// Uses the connected address, and the remote canonical address.
333    ///
334    /// Skips duplicates. If this is an outbound connection, also skips the
335    /// remote address that we're currently connected to.
336    pub fn get_alternate_addrs(
337        &self,
338        mut canonical_remote: PeerSocketAddr,
339    ) -> impl Iterator<Item = PeerSocketAddr> {
340        let addrs = match self {
341            OutboundDirect { addr } => {
342                // Fixup unspecified addresses and ports using known good data
343                if canonical_remote.ip().is_unspecified() {
344                    canonical_remote.set_ip(addr.ip());
345                }
346                if canonical_remote.port() == 0 {
347                    canonical_remote.set_port(addr.port());
348                }
349
350                // Try the canonical remote address, if it is different from the
351                // outbound address (which we already have in our address book)
352                if &canonical_remote != addr {
353                    vec![canonical_remote]
354                } else {
355                    // we didn't learn a new address from the handshake:
356                    // it's the same as the outbound address, which is already in our address book
357                    Vec::new()
358                }
359            }
360
361            InboundDirect { addr } => {
362                // Use the IP from the TCP connection, and the port the peer told us
363                let maybe_addr = SocketAddr::new(addr.ip(), canonical_remote.port()).into();
364
365                // Try both addresses, but remove one duplicate if they match
366                if canonical_remote != maybe_addr {
367                    vec![canonical_remote, maybe_addr]
368                } else {
369                    vec![canonical_remote]
370                }
371            }
372
373            // Proxy addresses can't be used for reconnection attempts, but we
374            // can try the canonical remote address
375            OutboundProxy { .. } | InboundProxy { .. } => vec![canonical_remote],
376
377            // Hide all metadata for isolated connections
378            Isolated => Vec::new(),
379        };
380
381        addrs.into_iter()
382    }
383
384    /// Returns true if the [`ConnectedAddr`] was created for an inbound connection.
385    pub fn is_inbound(&self) -> bool {
386        matches!(self, InboundDirect { .. } | InboundProxy { .. })
387    }
388}
389
390impl fmt::Debug for ConnectedAddr {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        let kind = self.get_short_kind_label();
393        let addr = self.get_transient_addr_label();
394
395        if matches!(self, Isolated) {
396            f.write_str(kind)
397        } else {
398            f.debug_tuple(kind).field(&addr).finish()
399        }
400    }
401}
402
403/// A builder for `Handshake`.
404pub struct Builder<S, C = NoChainTip>
405where
406    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
407    S::Future: Send,
408    C: ChainTip + Clone + Send + 'static,
409{
410    config: Option<Config>,
411    our_services: Option<PeerServices>,
412    user_agent: Option<String>,
413    relay: Option<bool>,
414
415    inbound_service: Option<S>,
416    address_book_updater: Option<AddressBookChangeSender>,
417    inv_collector: Option<broadcast::Sender<InventoryChange>>,
418    latest_chain_tip: C,
419    bans_receiver: Option<tokio::sync::watch::Receiver<crate::BanList>>,
420}
421
422impl<S, C> Builder<S, C>
423where
424    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
425    S::Future: Send,
426    C: ChainTip + Clone + Send + 'static,
427{
428    /// Provide a config.  Mandatory.
429    pub fn with_config(mut self, config: Config) -> Self {
430        self.config = Some(config);
431        self
432    }
433
434    /// Provide a service to handle inbound requests. Mandatory.
435    pub fn with_inbound_service(mut self, inbound_service: S) -> Self {
436        self.inbound_service = Some(inbound_service);
437        self
438    }
439
440    /// Provide a channel for registering inventory advertisements. Optional.
441    ///
442    /// This channel takes transient remote addresses, which the `PeerSet` uses
443    /// to look up peers that have specific inventory.
444    pub fn with_inventory_collector(
445        mut self,
446        inv_collector: broadcast::Sender<InventoryChange>,
447    ) -> Self {
448        self.inv_collector = Some(inv_collector);
449        self
450    }
451
452    /// Provide a hook for timestamp collection. Optional.
453    ///
454    /// This channel takes `MetaAddr`s, permanent addresses which can be used to
455    /// make outbound connections to peers.
456    pub fn with_address_book_updater(
457        mut self,
458        address_book_updater: AddressBookChangeSender,
459    ) -> Self {
460        self.address_book_updater = Some(address_book_updater);
461        self
462    }
463
464    /// Share the live ban list with connection request and advert delivery.
465    pub fn with_bans(mut self, bans: tokio::sync::watch::Receiver<crate::BanList>) -> Self {
466        self.bans_receiver = Some(bans);
467        self
468    }
469
470    /// Provide the services this node advertises to other peers.  Optional.
471    ///
472    /// If this is unset, the node will advertise itself as a client.
473    pub fn with_advertised_services(mut self, services: PeerServices) -> Self {
474        self.our_services = Some(services);
475        self
476    }
477
478    /// Provide this node's user agent.  Optional.
479    ///
480    /// This must be a valid BIP14 string.  If it is unset, the user-agent will be empty.
481    pub fn with_user_agent(mut self, user_agent: String) -> Self {
482        self.user_agent = Some(user_agent);
483        self
484    }
485
486    /// Provide a realtime endpoint to obtain the current best chain tip block height. Optional.
487    ///
488    /// If this is unset, the minimum accepted protocol version for peer connections is kept
489    /// constant over network upgrade activations.
490    ///
491    /// Use [`NoChainTip`] to explicitly provide no chain tip.
492    pub fn with_latest_chain_tip<NewC>(self, latest_chain_tip: NewC) -> Builder<S, NewC>
493    where
494        NewC: ChainTip + Clone + Send + 'static,
495    {
496        Builder {
497            latest_chain_tip,
498
499            // TODO: Until Rust RFC 2528 reaches stable, we can't do `..self`
500            config: self.config,
501            inbound_service: self.inbound_service,
502            address_book_updater: self.address_book_updater,
503            our_services: self.our_services,
504            user_agent: self.user_agent,
505            relay: self.relay,
506            inv_collector: self.inv_collector,
507            bans_receiver: self.bans_receiver,
508        }
509    }
510
511    /// Whether to request that peers relay transactions to our node.  Optional.
512    ///
513    /// If this is unset, the node will not request transactions.
514    pub fn want_transactions(mut self, relay: bool) -> Self {
515        self.relay = Some(relay);
516        self
517    }
518
519    /// Consume this builder and produce a [`Handshake`].
520    ///
521    /// Returns an error only if any mandatory field was unset.
522    pub fn finish(self) -> Result<Handshake<S, C>, &'static str> {
523        let config = self.config.ok_or("did not specify config")?;
524        let inbound_service = self
525            .inbound_service
526            .ok_or("did not specify inbound service")?;
527        let inv_collector = self.inv_collector.unwrap_or_else(|| {
528            let (tx, _) = broadcast::channel(100);
529            tx
530        });
531        let address_book_updater = self.address_book_updater.unwrap_or_else(|| {
532            // No `AddressBookUpdater` for timestamp collection was passed, so create a stub
533            // channel. Dropping the receiver means sends will fail, but we don't care.
534            let (tx, _rx) = address_book_updater::change_channel(1);
535            tx
536        });
537        let nonces = Arc::new(futures::lock::Mutex::new(IndexSet::new()));
538        let user_agent = self.user_agent.unwrap_or_default();
539        let our_services = self.our_services.unwrap_or_else(PeerServices::empty);
540        let relay = self.relay.unwrap_or(false);
541        let network = config.network.clone();
542        let minimum_peer_version = MinimumPeerVersion::new(self.latest_chain_tip, &network);
543
544        Ok(Handshake {
545            config,
546            user_agent,
547            our_services,
548            relay,
549            inbound_service,
550            address_book_updater,
551            inv_collector,
552            minimum_peer_version,
553            bans_receiver: self
554                .bans_receiver
555                .unwrap_or_else(|| tokio::sync::watch::channel(crate::BanList::default()).1),
556            nonces,
557            parent_span: Span::current(),
558        })
559    }
560}
561
562impl<S> Handshake<S, NoChainTip>
563where
564    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
565    S::Future: Send,
566{
567    /// Create a builder that configures a [`Handshake`] service.
568    pub fn builder() -> Builder<S, NoChainTip> {
569        // We don't derive `Default` because the derive inserts a `where S:
570        // Default` bound even though `Option<S>` implements `Default` even if
571        // `S` does not.
572        Builder {
573            config: None,
574            our_services: None,
575            user_agent: None,
576            relay: None,
577            inbound_service: None,
578            address_book_updater: None,
579            inv_collector: None,
580            latest_chain_tip: NoChainTip,
581            bans_receiver: None,
582        }
583    }
584}
585
586/// Negotiate the Zcash network protocol version with the remote peer at `connected_addr`, using
587/// the connection `peer_conn`.
588///
589/// We split `Handshake` into its components before calling this function, to avoid infectious
590/// `Sync` bounds on the returned future.
591///
592/// Returns the [`VersionMessage`] sent by the remote peer, and the [`Version`] negotiated with the
593/// remote peer, inside a [`ConnectionInfo`] struct.
594#[allow(clippy::too_many_arguments)]
595pub async fn negotiate_version<PeerTransport>(
596    peer_conn: &mut Framed<PeerTransport, Codec>,
597    connected_addr: &ConnectedAddr,
598    config: Config,
599    nonces: Arc<futures::lock::Mutex<IndexSet<Nonce>>>,
600    user_agent: String,
601    our_services: PeerServices,
602    relay: bool,
603    mut minimum_peer_version: MinimumPeerVersion<impl ChainTip>,
604) -> Result<Arc<ConnectionInfo>, HandshakeError>
605where
606    PeerTransport: AsyncRead + AsyncWrite + Unpin + Send + 'static,
607{
608    // Create a random nonce for this connection
609    let local_nonce = Nonce::default();
610
611    // Insert the nonce for this handshake into the shared nonce set.
612    // Each connection has its own connection state, and handshakes execute concurrently.
613    //
614    // # Correctness
615    //
616    // It is ok to wait for the lock here, because handshakes have a short
617    // timeout, and the async mutex will be released when the task times
618    // out.
619    {
620        let mut locked_nonces = nonces.lock().await;
621
622        // Duplicate nonces are very rare, because they require a 64-bit random number collision,
623        // and the nonce set is limited to a few hundred entries.
624        let is_unique_nonce = locked_nonces.insert(local_nonce);
625        if !is_unique_nonce {
626            return Err(HandshakeError::LocalDuplicateNonce);
627        }
628
629        // # Security
630        //
631        // Limit the amount of memory used for nonces.
632        // Nonces can be left in the set if the connection fails or times out between
633        // the nonce being inserted, and it being removed.
634        //
635        // Zebra has strict connection limits, so we limit the number of nonces to
636        // the configured connection limit.
637        // This is a tradeoff between:
638        // - avoiding memory denial of service attacks which make large numbers of connections,
639        //   for example, 100 failed inbound connections takes 1 second.
640        // - memory usage: 16 bytes per `Nonce`, 3.2 kB for 200 nonces
641        // - collision probability: two hundred 64-bit nonces have a very low collision probability
642        //   <https://en.wikipedia.org/wiki/Birthday_problem#Probability_of_a_shared_birthday_(collision)>
643        while locked_nonces.len() > config.peerset_total_connection_limit() {
644            locked_nonces.shift_remove_index(0);
645        }
646
647        std::mem::drop(locked_nonces);
648    }
649
650    // Don't leak our exact clock skew to our peers. On the other hand,
651    // we can't deviate too much, or zcashd will get confused.
652    // Inspection of the zcashd source code reveals that the timestamp
653    // is only ever used at the end of parsing the version message, in
654    //
655    // pfrom->nTimeOffset = timeWarning.AddTimeData(pfrom->addr, nTime, GetTime());
656    //
657    // AddTimeData is defined in src/timedata.cpp and is a no-op as long
658    // as the difference between the specified timestamp and the
659    // zcashd's local time is less than TIMEDATA_WARNING_THRESHOLD, set
660    // to 10 * 60 seconds (10 minutes).
661    //
662    // nTimeOffset is peer metadata that is never used, except for
663    // statistics.
664    //
665    // To try to stay within the range where zcashd will ignore our clock skew,
666    // truncate the timestamp to the nearest 5 minutes.
667    let now = Utc::now().timestamp();
668    let timestamp = Utc
669        .timestamp_opt(now - now.rem_euclid(5 * 60), 0)
670        .single()
671        .expect("in-range number of seconds and valid nanosecond");
672
673    // Whether this node is still syncing, used below to decide whether outbound peers must
674    // advertise `NODE_NETWORK`.
675    let is_syncing = !minimum_peer_version
676        .chain_tip()
677        .is_at_or_near_network_tip(Utc::now());
678
679    let network = config.network.clone();
680    let (their_addr, mut our_services, our_listen_addr) = match connected_addr {
681        // Version messages require an address, so we use
682        // an unspecified address for Isolated connections
683        Isolated => {
684            let unspec_ipv4 = get_unspecified_ipv4_addr(config.network);
685            (unspec_ipv4.into(), PeerServices::empty(), unspec_ipv4)
686        }
687        _ => {
688            let their_addr = connected_addr
689                .get_transient_addr()
690                .expect("non-Isolated connections have a remote addr");
691
692            // Include the configured external address in our version message, if any, otherwise, include our listen address.
693            let advertise_addr = match config.external_addr {
694                Some(external_addr) => {
695                    info!(?their_addr, ?config.listen_addr, "using external address for Version messages");
696                    external_addr
697                }
698                None => config.listen_addr,
699            };
700
701            (their_addr, our_services, advertise_addr)
702        }
703    };
704    our_services.set(
705        PeerServices::NODE_COMPACT_BLOCKS,
706        config.compact_block_relay && !matches!(connected_addr, Isolated),
707    );
708
709    let start_height = minimum_peer_version
710        .chain_tip()
711        .best_tip_height()
712        .unwrap_or(block::Height(0));
713
714    let our_version = VersionMessage {
715        version: constants::CURRENT_NETWORK_PROTOCOL_VERSION,
716        services: our_services,
717        timestamp,
718        address_recv: AddrInVersion::new(their_addr, PeerServices::NODE_NETWORK),
719        // TODO: detect external address (#1893)
720        address_from: AddrInVersion::new(our_listen_addr, our_services),
721        nonce: local_nonce,
722        user_agent: user_agent.clone(),
723        start_height,
724        relay,
725    }
726    .into();
727
728    debug!(?our_version, "sending initial version message");
729    peer_conn.send(our_version).await?;
730
731    let mut remote_msg = peer_conn
732        .next()
733        .await
734        .ok_or(HandshakeError::ConnectionClosed)??;
735
736    // Wait for next message if the one we got is not Version
737    let remote: VersionMessage = loop {
738        match remote_msg {
739            Message::Version(version_message) => {
740                debug!(?version_message, "got version message from remote peer");
741                break version_message;
742            }
743            _ => {
744                remote_msg = peer_conn
745                    .next()
746                    .await
747                    .ok_or(HandshakeError::ConnectionClosed)??;
748                debug!(?remote_msg, "ignoring non-version message from remote peer");
749            }
750        }
751    };
752
753    let remote_address_services = remote.address_from.untrusted_services();
754    let mut remote_version_outcome =
755        RemoteVersionOutcomeGuard::new(&network, connected_addr, &remote.user_agent);
756    if remote_address_services != remote.services {
757        info!(
758            ?remote.services,
759            ?remote_address_services,
760            ?remote.user_agent,
761            "peer with inconsistent version services and version address services",
762        );
763    }
764
765    // Check for nonce reuse, indicating self-connection
766    //
767    // # Correctness
768    //
769    // We must wait for the lock before we continue with the connection, to avoid
770    // self-connection. If the connection times out, the async lock will be
771    // released.
772    //
773    // # Security
774    //
775    // We don't remove the nonce here, because peers that observe our network traffic could
776    // maliciously remove nonces, and force us to make self-connections.
777    let nonce_reuse = nonces.lock().await.contains(&remote.nonce);
778    if nonce_reuse {
779        info!(?connected_addr, "rejecting self-connection attempt");
780        return Err(remote_version_outcome.record_error(HandshakeError::RemoteNonceReuse));
781    }
782
783    // # Security
784    //
785    // Reject connections to peers on old versions, because they might not know about all
786    // network upgrades and could lead to chain forks or slower block propagation.
787    let min_version = minimum_peer_version.current();
788
789    if remote.version < min_version {
790        debug!(
791            remote_ip = ?their_addr,
792            ?remote.version,
793            ?min_version,
794            ?remote.user_agent,
795            "disconnecting from peer with obsolete network protocol version",
796        );
797
798        // Count rejected handshakes by protocol version, without per-peer labels.
799        metrics::counter!(
800            "zcash.net.peers.obsolete",
801            "remote_version" => remote.version.metric_label(),
802            "min_version" => min_version.to_string(),
803        )
804        .increment(1);
805
806        // Record the remote version of the most recently rejected handshake.
807        metrics::gauge!("zcash.net.peers.version.obsolete").set(f64::from(remote.version.0));
808
809        // Disconnect if peer is using an obsolete version.
810        return Err(
811            remote_version_outcome.record_error(HandshakeError::ObsoleteVersion(remote.version))
812        );
813    }
814
815    // # Security
816    //
817    // While syncing, require `NODE_NETWORK` without `NODE_PRUNED` from outbound peers: other
818    // peers can't serve us historic blocks, but still occupy outbound slots and receive syncer block requests.
819    // When many reachable listeners are non-serving, those slots can fill up and stall a fresh
820    // sync (#11061). This mirrors Bitcoin Core, which requires block-serving peers during
821    // initial block download.
822    //
823    // At or near the network tip the requirement is dropped, because non-serving peers (like
824    // pruned nodes) can still serve recent blocks and transactions. Inbound and isolated
825    // connections are always exempt, so light clients can still connect to us.
826    if is_syncing
827        && matches!(connected_addr, OutboundDirect { .. } | OutboundProxy { .. })
828        && !remote.services.serves_full_history()
829    {
830        debug!(
831            remote_ip = ?their_addr,
832            ?remote.services,
833            ?remote.user_agent,
834            "disconnecting from non-serving peer",
835        );
836
837        // Peers choose their service bits, so the label names the required service, not the bits.
838        metrics::counter!(
839            "zcash.net.peers.missing_services",
840            "missing_service" => "NODE_NETWORK",
841        )
842        .increment(1);
843
844        // Disconnect if the outbound peer doesn't advertise the required services.
845        return Err(
846            remote_version_outcome.record_error(HandshakeError::MissingRequiredServices {
847                services: remote.services,
848            }),
849        );
850    }
851
852    let negotiated_version = min(constants::CURRENT_NETWORK_PROTOCOL_VERSION, remote.version);
853    let early_block_relay = our_services
854        .intersection(remote.services)
855        .contains(PeerServices::NODE_COMPACT_BLOCKS);
856
857    // Limit containing struct size, and avoid multiple duplicates of 300+ bytes of data.
858    let connection_info = Arc::new(ConnectionInfo {
859        connected_addr: *connected_addr,
860        remote,
861        negotiated_version,
862        early_block_relay,
863    });
864
865    debug!(
866        remote_ip = ?their_addr,
867        ?connection_info.remote.version,
868        ?negotiated_version,
869        ?min_version,
870        ?connection_info.remote.user_agent,
871        "negotiated network protocol version with peer",
872    );
873
874    // Count connected handshakes by protocol version, without per-peer labels.
875    metrics::counter!(
876        "zcash.net.peers.connected",
877        "remote_version" => connection_info.remote.version.metric_label(),
878        "negotiated_version" => negotiated_version.metric_label(),
879        "min_version" => min_version.to_string(),
880    )
881    .increment(1);
882
883    // Record the remote version of the most recently connected handshake.
884    metrics::gauge!("zcash.net.peers.version.connected")
885        .set(f64::from(connection_info.remote.version.0));
886
887    if let Err(error) = peer_conn.send(Message::Verack).await {
888        return Err(remote_version_outcome.record_error(HandshakeError::from(error)));
889    }
890
891    let mut remote_msg = match peer_conn.next().await {
892        Some(Ok(message)) => message,
893        Some(Err(error)) => {
894            return Err(remote_version_outcome.record_error(HandshakeError::from(error)));
895        }
896        None => {
897            return Err(remote_version_outcome.record_error(HandshakeError::ConnectionClosed));
898        }
899    };
900
901    // Wait for next message if the one we got is not Verack
902    loop {
903        match remote_msg {
904            Message::Verack => {
905                debug!(?remote_msg, "got verack message from remote peer");
906                break;
907            }
908            _ => {
909                remote_msg = match peer_conn.next().await {
910                    Some(Ok(message)) => message,
911                    Some(Err(error)) => {
912                        return Err(
913                            remote_version_outcome.record_error(HandshakeError::from(error))
914                        );
915                    }
916                    None => {
917                        return Err(
918                            remote_version_outcome.record_error(HandshakeError::ConnectionClosed)
919                        );
920                    }
921                };
922                debug!(?remote_msg, "ignoring non-verack message from remote peer");
923            }
924        }
925    }
926
927    remote_version_outcome.record_success();
928    Ok(connection_info)
929}
930
931/// A handshake request.
932/// Contains the information needed to handshake with the peer.
933pub struct HandshakeRequest<PeerTransport>
934where
935    PeerTransport: AsyncRead + AsyncWrite + Unpin + Send + 'static,
936{
937    /// The tokio [`TcpStream`](tokio::net::TcpStream) or Tor
938    /// `arti_client::DataStream` to the peer.
939    // Use [`arti_client::DataStream`] when #5492 is done.
940    pub data_stream: PeerTransport,
941
942    /// The address of the peer, and other related information.
943    pub connected_addr: ConnectedAddr,
944
945    /// A connection tracker that reduces the open connection count when dropped.
946    ///
947    /// Used to limit the number of open connections in Zebra.
948    pub connection_tracker: ConnectionTracker,
949}
950
951impl<S, PeerTransport, C> Service<HandshakeRequest<PeerTransport>> for Handshake<S, C>
952where
953    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + 'static,
954    S::Future: Send,
955    C: ChainTip + Clone + Send + 'static,
956    PeerTransport: AsyncRead + AsyncWrite + Unpin + Send + 'static,
957{
958    type Response = Client;
959    type Error = BoxError;
960    type Future =
961        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
962
963    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
964        Poll::Ready(Ok(()))
965    }
966
967    fn call(&mut self, req: HandshakeRequest<PeerTransport>) -> Self::Future {
968        let HandshakeRequest {
969            data_stream,
970            connected_addr,
971            mut connection_tracker,
972        } = req;
973
974        let negotiator_span = debug_span!("negotiator", peer = ?connected_addr);
975        // set the peer connection span's parent to the global span, as it
976        // should exist independently of its creation source (inbound
977        // connection, crawler, initial peer, ...)
978        let connection_span =
979            span!(parent: &self.parent_span, Level::INFO, "", peer = ?connected_addr);
980
981        // Clone these upfront, so they can be moved into the future.
982        let nonces = self.nonces.clone();
983        let inbound_service = self.inbound_service.clone();
984        let address_book_updater = self.address_book_updater.clone();
985        let inv_collector = self.inv_collector.clone();
986        let config = self.config.clone();
987        let user_agent = self.user_agent.clone();
988        let our_services = self.our_services;
989        let relay = self.relay;
990        let minimum_peer_version = self.minimum_peer_version.clone();
991        let bans_receiver = self.bans_receiver.clone();
992
993        // # Security
994        //
995        // `zebra_network::init()` implements a connection timeout on this future.
996        // Any code outside this future does not have a timeout.
997        let fut = async move {
998            debug!(
999                addr = ?connected_addr,
1000                "negotiating protocol version with remote peer"
1001            );
1002
1003            // Start timing the handshake for metrics
1004            let handshake_start = Instant::now();
1005
1006            let mut peer_conn = Framed::new(
1007                data_stream,
1008                Codec::builder().for_network(&config.network).finish(),
1009            );
1010
1011            let connection_info = match negotiate_version(
1012                &mut peer_conn,
1013                &connected_addr,
1014                config,
1015                nonces,
1016                user_agent,
1017                our_services,
1018                relay,
1019                minimum_peer_version.clone(),
1020            )
1021            .await
1022            {
1023                Ok(info) => {
1024                    // Record successful handshake duration
1025                    let duration = handshake_start.elapsed().as_secs_f64();
1026                    metrics::histogram!(
1027                        "zcash.net.peer.handshake.duration_seconds",
1028                        "result" => "success"
1029                    )
1030                    .record(duration);
1031                    info
1032                }
1033                Err(err) => {
1034                    // Record failed handshake duration and failure reason
1035                    let duration = handshake_start.elapsed().as_secs_f64();
1036                    let reason = match &err {
1037                        HandshakeError::UnexpectedMessage(_) => "unexpected_message",
1038                        HandshakeError::RemoteNonceReuse => "nonce_reuse",
1039                        HandshakeError::LocalDuplicateNonce => "duplicate_nonce",
1040                        HandshakeError::ConnectionClosed => "connection_closed",
1041                        HandshakeError::Io(_) => "io_error",
1042                        HandshakeError::Serialization(_) => "serialization",
1043                        HandshakeError::ObsoleteVersion(_) => "obsolete_version",
1044                        HandshakeError::MissingRequiredServices { .. } => {
1045                            "missing_required_services"
1046                        }
1047                        HandshakeError::Timeout => "timeout",
1048                    };
1049                    metrics::histogram!(
1050                        "zcash.net.peer.handshake.duration_seconds",
1051                        "result" => "failure"
1052                    )
1053                    .record(duration);
1054                    metrics::counter!(
1055                        "zcash.net.peer.handshake.failures.total",
1056                        "reason" => reason
1057                    )
1058                    .increment(1);
1059
1060                    // Rejected non-serving peers are reported by the crawler's `report_failed`
1061                    // without their services, so they get the standard failure backoff and can
1062                    // be dialed again once the node is near the network tip (#11061).
1063                    return Err(err);
1064                }
1065            };
1066
1067            let remote_services = connection_info.remote.services;
1068
1069            // The handshake succeeded: update the peer status from AttemptPending to Responded,
1070            // send initial connection info, and update the active connection counter.
1071            connection_tracker.mark_open();
1072            if let Some(book_addr) = connected_addr.get_address_book_addr() {
1073                // the collector doesn't depend on network activity,
1074                // so this await should not hang
1075                let _ = address_book_updater
1076                    .send(MetaAddr::new_connected(
1077                        book_addr,
1078                        &remote_services,
1079                        connected_addr.is_inbound(),
1080                        connection_info.remote.user_agent.clone(),
1081                        connection_info.negotiated_version,
1082                    ))
1083                    .await;
1084            }
1085
1086            // Reconfigure the codec to use the negotiated version.
1087            //
1088            // TODO: The tokio documentation says not to do this while any frames are still being processed.
1089            // Since we don't know that here, another way might be to release the tcp
1090            // stream from the unversioned Framed wrapper and construct a new one with a versioned codec.
1091            let bare_codec = peer_conn.codec_mut();
1092            bare_codec.reconfigure_version(connection_info.negotiated_version);
1093            bare_codec.reconfigure_full_body_len();
1094            bare_codec.reconfigure_early_block_relay(connection_info.early_block_relay);
1095            let compact_recovery = connection_info.early_block_relay.then(|| {
1096                let (sender, receiver) = tokio::sync::watch::channel(None);
1097                bare_codec.reconfigure_compact_recovery(receiver);
1098                sender
1099            });
1100
1101            debug!("constructing client, spawning server");
1102
1103            // These channels communicate between the inbound and outbound halves of the connection,
1104            // and between the different connection tasks. We create separate tasks and channels
1105            // for each new connection.
1106            let (server_tx, server_rx) = futures::channel::mpsc::channel(0);
1107            // Bound pending adverts; slow peers can catch up through later tip gossip.
1108            let (block_advert_tx, block_advert_rx) = tokio::sync::mpsc::channel(4);
1109            let (shutdown_tx, shutdown_rx) = oneshot::channel();
1110            let error_slot = ErrorSlot::default();
1111
1112            let (peer_tx, peer_rx) = peer_conn.split();
1113
1114            // Instrument the peer's rx and tx streams.
1115
1116            let inner_conn_span = connection_span.clone();
1117            let peer_tx = peer_tx.with(move |msg: Message| {
1118                let span = debug_span!(parent: inner_conn_span.clone(), "outbound_metric");
1119                // Add a metric for outbound messages.
1120                metrics::counter!(
1121                    "zcash.net.out.messages",
1122                    "command" => msg.command(),
1123                )
1124                .increment(1);
1125                // We need to use future::ready rather than an async block here,
1126                // because we need the sink to be Unpin, and the With<Fut, ...>
1127                // returned by .with is Unpin only if Fut is Unpin, and the
1128                // futures generated by async blocks are not Unpin.
1129                future::ready(Ok(msg)).instrument(span)
1130            });
1131
1132            // CORRECTNESS
1133            //
1134            // Ping/Pong messages and every error must update the peer address state via
1135            // the inbound_ts_collector.
1136            //
1137            // The heartbeat task sends regular Ping/Pong messages,
1138            // and it ends the connection if the heartbeat times out.
1139            // So we can just track peer activity based on Ping and Pong.
1140            // (This significantly improves performance, by reducing time system calls.)
1141            let inbound_ts_collector = address_book_updater.clone();
1142            let compact_inventory = connection_info
1143                .early_block_relay
1144                .then(|| inv_collector.clone());
1145            let inbound_inv_collector = inv_collector;
1146            let ts_inner_conn_span = connection_span.clone();
1147            let inv_inner_conn_span = connection_span.clone();
1148            let peer_rx = peer_rx
1149                .then(move |msg| {
1150                    // Add a metric for inbound messages and errors.
1151                    // Fire a timestamp or failure event.
1152                    let inbound_ts_collector = inbound_ts_collector.clone();
1153                    let span =
1154                        debug_span!(parent: ts_inner_conn_span.clone(), "inbound_ts_collector");
1155
1156                    async move {
1157                        match &msg {
1158                            Ok(msg) => {
1159                                metrics::counter!(
1160                                    "zcash.net.in.messages",
1161                                    "command" => msg.command(),
1162                                )
1163                                .increment(1);
1164
1165                                // # Security
1166                                //
1167                                // Peer messages are not rate-limited, so we can't send anything
1168                                // to a shared channel or do anything expensive here.
1169                            }
1170                            Err(err) => {
1171                                metrics::counter!(
1172                                    "zebra.net.in.errors",
1173                                    "error" => serialization_error_metric_label(err),
1174                                )
1175                                .increment(1);
1176
1177                                // # Security
1178                                //
1179                                // Peer errors are rate-limited because:
1180                                // - opening connections is rate-limited
1181                                // - the number of connections is limited
1182                                // - after the first error, the peer is disconnected
1183                                if let Some(book_addr) = connected_addr.get_address_book_addr() {
1184                                    let _ = inbound_ts_collector
1185                                        .send(MetaAddr::new_errored(book_addr, remote_services))
1186                                        .await;
1187                                }
1188                            }
1189                        }
1190                        msg
1191                    }
1192                    .instrument(span)
1193                })
1194                .then(move |msg| {
1195                    let inbound_inv_collector = inbound_inv_collector.clone();
1196                    let span = debug_span!(parent: inv_inner_conn_span.clone(), "inventory_filter");
1197                    register_inventory_status(msg, connected_addr, inbound_inv_collector)
1198                        .instrument(span)
1199                })
1200                .boxed();
1201
1202            // If we've learned potential peer addresses from the inbound connection remote address
1203            // or the handshake version message, add those addresses to the peer cache for this
1204            // peer.
1205            //
1206            // # Security
1207            //
1208            // We can't add these alternate addresses directly to the address book. If we did,
1209            // malicious peers could interfere with the address book state of other peers by
1210            // providing their addresses in `Version` messages. Or they could fill the address book
1211            // with fake addresses.
1212            //
1213            // These peer addresses are rate-limited because:
1214            // - opening connections is rate-limited
1215            // - these addresses are put in the peer address cache
1216            // - the peer address cache is only used when Zebra requests addresses from that peer
1217            let remote_canonical_addr = connection_info.remote.address_from.addr();
1218            let alternate_addrs = connected_addr
1219                .get_alternate_addrs(remote_canonical_addr)
1220                .map(|addr| {
1221                    MetaAddr::new_gossiped_meta_addr(addr, remote_services, DateTime32::now())
1222                });
1223
1224            let mut server = Connection::new(
1225                inbound_service,
1226                (
1227                    server_rx,
1228                    block_advert_rx,
1229                    minimum_peer_version,
1230                    bans_receiver,
1231                ),
1232                error_slot.clone(),
1233                peer_tx,
1234                connection_tracker,
1235                connection_info.clone(),
1236                alternate_addrs.collect(),
1237            );
1238            server.compact_recovery = compact_recovery;
1239            server.compact_inventory = compact_inventory;
1240
1241            let connection_task = tokio::spawn(
1242                server
1243                    .run(peer_rx)
1244                    .instrument(connection_span.clone())
1245                    .boxed(),
1246            );
1247
1248            let heartbeat_task = tokio::spawn(
1249                send_periodic_heartbeats_with_shutdown_handle(
1250                    connected_addr,
1251                    shutdown_rx,
1252                    server_tx.clone(),
1253                    address_book_updater.clone(),
1254                )
1255                .instrument(tracing::debug_span!(parent: connection_span, "heartbeat"))
1256                .boxed(),
1257            );
1258
1259            let client = Client {
1260                connection_info,
1261                shutdown_tx: Some(shutdown_tx),
1262                server_tx,
1263                block_advert_tx,
1264                error_slot,
1265                connection_task,
1266                heartbeat_task,
1267            };
1268
1269            Ok(client)
1270        };
1271
1272        // Correctness: As a defence-in-depth against hangs, wrap the entire handshake in a timeout.
1273        let fut = timeout(constants::HANDSHAKE_TIMEOUT, fut);
1274
1275        // Forward panics, but cancel negotiation if the owning listener, crawler, or caller stops.
1276        AbortOnDropHandle::new(tokio::spawn(fut.instrument(negotiator_span)))
1277            .map(
1278                |join_result: Result<
1279                    Result<Result<Client, HandshakeError>, error::Elapsed>,
1280                    JoinError,
1281                >| {
1282                    match join_result {
1283                        Ok(Ok(Ok(connection_client))) => Ok(connection_client),
1284                        Ok(Ok(Err(handshake_error))) => Err(handshake_error.into()),
1285                        Ok(Err(timeout_error)) => Err(timeout_error.into()),
1286                        Err(join_error) => match join_error.try_into_panic() {
1287                            // Forward panics to the calling task
1288                            Ok(panic_reason) => panic::resume_unwind(panic_reason),
1289                            Err(join_error) => Err(join_error.into()),
1290                        },
1291                    }
1292                },
1293            )
1294            .boxed()
1295    }
1296}
1297
1298/// Returns a bounded serialization error label without error details.
1299fn serialization_error_metric_label(error: &SerializationError) -> &'static str {
1300    match error {
1301        SerializationError::Io(_) => "io",
1302        SerializationError::Parse(_) => "parse",
1303        SerializationError::Utf8Error(_) => "utf8_error",
1304        SerializationError::TryFromSliceError(_) => "try_from_slice_error",
1305        SerializationError::TryFromIntError(_) => "try_from_int_error",
1306        SerializationError::FromHexError(_) => "from_hex_error",
1307        SerializationError::Amount { .. } => "amount",
1308        SerializationError::BadTransactionBalance => "bad_transaction_balance",
1309        SerializationError::Script(_) => "script",
1310        SerializationError::Opcode(_) => "opcode",
1311        SerializationError::Num(_) => "num",
1312    }
1313}
1314
1315/// Register any advertised or missing inventory in `msg` for `connected_addr`.
1316///
1317/// The connection registers compact block announcements itself, once it has screened them.
1318pub(crate) async fn register_inventory_status(
1319    msg: Result<Message, SerializationError>,
1320    connected_addr: ConnectedAddr,
1321    inv_collector: broadcast::Sender<InventoryChange>,
1322) -> Result<Message, SerializationError> {
1323    match (&msg, connected_addr.get_transient_addr()) {
1324        (Ok(Message::Inv(advertised)), Some(transient_addr)) => {
1325            // We ignore inventory messages with more than one
1326            // block, because they are most likely replies to a
1327            // query, rather than a newly gossiped block.
1328            //
1329            // (We process inventory messages with any number of
1330            // transactions.)
1331            //
1332            // https://zebra.zfnd.org/dev/rfcs/0003-inventory-tracking.html#inventory-monitoring
1333            //
1334            // Note: zcashd has a bug where it merges queued inv messages of
1335            // the same or different types. Zebra compensates by sending `notfound`
1336            // responses to the inv collector. (#2156, #1768)
1337            //
1338            // (We can't split `inv`s, because that fills the inventory registry
1339            // with useless entries that the whole network has, making it large and slow.)
1340            match advertised.as_slice() {
1341                [advertised @ InventoryHash::Block(_)] => {
1342                    debug!(
1343                        ?advertised,
1344                        "registering gossiped advertised block inventory for peer"
1345                    );
1346
1347                    // The peer set and inv collector use the peer's remote
1348                    // address as an identifier
1349                    // If all receivers have been dropped, `send` returns an error.
1350                    // When that happens, Zebra is shutting down, so we want to ignore this error.
1351                    let _ = inv_collector
1352                        .send(InventoryChange::new_available(*advertised, transient_addr));
1353                }
1354                advertised => {
1355                    let advertised = advertised
1356                        .iter()
1357                        .filter(|advertised| advertised.unmined_tx_id().is_some());
1358
1359                    debug!(
1360                        ?advertised,
1361                        "registering advertised unmined transaction inventory for peer",
1362                    );
1363
1364                    if let Some(change) =
1365                        InventoryChange::new_available_multi(advertised, transient_addr)
1366                    {
1367                        // Ignore channel errors that should only happen during shutdown.
1368                        let _ = inv_collector.send(change);
1369                    }
1370                }
1371            }
1372        }
1373
1374        (Ok(Message::NotFound(missing)), Some(transient_addr)) => {
1375            // Only wire messages establish missing inventory; local responses can synthesize IDs.
1376            // Ignore Errors and the unsupported FilteredBlock type
1377            let missing = missing.iter().filter(|missing| {
1378                missing.unmined_tx_id().is_some() || missing.block_hash().is_some()
1379            });
1380
1381            debug!(?missing, "registering missing inventory for peer");
1382
1383            if let Some(change) = InventoryChange::new_missing_multi(missing, transient_addr) {
1384                let _ = inv_collector.send(change);
1385            }
1386        }
1387        _ => {}
1388    }
1389
1390    msg
1391}
1392
1393/// Send periodical heartbeats to `server_tx`, and update the peer status through
1394/// `heartbeat_ts_collector`.
1395///
1396/// # Correctness
1397///
1398/// To prevent hangs:
1399/// - every await that depends on the network must have a timeout (or interval)
1400/// - every error/shutdown must update the address book state and return
1401///
1402/// The address book state can be updated via `ClientRequest.tx`, or the
1403/// heartbeat_ts_collector.
1404///
1405/// Returning from this function terminates the connection's heartbeat task.
1406async fn send_periodic_heartbeats_with_shutdown_handle(
1407    connected_addr: ConnectedAddr,
1408    shutdown_rx: oneshot::Receiver<CancelHeartbeatTask>,
1409    server_tx: futures::channel::mpsc::Sender<ClientRequest>,
1410    heartbeat_ts_collector: AddressBookChangeSender,
1411) -> Result<(), BoxError> {
1412    use futures::future::Either;
1413
1414    let heartbeat_run_loop = send_periodic_heartbeats_run_loop(
1415        connected_addr,
1416        server_tx,
1417        heartbeat_ts_collector.clone(),
1418    );
1419
1420    pin_mut!(shutdown_rx);
1421    pin_mut!(heartbeat_run_loop);
1422
1423    // CORRECTNESS
1424    //
1425    // Currently, select prefers the first future if multiple
1426    // futures are ready.
1427    //
1428    // Starvation is impossible here, because interval has a
1429    // slow rate, and shutdown is a oneshot. If both futures
1430    // are ready, we want the shutdown to take priority over
1431    // sending a useless heartbeat.
1432    match future::select(shutdown_rx, heartbeat_run_loop).await {
1433        Either::Left((Ok(CancelHeartbeatTask), _unused_run_loop)) => {
1434            tracing::trace!("shutting down because Client requested shut down");
1435            handle_heartbeat_shutdown(
1436                PeerError::ClientCancelledHeartbeatTask,
1437                &heartbeat_ts_collector,
1438                &connected_addr,
1439            )
1440            .await
1441        }
1442        Either::Left((Err(oneshot::Canceled), _unused_run_loop)) => {
1443            tracing::trace!("shutting down because Client was dropped");
1444            handle_heartbeat_shutdown(
1445                PeerError::ClientDropped,
1446                &heartbeat_ts_collector,
1447                &connected_addr,
1448            )
1449            .await
1450        }
1451        Either::Right((result, _unused_shutdown)) => {
1452            tracing::trace!("shutting down due to heartbeat failure");
1453            // heartbeat_timeout() already send an error on the timestamp collector channel
1454
1455            result
1456        }
1457    }
1458}
1459
1460/// Send periodical heartbeats to `server_tx`, and update the peer status through
1461/// `heartbeat_ts_collector`.
1462///
1463/// See `send_periodic_heartbeats_with_shutdown_handle` for details.
1464async fn send_periodic_heartbeats_run_loop(
1465    connected_addr: ConnectedAddr,
1466    mut server_tx: futures::channel::mpsc::Sender<ClientRequest>,
1467    heartbeat_ts_collector: AddressBookChangeSender,
1468) -> Result<(), BoxError> {
1469    // Don't send the first heartbeat immediately - we've just completed the handshake!
1470    let mut interval = tokio::time::interval_at(
1471        Instant::now() + constants::HEARTBEAT_INTERVAL,
1472        constants::HEARTBEAT_INTERVAL,
1473    );
1474    // If the heartbeat is delayed, also delay all future heartbeats.
1475    // (Shorter heartbeat intervals just add load, without any benefit.)
1476    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1477
1478    let mut interval_stream = IntervalStream::new(interval);
1479
1480    while let Some(_instant) = interval_stream.next().await {
1481        // We've reached another heartbeat interval without
1482        // shutting down, so do a heartbeat request.
1483        let ping_sent_at = Instant::now();
1484        if let Some(book_addr) = connected_addr.get_address_book_addr() {
1485            let _ = heartbeat_ts_collector
1486                .send(MetaAddr::new_ping_sent(book_addr, ping_sent_at.into()))
1487                .await;
1488        }
1489
1490        let heartbeat = send_one_heartbeat(&mut server_tx);
1491        let rtt = heartbeat_timeout(heartbeat, &heartbeat_ts_collector, &connected_addr).await?;
1492
1493        // # Security
1494        //
1495        // Peer heartbeats are rate-limited because:
1496        // - opening connections is rate-limited
1497        // - the number of connections is limited
1498        // - Zebra initiates each heartbeat using a timer
1499        if let Some(book_addr) = connected_addr.get_address_book_addr() {
1500            if let Some(rtt) = rtt {
1501                // the collector doesn't depend on network activity,
1502                // so this await should not hang
1503                let _ = heartbeat_ts_collector
1504                    .send(MetaAddr::new_responded(book_addr, Some(rtt)))
1505                    .await;
1506            }
1507        }
1508    }
1509
1510    unreachable!("unexpected IntervalStream termination")
1511}
1512
1513/// Send one heartbeat using `server_tx`.
1514async fn send_one_heartbeat(
1515    server_tx: &mut futures::channel::mpsc::Sender<ClientRequest>,
1516) -> Result<Response, BoxError> {
1517    // We just reached a heartbeat interval, so start sending
1518    // a heartbeat.
1519    let (tx, rx) = oneshot::channel();
1520
1521    // Try to send the heartbeat request
1522    let request = Request::Ping(Nonce::default());
1523    tracing::trace!(?request, "queueing heartbeat request");
1524    match server_tx.try_send(ClientRequest {
1525        request,
1526        tx,
1527        span: tracing::Span::current(),
1528    }) {
1529        Ok(()) => {}
1530        Err(e) => {
1531            if e.is_disconnected() {
1532                Err(PeerError::ConnectionClosed)?;
1533            } else if e.is_full() {
1534                // Send the message when the Client becomes ready.
1535                // If sending takes too long, the heartbeat timeout will elapse
1536                // and close the connection, reducing our load to busy peers.
1537                server_tx.send(e.into_inner()).await?;
1538            } else {
1539                // we need to map unexpected error types to PeerErrors
1540                warn!(?e, "unexpected try_send error");
1541                Err(e)?;
1542            };
1543        }
1544    }
1545
1546    // Flush the heartbeat request from the queue
1547    server_tx.flush().await?;
1548    tracing::trace!("sent heartbeat request");
1549
1550    // Heartbeats are checked internally to the
1551    // connection logic, but we need to wait on the
1552    // response to avoid canceling the request.
1553    let response = rx.await??;
1554    tracing::trace!(?response, "got heartbeat response");
1555
1556    Ok(response)
1557}
1558
1559/// Wrap `fut` in a timeout, handing any inner or outer errors using
1560/// `handle_heartbeat_error`.
1561async fn heartbeat_timeout(
1562    fut: impl Future<Output = Result<Response, BoxError>>,
1563    address_book_updater: &AddressBookChangeSender,
1564    connected_addr: &ConnectedAddr,
1565) -> Result<Option<Duration>, BoxError> {
1566    let response = match timeout(constants::HEARTBEAT_INTERVAL, fut).await {
1567        Ok(inner_result) => {
1568            handle_heartbeat_error(inner_result, address_book_updater, connected_addr).await?
1569        }
1570        Err(elapsed) => {
1571            handle_heartbeat_error(Err(elapsed), address_book_updater, connected_addr).await?
1572        }
1573    };
1574
1575    let rtt = match response {
1576        Response::Pong(rtt) => Some(rtt),
1577        _ => None,
1578    };
1579
1580    Ok(rtt)
1581}
1582
1583/// If `result.is_err()`, mark `connected_addr` as failed using `address_book_updater`.
1584async fn handle_heartbeat_error<T, E>(
1585    result: Result<T, E>,
1586    address_book_updater: &AddressBookChangeSender,
1587    connected_addr: &ConnectedAddr,
1588) -> Result<T, E>
1589where
1590    E: std::fmt::Debug,
1591{
1592    match result {
1593        Ok(t) => Ok(t),
1594        Err(err) => {
1595            tracing::debug!(?err, "heartbeat error, shutting down");
1596
1597            // # Security
1598            //
1599            // Peer errors and shutdowns are rate-limited because:
1600            // - opening connections is rate-limited
1601            // - the number of connections is limited
1602            // - after the first error or shutdown, the peer is disconnected
1603            if let Some(book_addr) = connected_addr.get_address_book_addr() {
1604                let _ = address_book_updater
1605                    .send(MetaAddr::new_errored(book_addr, None))
1606                    .await;
1607            }
1608            Err(err)
1609        }
1610    }
1611}
1612
1613/// Mark `connected_addr` as shut down using `address_book_updater`.
1614async fn handle_heartbeat_shutdown(
1615    peer_error: PeerError,
1616    address_book_updater: &AddressBookChangeSender,
1617    connected_addr: &ConnectedAddr,
1618) -> Result<(), BoxError> {
1619    tracing::debug!(?peer_error, "client shutdown, shutting down heartbeat");
1620
1621    if let Some(book_addr) = connected_addr.get_address_book_addr() {
1622        let _ = address_book_updater
1623            .send(MetaAddr::new_shutdown(book_addr))
1624            .await;
1625    }
1626
1627    Err(peer_error.into())
1628}