Skip to main content

zebra_network/
meta_addr.rs

1//! An address-with-metadata type used in Bitcoin networking.
2
3use std::{
4    cmp::{max, Ordering},
5    time::{Duration, Instant},
6};
7
8use chrono::Utc;
9
10use zebra_chain::{parameters::Network, serialization::DateTime32};
11
12use crate::{
13    constants,
14    peer::{address_is_valid_for_outbound_connections, PeerPreference},
15    protocol::{
16        external::{canonical_peer_addr, types::Version},
17        types::PeerServices,
18    },
19};
20
21use MetaAddrChange::*;
22use PeerAddrState::*;
23
24pub mod peer_addr;
25
26pub use peer_addr::PeerSocketAddr;
27
28#[cfg(any(test, feature = "proptest-impl"))]
29use proptest_derive::Arbitrary;
30
31#[cfg(any(test, feature = "proptest-impl"))]
32use crate::protocol::external::arbitrary::canonical_peer_addr_strategy;
33
34#[cfg(any(test, feature = "proptest-impl"))]
35pub(crate) mod arbitrary;
36
37#[cfg(test)]
38pub(crate) mod tests;
39
40/// Peer connection state, based on our interactions with the peer.
41///
42/// Zebra also tracks how recently a peer has sent us messages, and derives peer
43/// liveness based on the current time. This derived state is tracked using
44/// [`maybe_connected_peers`][mcp] and
45/// [`reconnection_peers`][rp].
46///
47/// [mcp]: crate::AddressBook::maybe_connected_peers
48/// [rp]: crate::AddressBook::reconnection_peers
49#[derive(Copy, Clone, Debug, Eq, PartialEq)]
50#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
51pub enum PeerAddrState {
52    /// The peer has sent us a valid message.
53    ///
54    /// Peers remain in this state, even if they stop responding to requests.
55    /// (Peer liveness is derived from the `last_seen` timestamp, and the current
56    /// time.)
57    Responded,
58
59    /// The peer's address has just been fetched from a DNS seeder, or via peer
60    /// gossip, or as part of a `Version` message, or guessed from an inbound remote IP,
61    /// but we haven't attempted to connect to it yet.
62    NeverAttemptedGossiped,
63
64    /// The peer's TCP connection failed, or the peer sent us an unexpected
65    /// Zcash protocol message, so we failed the connection.
66    Failed,
67
68    /// We just started a connection attempt to this peer.
69    AttemptPending,
70}
71
72impl std::fmt::Display for PeerAddrState {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            Responded => write!(f, "connected"),
76            NeverAttemptedGossiped => write!(f, "never_connected"),
77            Failed => write!(f, "failed"),
78            AttemptPending => write!(f, "connecting"),
79        }
80    }
81}
82
83impl PeerAddrState {
84    /// Return true if this state is a "never attempted" state.
85    pub fn is_never_attempted(&self) -> bool {
86        match self {
87            NeverAttemptedGossiped => true,
88            AttemptPending | Responded | Failed => false,
89        }
90    }
91
92    /// Returns the typical connection state machine order of `self` and `other`.
93    /// Partially ordered states are sorted in connection attempt order.
94    ///
95    /// See [`MetaAddrChange::apply_to_meta_addr()`] for more details.
96    fn connection_state_order(&self, other: &Self) -> Ordering {
97        use Ordering::*;
98        match (self, other) {
99            _ if self == other => Equal,
100            // Peers start in the "never attempted" state,
101            // then typically progress towards a "responded" or "failed" state.
102            (NeverAttemptedGossiped, _) => Less,
103            (_, NeverAttemptedGossiped) => Greater,
104            (AttemptPending, _) => Less,
105            (_, AttemptPending) => Greater,
106            (Responded, _) => Less,
107            (_, Responded) => Greater,
108            // These patterns are redundant, but Rust doesn't assume that `==` is reflexive,
109            // so the first is still required (but unreachable).
110            (Failed, _) => Less,
111            //(_, Failed) => Greater,
112        }
113    }
114}
115
116// non-test code should explicitly specify the peer address state
117#[cfg(test)]
118#[allow(clippy::derivable_impls)]
119impl Default for PeerAddrState {
120    fn default() -> Self {
121        NeverAttemptedGossiped
122    }
123}
124
125impl Ord for PeerAddrState {
126    /// `PeerAddrState`s are sorted in approximate reconnection attempt
127    /// order, ignoring liveness.
128    ///
129    /// See [`candidate_set`] and [`MetaAddr::cmp`] for more details.
130    ///
131    /// [`candidate_set`]: super::peer_set::candidate_set
132    fn cmp(&self, other: &Self) -> Ordering {
133        use Ordering::*;
134        match (self, other) {
135            _ if self == other => Equal,
136            // We reconnect to `Responded` peers that have stopped sending messages,
137            // then `NeverAttempted` peers, then `Failed` peers
138            (Responded, _) => Less,
139            (_, Responded) => Greater,
140            (NeverAttemptedGossiped, _) => Less,
141            (_, NeverAttemptedGossiped) => Greater,
142            (Failed, _) => Less,
143            (_, Failed) => Greater,
144            // These patterns are redundant, but Rust doesn't assume that `==` is reflexive,
145            // so the first is still required (but unreachable).
146            (AttemptPending, _) => Less,
147            //(_, AttemptPending) => Greater,
148        }
149    }
150}
151
152impl PartialOrd for PeerAddrState {
153    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
154        Some(self.cmp(other))
155    }
156}
157
158/// An address with metadata on its advertised services and last-seen time.
159///
160/// This struct can be created from `addr` or `addrv2` messages.
161///
162/// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#Network_address)
163#[derive(Clone, Debug)]
164#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
165pub struct MetaAddr {
166    /// The peer's canonical socket address.
167    #[cfg_attr(
168        any(test, feature = "proptest-impl"),
169        proptest(strategy = "canonical_peer_addr_strategy()")
170    )]
171    //
172    // TODO: make addr private, so the constructors can make sure it is a
173    // canonical SocketAddr (#2357)
174    pub(crate) addr: PeerSocketAddr,
175
176    /// The services advertised by the peer.
177    ///
178    /// The exact meaning depends on `last_connection_state`:
179    ///   - `Responded`: the services advertised by this peer, the last time we
180    ///     performed a handshake with it
181    ///   - `NeverAttempted`: the unverified services advertised by another peer,
182    ///     then gossiped by the peer that sent us this address
183    ///   - `Failed` or `AttemptPending`: unverified services via another peer,
184    ///     or services advertised in a previous handshake
185    ///
186    /// ## Security
187    ///
188    /// `services` from `NeverAttempted` peers may be invalid due to outdated
189    /// records, older peer versions, or buggy or malicious peers.
190    //
191    // TODO: make services private
192    //       split gossiped and handshake services? (#2324)
193    pub(crate) services: Option<PeerServices>,
194
195    /// The unverified "last seen time" gossiped by the remote peer that sent us
196    /// this address.
197    ///
198    /// See the [`MetaAddr::last_seen`] method for details.
199    untrusted_last_seen: Option<DateTime32>,
200
201    /// The last time we received a message from this peer.
202    ///
203    /// See the [`MetaAddr::last_seen`] method for details.
204    last_response: Option<DateTime32>,
205
206    /// The last measured round-trip time (RTT) for this peer, if available.
207    ///
208    /// This value is updated when the peer responds to a ping (Pong).
209    rtt: Option<Duration>,
210
211    /// The last time we sent a ping to this peer.
212    ///
213    /// This value is updated each time a heartbeat ping is sent,
214    /// even if we never receive a response.
215    ping_sent_at: Option<Instant>,
216
217    /// The last time we tried to open an outbound connection to this peer.
218    ///
219    /// See the [`MetaAddr::last_attempt`] method for details.
220    last_attempt: Option<Instant>,
221
222    /// The last time our outbound connection with this peer failed.
223    ///
224    /// See the [`MetaAddr::last_failure`] method for details.
225    last_failure: Option<Instant>,
226
227    /// The outcome of our most recent communication attempt with this peer.
228    //
229    // TODO: move the time and services fields into PeerAddrState?
230    //       then some fields could be required in some states
231    pub(crate) last_connection_state: PeerAddrState,
232
233    /// Whether this peer address was added to the address book
234    /// when the peer made an inbound connection.
235    is_inbound: bool,
236
237    /// The user agent string reported by the peer during handshake, if available.
238    user_agent: Option<String>,
239
240    /// The protocol version negotiated with the peer during handshake, if available.
241    negotiated_version: Option<Version>,
242}
243
244/// A change to an existing `MetaAddr`.
245#[derive(Clone, Debug, Eq, PartialEq)]
246#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
247pub enum MetaAddrChange {
248    // TODO:
249    // - split the common `addr` field into an outer struct
250    //
251    /// Creates a `MetaAddr` for an initial peer.
252    NewInitial {
253        #[cfg_attr(
254            any(test, feature = "proptest-impl"),
255            proptest(strategy = "canonical_peer_addr_strategy()")
256        )]
257        addr: PeerSocketAddr,
258    },
259
260    /// Creates a new gossiped `MetaAddr`.
261    NewGossiped {
262        #[cfg_attr(
263            any(test, feature = "proptest-impl"),
264            proptest(strategy = "canonical_peer_addr_strategy()")
265        )]
266        addr: PeerSocketAddr,
267        untrusted_services: PeerServices,
268        untrusted_last_seen: DateTime32,
269    },
270
271    /// Creates new local listener `MetaAddr`.
272    NewLocal {
273        #[cfg_attr(
274            any(test, feature = "proptest-impl"),
275            proptest(strategy = "canonical_peer_addr_strategy()")
276        )]
277        addr: PeerSocketAddr,
278    },
279
280    /// Updates an existing `MetaAddr` when an outbound connection attempt
281    /// starts.
282    UpdateAttempt {
283        #[cfg_attr(
284            any(test, feature = "proptest-impl"),
285            proptest(strategy = "canonical_peer_addr_strategy()")
286        )]
287        addr: PeerSocketAddr,
288    },
289
290    /// Updates an existing `MetaAddr` when we've made a successful connection with a peer.
291    UpdateConnected {
292        #[cfg_attr(
293            any(test, feature = "proptest-impl"),
294            proptest(strategy = "canonical_peer_addr_strategy()")
295        )]
296        addr: PeerSocketAddr,
297        services: PeerServices,
298        is_inbound: bool,
299        user_agent: String,
300        negotiated_version: Version,
301    },
302
303    /// Updates an existing `MetaAddr` when we send a ping to a peer.
304    UpdatePingSent {
305        #[cfg_attr(
306            any(test, feature = "proptest-impl"),
307            proptest(strategy = "canonical_peer_addr_strategy()")
308        )]
309        addr: PeerSocketAddr,
310        ping_sent_at: Instant,
311    },
312
313    /// Updates an existing `MetaAddr` when a peer responds with a message.
314    UpdateResponded {
315        #[cfg_attr(
316            any(test, feature = "proptest-impl"),
317            proptest(strategy = "canonical_peer_addr_strategy()")
318        )]
319        addr: PeerSocketAddr,
320        rtt: Option<Duration>,
321    },
322
323    /// Updates an existing `MetaAddr` when a peer fails.
324    UpdateFailed {
325        #[cfg_attr(
326            any(test, feature = "proptest-impl"),
327            proptest(strategy = "canonical_peer_addr_strategy()")
328        )]
329        addr: PeerSocketAddr,
330        services: Option<PeerServices>,
331    },
332
333    /// Bans a peer's group when it misbehaves, such as by advertising
334    /// semantically invalid blocks or transactions.
335    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
336    UpdateMisbehavior {
337        addr: PeerSocketAddr,
338        score_increment: u32,
339        /// Why the peer was scored, logged if this change bans the peer's group.
340        reason: String,
341    },
342}
343
344impl MetaAddr {
345    /// Returns a [`MetaAddrChange::NewInitial`] for a peer that was excluded from
346    /// the list of the initial peers.
347    pub fn new_initial_peer(addr: PeerSocketAddr) -> MetaAddrChange {
348        NewInitial {
349            addr: canonical_peer_addr(addr),
350        }
351    }
352
353    /// Returns a new `MetaAddr`, based on the deserialized fields from a
354    /// gossiped peer [`Addr`][crate::protocol::external::Message::Addr] message.
355    pub fn new_gossiped_meta_addr(
356        addr: PeerSocketAddr,
357        untrusted_services: PeerServices,
358        untrusted_last_seen: DateTime32,
359    ) -> MetaAddr {
360        MetaAddr {
361            addr: canonical_peer_addr(addr),
362            services: Some(untrusted_services),
363            untrusted_last_seen: Some(untrusted_last_seen),
364            last_response: None,
365            rtt: None,
366            ping_sent_at: None,
367            last_attempt: None,
368            last_failure: None,
369            last_connection_state: NeverAttemptedGossiped,
370            is_inbound: false,
371            user_agent: None,
372            negotiated_version: None,
373        }
374    }
375
376    /// Returns a [`MetaAddrChange::NewGossiped`], based on a gossiped peer
377    /// [`MetaAddr`].
378    ///
379    /// Returns [`None`] if the gossiped peer is missing the untrusted services field.
380    #[allow(clippy::unwrap_in_result)]
381    pub fn new_gossiped_change(self) -> Option<MetaAddrChange> {
382        let untrusted_services = self.services?;
383
384        Some(NewGossiped {
385            addr: canonical_peer_addr(self.addr),
386            untrusted_services,
387            untrusted_last_seen: self
388                .untrusted_last_seen
389                .expect("unexpected missing last seen"),
390        })
391    }
392
393    /// Returns a [`MetaAddrChange::UpdateConnected`] for a peer that has just successfully
394    /// connected.
395    ///
396    /// # Security
397    ///
398    /// This address must be the remote address from an outbound connection,
399    /// and the services must be the services from that peer's handshake.
400    ///
401    /// Otherwise:
402    /// - malicious peers could interfere with other peers' [`AddressBook`](crate::AddressBook)
403    ///   state, or
404    /// - Zebra could advertise unreachable addresses to its own peers.
405    pub fn new_connected(
406        addr: PeerSocketAddr,
407        services: &PeerServices,
408        is_inbound: bool,
409        user_agent: String,
410        negotiated_version: Version,
411    ) -> MetaAddrChange {
412        UpdateConnected {
413            addr: canonical_peer_addr(*addr),
414            services: *services,
415            is_inbound,
416            user_agent,
417            negotiated_version,
418        }
419    }
420
421    /// Returns a [`MetaAddrChange::UpdatePingSent`] for a peer that we just sent a ping to.
422    pub fn new_ping_sent(addr: PeerSocketAddr, ping_sent_at: Instant) -> MetaAddrChange {
423        UpdatePingSent {
424            addr: canonical_peer_addr(*addr),
425            ping_sent_at,
426        }
427    }
428
429    /// Returns a [`MetaAddrChange::UpdateResponded`] for a peer that has just
430    /// sent us a message.
431    ///
432    /// # Security
433    ///
434    /// This address must be the remote address from an outbound connection.
435    ///
436    /// Otherwise:
437    /// - malicious peers could interfere with other peers' [`AddressBook`](crate::AddressBook)
438    ///   state, or
439    /// - Zebra could advertise unreachable addresses to its own peers.
440    pub fn new_responded(addr: PeerSocketAddr, rtt: Option<Duration>) -> MetaAddrChange {
441        UpdateResponded {
442            addr: canonical_peer_addr(*addr),
443            rtt,
444        }
445    }
446
447    /// Returns a [`MetaAddrChange::UpdateAttempt`] for a peer that we
448    /// want to make an outbound connection to.
449    pub fn new_reconnect(addr: PeerSocketAddr) -> MetaAddrChange {
450        UpdateAttempt {
451            addr: canonical_peer_addr(*addr),
452        }
453    }
454
455    /// Returns a [`MetaAddrChange::NewLocal`] for our own listener address.
456    pub fn new_local_listener_change(addr: impl Into<PeerSocketAddr>) -> MetaAddrChange {
457        NewLocal {
458            addr: canonical_peer_addr(addr),
459        }
460    }
461
462    /// Returns a [`MetaAddrChange::UpdateFailed`] for a peer that has just had an error.
463    pub fn new_errored(
464        addr: PeerSocketAddr,
465        services: impl Into<Option<PeerServices>>,
466    ) -> MetaAddrChange {
467        UpdateFailed {
468            addr: canonical_peer_addr(*addr),
469            services: services.into(),
470        }
471    }
472
473    /// Returns a [`MetaAddrChange::UpdateMisbehavior`] for a peer that has misbehaved.
474    ///
475    /// Canonicalizes the address to match the form stored by a successful handshake
476    /// (`new_connected`). On Linux dual-stack sockets, inbound IPv4 connections
477    /// arrive as IPv4-mapped IPv6 addresses (`::ffff:A.B.C.D`); without
478    /// canonicalization, `apply_to_meta_addr` panics on the addr invariant.
479    pub fn new_misbehavior(
480        addr: PeerSocketAddr,
481        score_increment: u32,
482        reason: impl Into<String>,
483    ) -> MetaAddrChange {
484        UpdateMisbehavior {
485            addr: canonical_peer_addr(*addr),
486            score_increment,
487            reason: reason.into(),
488        }
489    }
490
491    /// Create a new `MetaAddr` for a peer that has just shut down.
492    pub fn new_shutdown(addr: PeerSocketAddr) -> MetaAddrChange {
493        // TODO: if the peer shut down in the Responded state, preserve that
494        // state. All other states should be treated as (timeout) errors.
495        MetaAddr::new_errored(addr, None)
496    }
497
498    /// Return the address for this `MetaAddr`.
499    pub fn addr(&self) -> PeerSocketAddr {
500        self.addr
501    }
502
503    /// Return the address preference level for this `MetaAddr`.
504    pub fn peer_preference(&self) -> Result<PeerPreference, &'static str> {
505        PeerPreference::new(self.addr, None)
506    }
507
508    /// Returns the time of the last successful interaction with this peer.
509    ///
510    /// Initially set to the unverified "last seen time" gossiped by the remote
511    /// peer that sent us this address.
512    ///
513    /// If the `last_connection_state` has ever been `Responded`, this field is
514    /// set to the last time we processed a message from this peer.
515    ///
516    /// ## Security
517    ///
518    /// `last_seen` times from peers that have never `Responded` may be
519    /// incorrect due to clock skew, or buggy or malicious peers.
520    pub fn last_seen(&self) -> Option<DateTime32> {
521        self.last_response.or(self.untrusted_last_seen)
522    }
523
524    /// Returns whether the address is from an inbound peer connection
525    pub fn is_inbound(&self) -> bool {
526        self.is_inbound
527    }
528
529    /// Returns the round-trip time (RTT) for this peer, if available.
530    pub fn rtt(&self) -> Option<Duration> {
531        self.rtt
532    }
533
534    /// Returns the time this peer was last pinged, if available.
535    pub fn ping_sent_at(&self) -> Option<Instant> {
536        self.ping_sent_at
537    }
538
539    /// Returns the unverified "last seen time" gossiped by the remote peer that
540    /// sent us this address.
541    ///
542    /// See the [`MetaAddr::last_seen`] method for details.
543    //
544    // TODO: pub(in crate::address_book) - move meta_addr into address_book
545    pub(crate) fn untrusted_last_seen(&self) -> Option<DateTime32> {
546        self.untrusted_last_seen
547    }
548
549    /// Returns the last time we received a message from this peer.
550    ///
551    /// See the [`MetaAddr::last_seen`] method for details.
552    //
553    // TODO: pub(in crate::address_book) - move meta_addr into address_book
554    #[allow(dead_code)]
555    pub(crate) fn last_response(&self) -> Option<DateTime32> {
556        self.last_response
557    }
558
559    /// Set the gossiped untrusted last seen time for this peer.
560    pub(crate) fn set_untrusted_last_seen(&mut self, untrusted_last_seen: DateTime32) {
561        self.untrusted_last_seen = Some(untrusted_last_seen);
562    }
563
564    /// Returns the time of our last outbound connection attempt with this peer.
565    ///
566    /// If the `last_connection_state` has ever been `AttemptPending`, this
567    /// field is set to the last time we started an outbound connection attempt
568    /// with this peer.
569    pub fn last_attempt(&self) -> Option<Instant> {
570        self.last_attempt
571    }
572
573    /// Returns the time of our last failed outbound connection with this peer.
574    ///
575    /// If the `last_connection_state` has ever been `Failed`, this field is set
576    /// to the last time:
577    /// - a connection attempt failed, or
578    /// - an open connection encountered a fatal protocol error.
579    pub fn last_failure(&self) -> Option<Instant> {
580        self.last_failure
581    }
582
583    /// Have we had any recently messages from this peer?
584    ///
585    /// Returns `true` if the peer is likely connected and responsive in the peer
586    /// set.
587    ///
588    /// [`constants::MIN_PEER_RECONNECTION_DELAY`] represents the time interval in which
589    /// we should receive at least one message from a peer, or close the
590    /// connection. Therefore, if the last-seen timestamp is older than
591    /// [`constants::MIN_PEER_RECONNECTION_DELAY`] ago, we know we should have
592    /// disconnected from it. Otherwise, we could potentially be connected to it.
593    pub fn has_connection_recently_responded(&self, now: chrono::DateTime<Utc>) -> bool {
594        if let Some(last_response) = self.last_response {
595            // Recent times and future times are considered live
596            last_response.saturating_elapsed(now)
597                <= constants::MIN_PEER_RECONNECTION_DELAY
598                    .try_into()
599                    .expect("unexpectedly large constant")
600        } else {
601            // If there has never been any response, it can't possibly be live
602            false
603        }
604    }
605
606    /// Have we recently attempted an outbound connection to this peer?
607    ///
608    /// Returns `true` if this peer was recently attempted, or has a connection
609    /// attempt in progress.
610    pub fn was_connection_recently_attempted(&self, now: Instant) -> bool {
611        if let Some(last_attempt) = self.last_attempt {
612            // Recent times and future times are considered live.
613            // Instants are monotonic, so `now` should always be later than `last_attempt`,
614            // except for synthetic data in tests.
615            now.saturating_duration_since(last_attempt) <= constants::MIN_PEER_RECONNECTION_DELAY
616        } else {
617            // If there has never been any attempt, it can't possibly be live
618            false
619        }
620    }
621
622    /// Have we recently had a failed connection to this peer?
623    ///
624    /// Returns `true` if this peer has recently failed.
625    pub fn has_connection_recently_failed(&self, now: Instant) -> bool {
626        if let Some(last_failure) = self.last_failure {
627            // Recent times and future times are considered live
628            now.saturating_duration_since(last_failure) <= constants::MIN_PEER_RECONNECTION_DELAY
629        } else {
630            // If there has never been any failure, it can't possibly be recent
631            false
632        }
633    }
634
635    /// Returns true if this peer has recently sent us a message.
636    pub fn was_recently_live(&self, now: chrono::DateTime<Utc>) -> bool {
637        // NeverAttempted, Failed, and AttemptPending peers should never be live
638        self.last_connection_state == PeerAddrState::Responded
639            && self.has_connection_recently_responded(now)
640    }
641
642    /// Has this peer been seen recently?
643    ///
644    /// Returns `true` if this peer has responded recently or if the peer was gossiped with a
645    /// recent reported last seen time.
646    ///
647    /// [`constants::MAX_PEER_ACTIVE_FOR_GOSSIP`] represents the maximum time since a peer was seen
648    /// to still be considered reachable.
649    pub fn is_active_for_gossip(&self, now: chrono::DateTime<Utc>) -> bool {
650        if let Some(last_seen) = self.last_seen() {
651            // Correctness: `last_seen` shouldn't ever be in the future, either because we set the
652            // time or because another peer's future time was sanitized when it was added to the
653            // address book
654            last_seen.saturating_elapsed(now) <= constants::MAX_PEER_ACTIVE_FOR_GOSSIP
655        } else {
656            // Peer has never responded and does not have a gossiped last seen time
657            false
658        }
659    }
660
661    /// Returns true if any messages were recently sent to or received from this address.
662    pub fn was_recently_updated(
663        &self,
664        instant_now: Instant,
665        chrono_now: chrono::DateTime<Utc>,
666    ) -> bool {
667        self.has_connection_recently_responded(chrono_now)
668            || self.was_connection_recently_attempted(instant_now)
669            || self.has_connection_recently_failed(instant_now)
670    }
671
672    /// Is this address ready for a new outbound connection attempt?
673    pub fn is_ready_for_connection_attempt(
674        &self,
675        instant_now: Instant,
676        chrono_now: chrono::DateTime<Utc>,
677        network: &Network,
678    ) -> bool {
679        self.last_known_info_is_valid_for_outbound(network)
680            && !self.was_recently_updated(instant_now, chrono_now)
681            && self.is_probably_reachable(chrono_now)
682    }
683
684    /// Is the [`PeerSocketAddr`] we have for this peer valid for outbound
685    /// connections?
686    ///
687    /// Since the addresses in the address book are unique, this check can be
688    /// used to permanently reject entire [`MetaAddr`]s.
689    pub fn address_is_valid_for_outbound(&self, network: &Network) -> bool {
690        address_is_valid_for_outbound_connections(self.addr, network.clone()).is_ok()
691    }
692
693    /// Is the last known information for this peer valid for outbound
694    /// connections?
695    ///
696    /// The last known info might be outdated or untrusted, so this check can
697    /// only be used to:
698    /// - reject `NeverAttempted...` [`MetaAddrChange`]s, and
699    /// - temporarily stop outbound connections to a [`MetaAddr`].
700    pub fn last_known_info_is_valid_for_outbound(&self, network: &Network) -> bool {
701        let is_node = match self.services {
702            Some(services) => services.contains(PeerServices::NODE_NETWORK),
703            None => true,
704        };
705
706        is_node && self.address_is_valid_for_outbound(network)
707    }
708
709    /// Should this peer considered reachable?
710    ///
711    /// A peer is probably reachable if:
712    /// - it has never been attempted, or
713    /// - the last connection attempt was successful, or
714    /// - the last successful connection was less than 3 days ago.
715    ///
716    /// # Security
717    ///
718    /// This is used by [`Self::is_ready_for_connection_attempt`] so that Zebra stops trying to
719    /// connect to peers that are likely unreachable.
720    ///
721    /// The `untrusted_last_seen` time is used as a fallback time if the local node has never
722    /// itself seen the peer. If the reported last seen time is a long time ago or `None`, then the local
723    /// node will attempt to connect the peer once, and if that attempt fails it won't
724    /// try to connect ever again. (The state can't be `Failed` until after the first connection attempt.)
725    pub fn is_probably_reachable(&self, now: chrono::DateTime<Utc>) -> bool {
726        self.last_connection_state != PeerAddrState::Failed || self.last_seen_is_recent(now)
727    }
728
729    /// Was this peer last seen recently?
730    ///
731    /// Returns `true` if this peer was last seen at most
732    /// [`MAX_RECENT_PEER_AGE`][constants::MAX_RECENT_PEER_AGE] ago.
733    /// Returns false if the peer is outdated, or it has no last seen time.
734    pub fn last_seen_is_recent(&self, now: chrono::DateTime<Utc>) -> bool {
735        match self.last_seen() {
736            Some(last_seen) => last_seen.saturating_elapsed(now) <= constants::MAX_RECENT_PEER_AGE,
737            None => false,
738        }
739    }
740
741    /// Returns the services advertised by the peer, if available.
742    pub fn services(&self) -> Option<PeerServices> {
743        self.services
744    }
745
746    /// Returns the last known connection state for this peer.
747    pub fn last_connection_state(&self) -> PeerAddrState {
748        self.last_connection_state
749    }
750
751    /// Returns the user agent string reported by this peer, if available.
752    pub fn user_agent(&self) -> Option<&str> {
753        self.user_agent.as_deref()
754    }
755
756    /// Returns the negotiated protocol version for this peer, if available.
757    pub fn negotiated_version(&self) -> Option<Version> {
758        self.negotiated_version
759    }
760
761    /// Return a sanitized version of this `MetaAddr`, for sending to a remote peer.
762    ///
763    /// Returns `None` if services are unknown or this `MetaAddr` should not be sent to remote peers.
764    #[allow(clippy::unwrap_in_result)]
765    pub fn sanitize(&self, network: &Network) -> Option<MetaAddr> {
766        if self.services.is_none() || !self.last_known_info_is_valid_for_outbound(network) {
767            return None;
768        }
769
770        // Inbound addresses are ephemeral remote ports, not listener ports.
771        if self.is_inbound {
772            return None;
773        }
774
775        // Sanitize time
776        let last_seen = self.last_seen()?;
777        let remainder = last_seen
778            .timestamp()
779            .rem_euclid(crate::constants::TIMESTAMP_TRUNCATION_SECONDS);
780        let last_seen = last_seen
781            .checked_sub(remainder.into())
782            .expect("unexpected underflow: rem_euclid is strictly less than timestamp");
783
784        Some(MetaAddr {
785            addr: canonical_peer_addr(self.addr),
786            services: self.services,
787            // only put the last seen time in the untrusted field,
788            // this matches deserialization, and avoids leaking internal state
789            untrusted_last_seen: Some(last_seen),
790            last_response: None,
791            // these fields aren't sent to the remote peer, but sanitize them anyway
792            rtt: None,
793            ping_sent_at: None,
794            last_attempt: None,
795            last_failure: None,
796            last_connection_state: NeverAttemptedGossiped,
797            is_inbound: false,
798            user_agent: None,
799            negotiated_version: None,
800        })
801    }
802}
803
804#[cfg(test)]
805impl MetaAddr {
806    /// Forcefully change the time this peer last responded.
807    ///
808    /// This method is for testing purposes only.
809    pub(crate) fn set_last_response(&mut self, last_response: DateTime32) {
810        self.last_response = Some(last_response);
811    }
812}
813
814impl MetaAddrChange {
815    /// Return the address for this change.
816    pub fn addr(&self) -> PeerSocketAddr {
817        match self {
818            NewInitial { addr }
819            | NewGossiped { addr, .. }
820            | NewLocal { addr, .. }
821            | UpdateAttempt { addr }
822            | UpdateConnected { addr, .. }
823            | UpdatePingSent { addr, .. }
824            | UpdateResponded { addr, .. }
825            | UpdateFailed { addr, .. }
826            | UpdateMisbehavior { addr, .. } => *addr,
827        }
828    }
829
830    #[cfg(any(test, feature = "proptest-impl"))]
831    /// Set the address for this change to `new_addr`.
832    ///
833    /// This method should only be used in tests.
834    pub fn set_addr(&mut self, new_addr: PeerSocketAddr) {
835        match self {
836            NewInitial { addr }
837            | NewGossiped { addr, .. }
838            | NewLocal { addr, .. }
839            | UpdateAttempt { addr }
840            | UpdateConnected { addr, .. }
841            | UpdatePingSent { addr, .. }
842            | UpdateResponded { addr, .. }
843            | UpdateFailed { addr, .. }
844            | UpdateMisbehavior { addr, .. } => *addr = new_addr,
845        }
846    }
847
848    /// Return the untrusted services for this change, if available.
849    pub fn untrusted_services(&self) -> Option<PeerServices> {
850        match self {
851            NewInitial { .. } => None,
852            // TODO: split untrusted and direct services (#2324)
853            NewGossiped {
854                untrusted_services, ..
855            } => Some(*untrusted_services),
856            // TODO: create a "services implemented by Zebra" constant (#2324)
857            NewLocal { .. } => Some(PeerServices::NODE_NETWORK),
858            UpdateAttempt { .. } => None,
859            UpdateConnected { services, .. } => Some(*services),
860            UpdatePingSent { .. } => None,
861            UpdateResponded { .. } => None,
862            UpdateFailed { services, .. } => *services,
863            UpdateMisbehavior { .. } => None,
864        }
865    }
866
867    /// Return the untrusted last seen time for this change, if available.
868    pub fn untrusted_last_seen(&self, now: DateTime32) -> Option<DateTime32> {
869        match self {
870            NewInitial { .. } => None,
871            NewGossiped {
872                untrusted_last_seen,
873                ..
874            } => Some(*untrusted_last_seen),
875            // We know that our local listener is available
876            NewLocal { .. } => Some(now),
877            UpdateAttempt { .. }
878            | UpdateConnected { .. }
879            | UpdatePingSent { .. }
880            | UpdateResponded { .. }
881            | UpdateFailed { .. }
882            | UpdateMisbehavior { .. } => None,
883        }
884    }
885
886    // # Concurrency
887    //
888    // We assign a time to each change when it is applied to the address book by either the
889    // address book updater or candidate set tasks. This is the time that the change was received
890    // from the updater channel, rather than the time that the message was read from the peer
891    // connection.
892    //
893    // Since the connection tasks run concurrently in an unspecified order, and the address book
894    // updater runs in a separate thread, these times are almost always very similar. If Zebra's
895    // address book is under load, we should use lower rate-limits for new inbound or outbound
896    // connections, disconnections, peer gossip crawls, or peer `UpdateResponded` updates.
897    //
898    // TODO:
899    // - move the time API calls from `impl MetaAddrChange` `last_*()` methods:
900    //   - if they impact performance, call them once in the address book updater task,
901    //     then apply them to all the waiting changes
902    //   - otherwise, move them to the `impl MetaAddrChange` `new_*()` methods,
903    //     so they are called in the connection tasks
904    //
905    /// Return the last attempt for this change, if available.
906    pub fn last_attempt(&self, now: Instant) -> Option<Instant> {
907        match self {
908            NewInitial { .. } | NewGossiped { .. } | NewLocal { .. } => None,
909            // Attempt changes are applied before we start the handshake to the
910            // peer address. So the attempt time is a lower bound for the actual
911            // handshake time.
912            UpdateAttempt { .. } => Some(now),
913            UpdateConnected { .. }
914            | UpdatePingSent { .. }
915            | UpdateResponded { .. }
916            | UpdateFailed { .. }
917            | UpdateMisbehavior { .. } => None,
918        }
919    }
920
921    /// Return the last response for this change, if available.
922    pub fn last_response(&self, now: DateTime32) -> Option<DateTime32> {
923        match self {
924            NewInitial { .. } | NewGossiped { .. } | NewLocal { .. } | UpdateAttempt { .. } => None,
925            // If there is a large delay applying this change, then:
926            // - the peer might stay in the `AttemptPending` state for longer,
927            // - we might send outdated last seen times to our peers, and
928            // - the peer will appear to be live for longer, delaying future
929            //   reconnection attempts.
930            UpdateConnected { .. } | UpdateResponded { .. } => Some(now),
931            UpdateFailed { .. } | UpdateMisbehavior { .. } => None,
932            UpdatePingSent { .. } => None,
933        }
934    }
935
936    /// Return the timestamp when a ping was last sent, if available.
937    pub fn ping_sent(&self) -> Option<Instant> {
938        match self {
939            UpdatePingSent { ping_sent_at, .. } => Some(*ping_sent_at),
940            _ => None,
941        }
942    }
943
944    /// Return the RTT for this change, if available
945    pub fn rtt(&self) -> Option<Duration> {
946        match self {
947            UpdateResponded { rtt, .. } => *rtt,
948            _ => None,
949        }
950    }
951
952    /// Returns the timestamp when a ping was last sent, if available.
953    pub fn ping_sent_at(&self) -> Option<Instant> {
954        match self {
955            UpdatePingSent { ping_sent_at, .. } => Some(*ping_sent_at),
956            _ => None,
957        }
958    }
959
960    /// Return the last failure for this change, if available.
961    pub fn last_failure(&self, now: Instant) -> Option<Instant> {
962        match self {
963            NewInitial { .. }
964            | NewGossiped { .. }
965            | NewLocal { .. }
966            | UpdateAttempt { .. }
967            | UpdateConnected { .. }
968            | UpdatePingSent { .. }
969            | UpdateResponded { .. } => None,
970            // If there is a large delay applying this change, then:
971            // - the peer might stay in the `AttemptPending` or `Responded`
972            //   states for longer, and
973            // - the peer will appear to be used for longer, delaying future
974            //   reconnection attempts.
975            UpdateFailed { .. } | UpdateMisbehavior { .. } => Some(now),
976        }
977    }
978
979    /// Return the peer connection state for this change.
980    pub fn peer_addr_state(&self) -> PeerAddrState {
981        match self {
982            NewInitial { .. } => NeverAttemptedGossiped,
983            NewGossiped { .. } => NeverAttemptedGossiped,
984            // local listeners get sanitized, so the state doesn't matter here
985            NewLocal { .. } => NeverAttemptedGossiped,
986            UpdateAttempt { .. } => AttemptPending,
987            UpdateConnected { .. }
988            // Sending a ping is an interaction with a connected peer, but does not indicate new liveness.
989            // Peers stay in Responded once connected, so we keep them in that state for UpdatePingSent.
990            | UpdatePingSent { .. }
991            | UpdateResponded { .. }
992            | UpdateMisbehavior { .. } => Responded,
993            UpdateFailed { .. } => Failed,
994        }
995    }
996
997    /// Returns the corresponding `MetaAddr` for this change.
998    pub fn into_new_meta_addr(self, instant_now: Instant, local_now: DateTime32) -> MetaAddr {
999        let user_agent = self.user_agent();
1000        let negotiated_version = self.negotiated_version();
1001        MetaAddr {
1002            addr: self.addr(),
1003            services: self.untrusted_services(),
1004            untrusted_last_seen: self.untrusted_last_seen(local_now),
1005            last_response: self.last_response(local_now),
1006            rtt: self.rtt(),
1007            ping_sent_at: self.ping_sent_at(),
1008            last_attempt: self.last_attempt(instant_now),
1009            last_failure: self.last_failure(instant_now),
1010            last_connection_state: self.peer_addr_state(),
1011            is_inbound: self.is_inbound(),
1012            user_agent,
1013            negotiated_version,
1014        }
1015    }
1016
1017    /// Returns the misbehavior score for the current change, or `0` if it is not
1018    /// an [`MetaAddrChange::UpdateMisbehavior`] change.
1019    pub fn misbehavior_score(&self) -> u32 {
1020        match self {
1021            MetaAddrChange::UpdateMisbehavior {
1022                score_increment, ..
1023            } => *score_increment,
1024            _ => 0,
1025        }
1026    }
1027
1028    /// Returns the reason the peer was scored, or `None` if this is not an
1029    /// [`MetaAddrChange::UpdateMisbehavior`] change.
1030    pub fn misbehavior_reason(&self) -> Option<&str> {
1031        match self {
1032            MetaAddrChange::UpdateMisbehavior { reason, .. } => Some(reason),
1033            _ => None,
1034        }
1035    }
1036
1037    /// Returns whether this change was created for a new inbound connection.
1038    pub fn is_inbound(&self) -> bool {
1039        if let MetaAddrChange::UpdateConnected { is_inbound, .. } = self {
1040            *is_inbound
1041        } else {
1042            false
1043        }
1044    }
1045
1046    /// Returns the user agent from this change, if available.
1047    pub fn user_agent(&self) -> Option<String> {
1048        if let MetaAddrChange::UpdateConnected { user_agent, .. } = self {
1049            Some(user_agent.clone())
1050        } else {
1051            None
1052        }
1053    }
1054
1055    /// Returns the negotiated protocol version from this change, if available.
1056    pub fn negotiated_version(&self) -> Option<Version> {
1057        if let MetaAddrChange::UpdateConnected {
1058            negotiated_version, ..
1059        } = self
1060        {
1061            Some(*negotiated_version)
1062        } else {
1063            None
1064        }
1065    }
1066
1067    /// Returns the corresponding [`MetaAddr`] for a local listener change.
1068    ///
1069    /// This method exists so we don't have to provide an unused [`Instant`] to get a local
1070    /// listener `MetaAddr`.
1071    ///
1072    /// # Panics
1073    ///
1074    /// If this change is not a [`MetaAddrChange::NewLocal`].
1075    pub fn local_listener_into_new_meta_addr(self, local_now: DateTime32) -> MetaAddr {
1076        assert!(matches!(self, MetaAddrChange::NewLocal { .. }));
1077
1078        MetaAddr {
1079            addr: self.addr(),
1080            services: self.untrusted_services(),
1081            untrusted_last_seen: self.untrusted_last_seen(local_now),
1082            last_response: self.last_response(local_now),
1083            rtt: None,
1084            ping_sent_at: None,
1085            last_attempt: None,
1086            last_failure: None,
1087            last_connection_state: self.peer_addr_state(),
1088            is_inbound: self.is_inbound(),
1089            user_agent: None,
1090            negotiated_version: None,
1091        }
1092    }
1093
1094    /// Apply this change to a previous `MetaAddr` from the address book,
1095    /// producing a new or updated `MetaAddr`.
1096    ///
1097    /// If the change isn't valid for the `previous` address, returns `None`.
1098    #[allow(clippy::unwrap_in_result)]
1099    pub fn apply_to_meta_addr(
1100        &self,
1101        previous: impl Into<Option<MetaAddr>>,
1102        instant_now: Instant,
1103        chrono_now: chrono::DateTime<Utc>,
1104    ) -> Option<MetaAddr> {
1105        let local_now: DateTime32 = chrono_now.try_into().expect("will succeed until 2038");
1106
1107        let Some(previous) = previous.into() else {
1108            // no previous: create a new entry
1109            return Some(self.clone().into_new_meta_addr(instant_now, local_now));
1110        };
1111
1112        assert_eq!(previous.addr, self.addr(), "unexpected addr mismatch");
1113
1114        let instant_previous = max(previous.last_attempt, previous.last_failure);
1115        let local_previous = previous.last_response;
1116
1117        // Is this change potentially concurrent with the previous change?
1118        //
1119        // Since we're using saturating arithmetic, one of each pair of less than comparisons
1120        // will always be true, because subtraction saturates to zero.
1121        let change_is_concurrent = instant_previous
1122            .map(|instant_previous| {
1123                instant_previous.saturating_duration_since(instant_now)
1124                    < constants::CONCURRENT_ADDRESS_CHANGE_PERIOD
1125                    && instant_now.saturating_duration_since(instant_previous)
1126                        < constants::CONCURRENT_ADDRESS_CHANGE_PERIOD
1127            })
1128            .unwrap_or_default()
1129            || local_previous
1130                .map(|local_previous| {
1131                    local_previous.saturating_duration_since(local_now).to_std()
1132                        < constants::CONCURRENT_ADDRESS_CHANGE_PERIOD
1133                        && local_now.saturating_duration_since(local_previous).to_std()
1134                            < constants::CONCURRENT_ADDRESS_CHANGE_PERIOD
1135                })
1136                .unwrap_or_default();
1137        let change_is_out_of_order = instant_previous
1138            .map(|instant_previous| instant_previous > instant_now)
1139            .unwrap_or_default()
1140            || local_previous
1141                .map(|local_previous| local_previous > local_now)
1142                .unwrap_or_default();
1143
1144        // Is this change typically from a connection state that has more progress?
1145        let connection_has_more_progress = self
1146            .peer_addr_state()
1147            .connection_state_order(&previous.last_connection_state)
1148            == Ordering::Greater;
1149
1150        let previous_has_been_attempted = !previous.last_connection_state.is_never_attempted();
1151        let change_to_never_attempted = self.peer_addr_state().is_never_attempted();
1152        let is_misbehavior_update = self.misbehavior_score() != 0;
1153
1154        // Re-adding a failed initial peer makes it eligible for another connection attempt.
1155        // Otherwise, a failed initial peer with no last seen time is never attempted again.
1156        //
1157        // # Security
1158        //
1159        // Initial peers come from the config, the DNS seeders, or the disk cache, never
1160        // from remote peers. The previous attempt and failure times are kept, so the peer
1161        // still waits for the reconnection delay.
1162        let is_initial_peer_retry =
1163            matches!(self, NewInitial { .. }) && previous.last_connection_state == Failed;
1164
1165        // Invalid changes
1166
1167        if change_to_never_attempted
1168            && previous_has_been_attempted
1169            && !is_misbehavior_update
1170            && !is_initial_peer_retry
1171        {
1172            // Existing entry has been attempted, change is NeverAttempted
1173            // - ignore the change
1174            //
1175            // # Security
1176            //
1177            // Ignore NeverAttempted changes once we have made an attempt,
1178            // so malicious peers can't keep changing our peer connection order.
1179            return None;
1180        }
1181
1182        if change_is_out_of_order && !change_is_concurrent && !is_misbehavior_update {
1183            // Change is significantly out of order: ignore it.
1184            //
1185            // # Security
1186            //
1187            // Ignore changes that arrive out of order, if they are far enough apart.
1188            // This enforces the peer connection retry interval.
1189            return None;
1190        }
1191
1192        if change_is_concurrent
1193            && !connection_has_more_progress
1194            && !is_misbehavior_update
1195            && !is_initial_peer_retry
1196        {
1197            // Change is close together in time, and it would revert the connection to an earlier
1198            // state.
1199            //
1200            // # Security
1201            //
1202            // If the changes might have been concurrent, ignore connection states with less
1203            // progress.
1204            //
1205            // ## Sources of Concurrency
1206            //
1207            // If two changes happen close together, the async scheduler can run their change
1208            // send and apply code in any order. This includes the code that records the time of
1209            // the change. So even if a failure happens after a response message, the failure time
1210            // can be recorded before the response time code is run.
1211            //
1212            // Some machines and OSes have limited time resolution, so we can't guarantee that
1213            // two messages on the same connection will always have different times. There are
1214            // also known bugs impacting monotonic times which make them go backwards or stay
1215            // equal. For wall clock times, clock skew is an expected event, particularly with
1216            // network time server updates.
1217            //
1218            // Also, the application can fail a connection independently and simultaneously
1219            // (or slightly before) a positive update from that peer connection. We want the
1220            // application change to take priority in the address book, because the connection
1221            // state machine also prioritises failures over any other peer messages.
1222            //
1223            // ## Resolution
1224            //
1225            // In these cases, we want to apply the failure, then ignore any nearby changes that
1226            // reset the address book entry to a more appealing state. This prevents peers from
1227            // sending updates right before failing a connection, in order to make themselves more
1228            // likely to get a reconnection.
1229            //
1230            // The connection state machine order is used so that state transitions which are
1231            // typically close together are preserved. These transitions are:
1232            // - NeverAttempted*->AttemptPending->(Responded|Failed)
1233            // - Responded->Failed
1234            //
1235            // State transitions like (Responded|Failed)->AttemptPending only happen after the
1236            // reconnection timeout, so they will never be considered concurrent.
1237            return None;
1238        }
1239
1240        // Valid changes
1241
1242        if change_to_never_attempted && !previous_has_been_attempted {
1243            // Existing entry and change are both NeverAttempted
1244            // - preserve original values of all fields
1245            // - but replace None with Some
1246            //
1247            // # Security
1248            //
1249            // Preserve the original field values for NeverAttempted peers,
1250            // so malicious peers can't keep changing our peer connection order.
1251            Some(MetaAddr {
1252                addr: self.addr(),
1253                services: previous.services.or_else(|| self.untrusted_services()),
1254                untrusted_last_seen: previous
1255                    .untrusted_last_seen
1256                    .or_else(|| self.untrusted_last_seen(local_now)),
1257                // These fields are None, unless a failed initial peer was re-added.
1258                // Keeping them makes the re-added peer wait for the reconnection delay.
1259                last_response: previous.last_response,
1260                rtt: previous.rtt,
1261                ping_sent_at: previous.ping_sent_at,
1262                last_attempt: previous.last_attempt,
1263                last_failure: previous.last_failure,
1264                last_connection_state: self.peer_addr_state(),
1265                is_inbound: previous.is_inbound || self.is_inbound(),
1266                user_agent: previous.user_agent,
1267                negotiated_version: previous.negotiated_version,
1268            })
1269        } else {
1270            // Existing entry and change are both Attempt, Responded, Failed,
1271            // or the change re-adds a failed initial peer,
1272            // and the change is later, either in time or in connection progress
1273            // (this is checked above and returns None early):
1274            // - update the fields from the change
1275            Some(MetaAddr {
1276                addr: self.addr(),
1277                // Always update optional fields, unless the update is None.
1278                //
1279                // We want up-to-date services, even if they have fewer bits
1280                services: self.untrusted_services().or(previous.services),
1281                // Only NeverAttempted changes can modify the last seen field
1282                untrusted_last_seen: previous.untrusted_last_seen,
1283                // This is a wall clock time, but we already checked that responses are in order.
1284                // Even if the wall clock time has jumped, we want to use the latest time.
1285                last_response: self.last_response(local_now).or(previous.last_response),
1286                rtt: self.rtt(),
1287                ping_sent_at: self.ping_sent_at(),
1288                // These are monotonic times, we already checked the responses are in order.
1289                last_attempt: self.last_attempt(instant_now).or(previous.last_attempt),
1290                last_failure: self.last_failure(instant_now).or(previous.last_failure),
1291                // Replace the state with the updated state.
1292                last_connection_state: self.peer_addr_state(),
1293                is_inbound: previous.is_inbound || self.is_inbound(),
1294                user_agent: self.user_agent().or(previous.user_agent),
1295                negotiated_version: self.negotiated_version().or(previous.negotiated_version),
1296            })
1297        }
1298    }
1299}
1300
1301impl Ord for MetaAddr {
1302    /// `MetaAddr`s are sorted in approximate reconnection attempt order, but
1303    /// with `Responded` peers sorted first as a group.
1304    ///
1305    /// But this order should not be used for reconnection attempts: use
1306    /// [`reconnection_peers`] instead.
1307    ///
1308    /// See [`candidate_set`] for more details.
1309    ///
1310    /// [`candidate_set`]: super::peer_set::candidate_set
1311    /// [`reconnection_peers`]: crate::AddressBook::reconnection_peers
1312    fn cmp(&self, other: &Self) -> Ordering {
1313        use std::net::IpAddr::{V4, V6};
1314        use Ordering::*;
1315
1316        // First, try states that are more likely to work
1317        let more_reliable_state = self.last_connection_state.cmp(&other.last_connection_state);
1318
1319        // Then, try addresses that are more likely to be valid.
1320        // Currently, this prefers addresses with canonical Zcash ports.
1321        let more_likely_valid = self.peer_preference().cmp(&other.peer_preference());
1322
1323        // # Security and Correctness
1324        //
1325        // Prioritise older attempt times, so we try all peers in each state,
1326        // before re-trying any of them. This avoids repeatedly reconnecting to
1327        // peers that aren't working.
1328        //
1329        // Using the internal attempt time for peer ordering also minimises the
1330        // amount of information `Addrs` responses leak about Zebra's retry order.
1331
1332        // If the states are the same, try peers that we haven't tried for a while.
1333        //
1334        // Each state change updates a specific time field, and
1335        // None is less than Some(T),
1336        // so the resulting ordering for each state is:
1337        // - Responded: oldest attempts first (attempt times are required and unique)
1338        // - NeverAttempted...: recent gossiped times first (all other times are None)
1339        // - Failed: oldest attempts first (attempt times are required and unique)
1340        // - AttemptPending: oldest attempts first (attempt times are required and unique)
1341        //
1342        // We also compare the other local times, because:
1343        // - seed peers may not have an attempt time, and
1344        // - updates can be applied to the address book in any order.
1345        let older_attempt = self.last_attempt.cmp(&other.last_attempt);
1346        let older_failure = self.last_failure.cmp(&other.last_failure);
1347        let older_response = self.last_response.cmp(&other.last_response);
1348
1349        // # Security
1350        //
1351        // Compare local times before untrusted gossiped times and services.
1352        // This gives malicious peers less influence over our peer connection
1353        // order.
1354
1355        // If all local times are None, try peers that other peers have seen more recently
1356        let newer_untrusted_last_seen = self
1357            .untrusted_last_seen
1358            .cmp(&other.untrusted_last_seen)
1359            .reverse();
1360
1361        // Finally, prefer numerically larger service bit patterns
1362        //
1363        // As of June 2021, Zebra only recognises the NODE_NETWORK bit.
1364        // When making outbound connections, Zebra skips non-nodes.
1365        // So this comparison will have no impact until Zebra implements
1366        // more service features.
1367        //
1368        // None is less than Some(T), so peers with missing services are chosen last.
1369        //
1370        // TODO: order services by usefulness, not bit pattern values (#2324)
1371        //       Security: split gossiped and direct services
1372        let larger_services = self.services.cmp(&other.services);
1373
1374        // The remaining comparisons are meaningless for peer connection priority.
1375        // But they are required so that we have a total order on `MetaAddr` values:
1376        // self and other must compare as Equal iff they are equal.
1377
1378        // As a tie-breaker, compare ip and port numerically
1379        //
1380        // Since SocketAddrs are unique in the address book, these comparisons
1381        // guarantee a total, unique order.
1382        let ip_tie_breaker = match (self.addr.ip(), other.addr.ip()) {
1383            (V4(a), V4(b)) => a.octets().cmp(&b.octets()),
1384            (V6(a), V6(b)) => a.octets().cmp(&b.octets()),
1385            (V4(_), V6(_)) => Less,
1386            (V6(_), V4(_)) => Greater,
1387        };
1388        let port_tie_breaker = self.addr.port().cmp(&other.addr.port());
1389
1390        more_reliable_state
1391            .then(more_likely_valid)
1392            .then(older_attempt)
1393            .then(older_failure)
1394            .then(older_response)
1395            .then(newer_untrusted_last_seen)
1396            .then(larger_services)
1397            .then(ip_tie_breaker)
1398            .then(port_tie_breaker)
1399    }
1400}
1401
1402impl PartialOrd for MetaAddr {
1403    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1404        Some(self.cmp(other))
1405    }
1406}
1407
1408impl PartialEq for MetaAddr {
1409    fn eq(&self, other: &Self) -> bool {
1410        self.cmp(other) == Ordering::Equal
1411    }
1412}
1413
1414impl Eq for MetaAddr {}