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