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