Skip to main content

tor_netdir/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] // See arti#2556
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51
52pub mod details;
53mod err;
54#[cfg(feature = "hs-common")]
55mod hsdir_params;
56#[cfg(feature = "hs-common")]
57mod hsdir_ring;
58pub mod params;
59mod weight;
60
61#[cfg(any(test, feature = "testing"))]
62pub mod testnet;
63#[cfg(feature = "testing")]
64pub mod testprovider;
65
66use async_trait::async_trait;
67#[cfg(feature = "hs-service")]
68use itertools::chain;
69use tor_error::warn_report;
70#[cfg(feature = "hs-common")]
71use tor_linkspec::OwnedCircTarget;
72use tor_linkspec::{
73    ChanTarget, DirectChanMethodsHelper, HasAddrs, HasRelayIds, RelayIdRef, RelayIdType,
74};
75use tor_llcrypto as ll;
76use tor_llcrypto::pk::{ed25519::Ed25519Identity, rsa::RsaIdentity};
77use tor_netdoc::doc::microdesc::{MdDigest, MicrodescAndHash};
78use tor_netdoc::doc::netstatus::{self, MdConsensus, MdRouterStatus};
79#[cfg(feature = "hs-common")]
80use {hsdir_ring::HsDirRing, std::iter};
81
82use derive_more::{From, Into};
83use futures::{StreamExt, stream::BoxStream};
84use num_enum::{IntoPrimitive, TryFromPrimitive};
85use rand::seq::{IndexedRandom as _, SliceRandom as _, WeightError};
86use serde::Deserialize;
87use std::collections::HashMap;
88use std::net::IpAddr;
89use std::ops::Deref;
90use std::sync::Arc;
91use std::time::SystemTime;
92use strum::{EnumCount, EnumIter};
93use tracing::warn;
94use typed_index_collections::{TiSlice, TiVec};
95
96#[cfg(feature = "hs-common")]
97use {
98    itertools::Itertools,
99    std::collections::HashSet,
100    std::result::Result as StdResult,
101    tor_error::{Bug, internal},
102    tor_hscrypto::{pk::HsBlindId, time::TimePeriod},
103    tor_linkspec::{OwnedChanTargetBuilder, verbatim::VerbatimLinkSpecCircTarget},
104    tor_llcrypto::pk::curve25519,
105};
106
107pub use err::Error;
108pub use weight::WeightRole;
109/// A Result using the Error type from the tor-netdir crate
110pub type Result<T> = std::result::Result<T, Error>;
111
112#[cfg(feature = "hs-common")]
113pub use err::{OnionDirLookupError, VerbatimCircTargetDecodeError};
114
115use params::NetParameters;
116#[cfg(feature = "geoip")]
117use tor_geoip::{CountryCode, GeoipDb, HasCountryCode};
118
119#[cfg(feature = "hs-common")]
120pub use hsdir_params::HsDirParams;
121
122/// Index into the consensus relays
123///
124/// This is an index into the list of relays returned by
125/// [`.c_relays()`](ConsensusRelays::c_relays)
126/// (on the corresponding consensus or netdir).
127///
128/// This is just a `usize` inside, but using a newtype prevents getting a relay index
129/// confused with other kinds of slice indices or counts.
130///
131/// If you are in a part of the code which needs to work with multiple consensuses,
132/// the typechecking cannot tell if you try to index into the wrong consensus.
133#[derive(Debug, From, Into, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
134pub(crate) struct RouterStatusIdx(usize);
135
136/// Extension trait to provide index-type-safe `.c_relays()` method
137//
138// TODO: Really it would be better to have MdConsensns::relays() return TiSlice,
139// but that would be an API break there.
140pub(crate) trait ConsensusRelays {
141    /// Obtain the list of relays in the consensus
142    //
143    fn c_relays(&self) -> &TiSlice<RouterStatusIdx, MdRouterStatus>;
144}
145impl ConsensusRelays for MdConsensus {
146    fn c_relays(&self) -> &TiSlice<RouterStatusIdx, MdRouterStatus> {
147        TiSlice::from_ref(MdConsensus::relays(self))
148    }
149}
150impl ConsensusRelays for NetDir {
151    fn c_relays(&self) -> &TiSlice<RouterStatusIdx, MdRouterStatus> {
152        self.consensus.c_relays()
153    }
154}
155
156/// Configuration for determining when two relays have addresses "too close" in
157/// the network.
158///
159/// Used by `Relay::low_level_details().in_same_subnet()`.
160#[derive(Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
161#[serde(deny_unknown_fields)]
162pub struct SubnetConfig {
163    /// Consider IPv4 nodes in the same /x to be the same family.
164    ///
165    /// If this value is 0, all nodes with IPv4 addresses will be in the
166    /// same family.  If this value is above 32, then no nodes will be
167    /// placed im the same family based on their IPv4 addresses.
168    subnets_family_v4: u8,
169    /// Consider IPv6 nodes in the same /x to be the same family.
170    ///
171    /// If this value is 0, all nodes with IPv6 addresses will be in the
172    /// same family.  If this value is above 128, then no nodes will be
173    /// placed im the same family based on their IPv6 addresses.
174    subnets_family_v6: u8,
175}
176
177impl Default for SubnetConfig {
178    fn default() -> Self {
179        Self::new(16, 32)
180    }
181}
182
183impl SubnetConfig {
184    /// Construct a new SubnetConfig from a pair of bit prefix lengths.
185    ///
186    /// The values are clamped to the appropriate ranges if they are
187    /// out-of-bounds.
188    pub fn new(subnets_family_v4: u8, subnets_family_v6: u8) -> Self {
189        Self {
190            subnets_family_v4,
191            subnets_family_v6,
192        }
193    }
194
195    /// Construct a new SubnetConfig such that addresses are not in the same
196    /// family with anything--not even with themselves.
197    pub fn no_addresses_match() -> SubnetConfig {
198        SubnetConfig {
199            subnets_family_v4: 33,
200            subnets_family_v6: 129,
201        }
202    }
203
204    /// Return true if the two addresses in the same subnet, according to this
205    /// configuration.
206    pub fn addrs_in_same_subnet(&self, a: &IpAddr, b: &IpAddr) -> bool {
207        match (a, b) {
208            (IpAddr::V4(a), IpAddr::V4(b)) => {
209                let bits = self.subnets_family_v4;
210                if bits > 32 {
211                    return false;
212                }
213                let a = u32::from_be_bytes(a.octets());
214                let b = u32::from_be_bytes(b.octets());
215                (a >> (32 - bits)) == (b >> (32 - bits))
216            }
217            (IpAddr::V6(a), IpAddr::V6(b)) => {
218                let bits = self.subnets_family_v6;
219                if bits > 128 {
220                    return false;
221                }
222                let a = u128::from_be_bytes(a.octets());
223                let b = u128::from_be_bytes(b.octets());
224                (a >> (128 - bits)) == (b >> (128 - bits))
225            }
226            _ => false,
227        }
228    }
229
230    /// Return true if any of the addresses in `a` shares a subnet with any of
231    /// the addresses in `b`, according to this configuration.
232    pub fn any_addrs_in_same_subnet<T, U>(&self, a: &T, b: &U) -> bool
233    where
234        T: tor_linkspec::HasAddrs,
235        U: tor_linkspec::HasAddrs,
236    {
237        a.addrs().any(|aa| {
238            b.addrs()
239                .any(|bb| self.addrs_in_same_subnet(&aa.ip(), &bb.ip()))
240        })
241    }
242
243    /// Return a new subnet configuration that is the union of `self` and
244    /// `other`.
245    ///
246    /// That is, return a subnet configuration that puts all addresses in the
247    /// same subnet if and only if at least one of `self` and `other` would put
248    /// them in the same subnet.
249    pub fn union(&self, other: &Self) -> Self {
250        use std::cmp::min;
251        Self {
252            subnets_family_v4: min(self.subnets_family_v4, other.subnets_family_v4),
253            subnets_family_v6: min(self.subnets_family_v6, other.subnets_family_v6),
254        }
255    }
256}
257
258/// Configuration for which listed family information to use when deciding
259/// whether relays belong to the same family.
260///
261/// Derived from network parameters.
262#[derive(Clone, Copy, Debug)]
263pub struct FamilyRules {
264    /// If true, we use family information from lists of family members.
265    use_family_lists: bool,
266    /// If true, we use family information from lists of family IDs and from family certs.
267    use_family_ids: bool,
268}
269
270impl<'a> From<&'a NetParameters> for FamilyRules {
271    fn from(params: &'a NetParameters) -> Self {
272        FamilyRules {
273            use_family_lists: bool::from(params.use_family_lists),
274            use_family_ids: bool::from(params.use_family_ids),
275        }
276    }
277}
278
279impl FamilyRules {
280    /// Return a `FamilyRules` that will use all recognized kinds of family information.
281    pub fn all_family_info() -> Self {
282        Self {
283            use_family_lists: true,
284            use_family_ids: true,
285        }
286    }
287
288    /// Return a `FamilyRules` that will ignore all family information declared by relays.
289    pub fn ignore_declared_families() -> Self {
290        Self {
291            use_family_lists: false,
292            use_family_ids: false,
293        }
294    }
295
296    /// Configure this `FamilyRules` to use (or not use) family information from
297    /// lists of family members.
298    pub fn use_family_lists(&mut self, val: bool) -> &mut Self {
299        self.use_family_lists = val;
300        self
301    }
302
303    /// Configure this `FamilyRules` to use (or not use) family information from
304    /// family IDs and family certs.
305    pub fn use_family_ids(&mut self, val: bool) -> &mut Self {
306        self.use_family_ids = val;
307        self
308    }
309
310    /// Return a `FamilyRules` that will look at every source of information
311    /// requested by `self` or by `other`.
312    pub fn union(&self, other: &Self) -> Self {
313        Self {
314            use_family_lists: self.use_family_lists || other.use_family_lists,
315            use_family_ids: self.use_family_ids || other.use_family_ids,
316        }
317    }
318}
319
320/// An opaque type representing the weight with which a relay or set of
321/// relays will be selected for a given role.
322///
323/// Most users should ignore this type, and just use pick_relay instead.
324#[derive(
325    Copy,
326    Clone,
327    Debug,
328    derive_more::Add,
329    derive_more::Sum,
330    derive_more::AddAssign,
331    Eq,
332    PartialEq,
333    Ord,
334    PartialOrd,
335)]
336pub struct RelayWeight(u64);
337
338impl RelayWeight {
339    /// Try to divide this weight by `rhs`.
340    ///
341    /// Return a ratio on success, or None on division-by-zero.
342    pub fn checked_div(&self, rhs: RelayWeight) -> Option<f64> {
343        if rhs.0 == 0 {
344            None
345        } else {
346            Some((self.0 as f64) / (rhs.0 as f64))
347        }
348    }
349
350    /// Compute a ratio `frac` of this weight.
351    ///
352    /// Return None if frac is less than zero, since negative weights
353    /// are impossible.
354    pub fn ratio(&self, frac: f64) -> Option<RelayWeight> {
355        let product = (self.0 as f64) * frac;
356        if product >= 0.0 && product.is_finite() {
357            Some(RelayWeight(product as u64))
358        } else {
359            None
360        }
361    }
362}
363
364impl From<u64> for RelayWeight {
365    fn from(val: u64) -> Self {
366        RelayWeight(val)
367    }
368}
369
370/// An operation for which we might be requesting a hidden service directory.
371#[derive(Copy, Clone, Debug, PartialEq)]
372// TODO: make this pub(crate) once NetDir::hs_dirs is removed
373#[non_exhaustive]
374pub enum HsDirOp {
375    /// Uploading an onion service descriptor.
376    #[cfg(feature = "hs-service")]
377    Upload,
378    /// Downloading an onion service descriptor.
379    Download,
380}
381
382/// A view of the Tor directory, suitable for use in building circuits.
383///
384/// Abstractly, a [`NetDir`] is a set of usable public [`Relay`]s, each of which
385/// has its own properties, identity, and correct weighted probability for use
386/// under different circumstances.
387///
388/// A [`NetDir`] is constructed by making a [`PartialNetDir`] from a consensus
389/// document, and then adding enough microdescriptors to that `PartialNetDir` so
390/// that it can be used to build paths. (Thus, if you have a NetDir, it is
391/// definitely adequate to build paths.)
392///
393/// # "Usable" relays
394///
395/// Many methods on NetDir are defined in terms of <a name="usable">"Usable"</a> relays.  Unless
396/// otherwise stated, a relay is "usable" if it is listed in the consensus,
397/// if we have full directory information for that relay (including a
398/// microdescriptor), and if that relay does not have any flags indicating that
399/// we should never use it. (Currently, `NoEdConsensus` is the only such flag.)
400///
401/// # Limitations
402///
403/// The current NetDir implementation assumes fairly strongly that every relay
404/// has an Ed25519 identity and an RSA identity, that the consensus is indexed
405/// by RSA identities, and that the Ed25519 identities are stored in
406/// microdescriptors.
407///
408/// If these assumptions someday change, then we'll have to revise the
409/// implementation.
410#[derive(Debug, Clone)]
411pub struct NetDir {
412    /// A microdescriptor consensus that lists the members of the network,
413    /// and maps each one to a 'microdescriptor' that has more information
414    /// about it
415    consensus: Arc<MdConsensus>,
416    /// A map from keys to integer values, distributed in the consensus,
417    /// and clamped to certain defaults.
418    params: NetParameters,
419    /// Map from routerstatus index, to that routerstatus's microdescriptor (if we have one.)
420    mds: TiVec<RouterStatusIdx, Option<Arc<MicrodescAndHash>>>,
421    /// Map from SHA256 of _missing_ microdescriptors to the index of their
422    /// corresponding routerstatus.
423    rsidx_by_missing: HashMap<MdDigest, RouterStatusIdx>,
424    /// Map from ed25519 identity to index of the routerstatus.
425    ///
426    /// Note that we don't know the ed25519 identity of a relay until
427    /// we get the microdescriptor for it, so this won't be filled in
428    /// until we get the microdescriptors.
429    ///
430    /// # Implementation note
431    ///
432    /// For this field, and for `rsidx_by_rsa`,
433    /// it might be cool to have references instead.
434    /// But that would make this into a self-referential structure,
435    /// which isn't possible in safe rust.
436    rsidx_by_ed: HashMap<Ed25519Identity, RouterStatusIdx>,
437    /// Map from RSA identity to index of the routerstatus.
438    ///
439    /// This is constructed at the same time as the NetDir object, so it
440    /// can be immutable.
441    rsidx_by_rsa: Arc<HashMap<RsaIdentity, RouterStatusIdx>>,
442
443    /// Hash ring(s) describing the onion service directory.
444    ///
445    /// This is empty in a PartialNetDir, and is filled in before the NetDir is
446    /// built.
447    //
448    // TODO hs: It is ugly to have this exist in a partially constructed state
449    // in a PartialNetDir.
450    // Ideally, a PartialNetDir would contain only an HsDirs<HsDirParams>,
451    // or perhaps nothing at all, here.
452    #[cfg(feature = "hs-common")]
453    hsdir_rings: Arc<HsDirs<HsDirRing>>,
454
455    /// Weight values to apply to a given relay when deciding how frequently
456    /// to choose it for a given role.
457    weights: weight::WeightSet,
458
459    #[cfg(feature = "geoip")]
460    /// Country codes for each router in our consensus.
461    ///
462    /// This is indexed by the `RouterStatusIdx` (i.e. a router idx of zero has
463    /// the country code at position zero in this array).
464    country_codes: Vec<Option<CountryCode>>,
465}
466
467/// Collection of hidden service directories (or parameters for them)
468///
469/// In [`NetDir`] this is used to store the actual hash rings.
470/// (But, in a NetDir in a [`PartialNetDir`], it contains [`HsDirRing`]s
471/// where only the `params` are populated, and the `ring` is empty.)
472///
473/// This same generic type is used as the return type from
474/// [`HsDirParams::compute`](HsDirParams::compute),
475/// where it contains the *parameters* for the primary and secondary rings.
476#[derive(Debug, Clone)]
477#[cfg(feature = "hs-common")]
478pub(crate) struct HsDirs<D> {
479    /// The current ring
480    ///
481    /// It corresponds to the time period containing the `valid-after` time in
482    /// the consensus. Its SRV is whatever SRV was most current at the time when
483    /// that time period began.
484    ///
485    /// This is the hash ring that we should use whenever we are fetching an
486    /// onion service descriptor.
487    current: D,
488
489    /// Secondary rings (based on the parameters for the previous and next time periods)
490    ///
491    /// Onion services upload to positions on these ring as well, based on how
492    /// far into the current time period this directory is, so that
493    /// not-synchronized clients can still find their descriptor.
494    ///
495    /// Note that with the current (2023) network parameters, with
496    /// `hsdir_interval = SRV lifetime = 24 hours` at most one of these
497    /// secondary rings will be active at a time.  We have two here in order
498    /// to conform with a more flexible regime in proposal 342.
499    //
500    // TODO: hs clients never need this; so I've made it not-present for them.
501    // But does that risk too much with respect to side channels?
502    //
503    // TODO: Perhaps we should refactor this so that it is clear that these
504    // are immutable?  On the other hand, the documentation for this type
505    // declares that it is immutable, so we are likely okay.
506    //
507    // TODO: this `Vec` is only ever 0,1,2 elements.
508    // Maybe it should be an ArrayVec or something.
509    #[cfg(feature = "hs-service")]
510    secondary: Vec<D>,
511}
512
513#[cfg(feature = "hs-common")]
514impl<D> HsDirs<D> {
515    /// Convert an `HsDirs<D>` to `HsDirs<D2>` by mapping each contained `D`
516    pub(crate) fn map<D2>(self, mut f: impl FnMut(D) -> D2) -> HsDirs<D2> {
517        HsDirs {
518            current: f(self.current),
519            #[cfg(feature = "hs-service")]
520            secondary: self.secondary.into_iter().map(f).collect(),
521        }
522    }
523
524    /// Iterate over some of the contained hsdirs, according to `secondary`
525    ///
526    /// The current ring is always included.
527    /// Secondary rings are included iff `secondary` and the `hs-service` feature is enabled.
528    fn iter_filter_secondary(&self, secondary: bool) -> impl Iterator<Item = &D> {
529        let i = iter::once(&self.current);
530
531        // With "hs-service" disabled, there are no secondary rings,
532        // so we don't care.
533        let _ = secondary;
534
535        #[cfg(feature = "hs-service")]
536        let i = chain!(i, self.secondary.iter().filter(move |_| secondary));
537
538        i
539    }
540
541    /// Iterate over all the contained hsdirs
542    pub(crate) fn iter(&self) -> impl Iterator<Item = &D> {
543        self.iter_filter_secondary(true)
544    }
545
546    /// Iterate over the hsdirs relevant for `op`
547    pub(crate) fn iter_for_op(&self, op: HsDirOp) -> impl Iterator<Item = &D> {
548        self.iter_filter_secondary(match op {
549            #[cfg(feature = "hs-service")]
550            HsDirOp::Upload => true,
551            HsDirOp::Download => false,
552        })
553    }
554}
555
556/// An event that a [`NetDirProvider`] can broadcast to indicate that a change in
557/// the status of its directory.
558#[derive(
559    Debug, Clone, Copy, PartialEq, Eq, EnumIter, EnumCount, IntoPrimitive, TryFromPrimitive,
560)]
561#[non_exhaustive]
562#[repr(u16)]
563pub enum DirEvent {
564    /// A new consensus has been received, and has enough information to be
565    /// used.
566    ///
567    /// This event is also broadcast when a new set of consensus parameters is
568    /// available, even if that set of parameters comes from a configuration
569    /// change rather than from the latest consensus.
570    NewConsensus,
571
572    /// New descriptors have been received for the current consensus.
573    ///
574    /// (This event is _not_ broadcast when receiving new descriptors for a
575    /// consensus which is not yet ready to replace the current consensus.)
576    NewDescriptors,
577
578    /// We have received updated recommendations and requirements
579    /// for which subprotocols we should have to use the network.
580    NewProtocolRecommendation,
581}
582
583/// The network directory provider is shutting down without giving us the
584/// netdir we asked for.
585#[derive(Clone, Copy, Debug, thiserror::Error)]
586#[error("Network directory provider is shutting down")]
587#[non_exhaustive]
588pub struct NetdirProviderShutdown;
589
590impl tor_error::HasKind for NetdirProviderShutdown {
591    fn kind(&self) -> tor_error::ErrorKind {
592        tor_error::ErrorKind::ArtiShuttingDown
593    }
594}
595
596/// How "timely" must a network directory be?
597///
598/// This enum is used as an argument when requesting a [`NetDir`] object from
599/// [`NetDirProvider`] and other APIs, to specify how recent the information
600/// must be in order to be useful.
601#[derive(Copy, Clone, Eq, PartialEq, Debug)]
602#[allow(clippy::exhaustive_enums)]
603pub enum Timeliness {
604    /// The network directory must be strictly timely.
605    ///
606    /// That is, it must be based on a consensus that valid right now, with no
607    /// tolerance for skew or consensus problems.
608    ///
609    /// Avoid using this option if you could use [`Timeliness::Timely`] instead.
610    Strict,
611    /// The network directory must be roughly timely.
612    ///
613    /// This is, it must be based on a consensus that is not _too_ far in the
614    /// future, and not _too_ far in the past.
615    ///
616    /// (The tolerances for "too far" will depend on configuration.)
617    ///
618    /// This is almost always the option that you want to use.
619    Timely,
620    /// Any network directory is permissible, regardless of how untimely.
621    ///
622    /// Avoid using this option if you could use [`Timeliness::Timely`] instead.
623    Unchecked,
624}
625
626/// An object that can provide [`NetDir`]s, as well as inform consumers when
627/// they might have changed.
628///
629/// It is the responsibility of the implementor of `NetDirProvider`
630/// to try to obtain an up-to-date `NetDir`,
631/// and continuously to maintain and update it.
632///
633/// In usual configurations, Arti uses `tor_dirmgr::DirMgr`
634/// as its `NetDirProvider`.
635#[async_trait]
636pub trait NetDirProvider: UpcastArcNetDirProvider + Send + Sync {
637    /// Return a network directory that's live according to the provided
638    /// `timeliness`.
639    fn netdir(&self, timeliness: Timeliness) -> Result<Arc<NetDir>>;
640
641    /// Return a reasonable netdir for general usage.
642    ///
643    /// This is an alias for
644    /// [`NetDirProvider::netdir`]`(`[`Timeliness::Timely`]`)`.
645    fn timely_netdir(&self) -> Result<Arc<NetDir>> {
646        self.netdir(Timeliness::Timely)
647    }
648
649    /// Return a new asynchronous stream that will receive notification
650    /// whenever the consensus has changed.
651    ///
652    /// Multiple events may be batched up into a single item: each time
653    /// this stream yields an event, all you can assume is that the event has
654    /// occurred at least once.
655    fn events(&self) -> BoxStream<'static, DirEvent>;
656
657    /// Return the latest network parameters.
658    ///
659    /// If we have no directory, return a reasonable set of defaults.
660    fn params(&self) -> Arc<dyn AsRef<NetParameters>>;
661
662    /// Get a NetDir from `provider`, waiting until one exists.
663    async fn wait_for_netdir(
664        &self,
665        timeliness: Timeliness,
666    ) -> std::result::Result<Arc<NetDir>, NetdirProviderShutdown> {
667        if let Ok(nd) = self.netdir(timeliness) {
668            return Ok(nd);
669        }
670
671        let mut stream = self.events();
672        loop {
673            // We need to retry `self.netdir()` before waiting for any stream events, to
674            // avoid deadlock.
675            //
676            // We ignore all errors here: they can all potentially be fixed by
677            // getting a fresh consensus, and they will all get warned about
678            // by the NetDirProvider itself.
679            if let Ok(nd) = self.netdir(timeliness) {
680                return Ok(nd);
681            }
682            match stream.next().await {
683                Some(_) => {}
684                None => {
685                    return Err(NetdirProviderShutdown);
686                }
687            }
688        }
689    }
690
691    /// Wait until `provider` lists `target`.
692    ///
693    /// NOTE: This might potentially wait indefinitely, if `target` is never actually
694    /// becomes listed in the directory.  It will exit if the `NetDirProvider` shuts down.
695    async fn wait_for_netdir_to_list(
696        &self,
697        target: &tor_linkspec::RelayIds,
698        timeliness: Timeliness,
699    ) -> std::result::Result<(), NetdirProviderShutdown> {
700        let mut events = self.events();
701        loop {
702            // See if the desired relay is in the netdir.
703            //
704            // We do this before waiting for any events, to avoid race conditions.
705            {
706                let netdir = self.wait_for_netdir(timeliness).await?;
707                if netdir.ids_listed(target) == Some(true) {
708                    return Ok(());
709                }
710                // If we reach this point, then ids_listed returned `Some(false)`,
711                // meaning "This relay is definitely not in the current directory";
712                // or it returned `None`, meaning "waiting for more information
713                // about this network directory.
714                // In both cases, it's reasonable to just wait for another netdir
715                // event and try again.
716            }
717            // We didn't find the relay; wait for the provider to have a new netdir
718            // or more netdir information.
719            if events.next().await.is_none() {
720                // The event stream is closed; the provider has shut down.
721                return Err(NetdirProviderShutdown);
722            }
723        }
724    }
725
726    /// Return the latest set of recommended and required protocols, if there is one.
727    ///
728    /// This may be more recent (or more available) than this provider's associated NetDir.
729    fn protocol_statuses(&self) -> Option<(SystemTime, Arc<netstatus::ProtoStatuses>)>;
730}
731
732#[async_trait]
733impl<T> NetDirProvider for Arc<T>
734where
735    T: NetDirProvider,
736{
737    fn netdir(&self, timeliness: Timeliness) -> Result<Arc<NetDir>> {
738        self.deref().netdir(timeliness)
739    }
740
741    fn timely_netdir(&self) -> Result<Arc<NetDir>> {
742        self.deref().timely_netdir()
743    }
744
745    fn events(&self) -> BoxStream<'static, DirEvent> {
746        self.deref().events()
747    }
748
749    fn params(&self) -> Arc<dyn AsRef<NetParameters>> {
750        self.deref().params()
751    }
752
753    async fn wait_for_netdir(
754        &self,
755        timeliness: Timeliness,
756    ) -> std::result::Result<Arc<NetDir>, NetdirProviderShutdown> {
757        self.deref().wait_for_netdir(timeliness).await
758    }
759
760    async fn wait_for_netdir_to_list(
761        &self,
762        target: &tor_linkspec::RelayIds,
763        timeliness: Timeliness,
764    ) -> std::result::Result<(), NetdirProviderShutdown> {
765        self.deref()
766            .wait_for_netdir_to_list(target, timeliness)
767            .await
768    }
769
770    fn protocol_statuses(&self) -> Option<(SystemTime, Arc<netstatus::ProtoStatuses>)> {
771        self.deref().protocol_statuses()
772    }
773}
774
775/// Helper trait: allows any `Arc<X>` to be upcast to a `Arc<dyn
776/// NetDirProvider>` if X is an implementation or supertrait of NetDirProvider.
777///
778/// This trait exists to work around a limitation in rust: when trait upcasting
779/// coercion is stable, this will be unnecessary.
780///
781/// The Rust tracking issue is <https://github.com/rust-lang/rust/issues/65991>.
782pub trait UpcastArcNetDirProvider {
783    /// Return a view of this object as an `Arc<dyn NetDirProvider>`
784    fn upcast_arc<'a>(self: Arc<Self>) -> Arc<dyn NetDirProvider + 'a>
785    where
786        Self: 'a;
787}
788
789impl<T> UpcastArcNetDirProvider for T
790where
791    T: NetDirProvider + Sized,
792{
793    fn upcast_arc<'a>(self: Arc<Self>) -> Arc<dyn NetDirProvider + 'a>
794    where
795        Self: 'a,
796    {
797        self
798    }
799}
800
801impl AsRef<NetParameters> for NetDir {
802    fn as_ref(&self) -> &NetParameters {
803        self.params()
804    }
805}
806
807/// A partially build NetDir -- it can't be unwrapped until it has
808/// enough information to build safe paths.
809#[derive(Debug, Clone)]
810pub struct PartialNetDir {
811    /// The netdir that's under construction.
812    netdir: NetDir,
813
814    /// The previous netdir, if we had one
815    ///
816    /// Used as a cache, so we can reuse information
817    #[cfg(feature = "hs-common")]
818    prev_netdir: Option<Arc<NetDir>>,
819}
820
821/// A view of a relay on the Tor network, suitable for building circuits.
822// TODO: This should probably be a more specific struct, with a trait
823// that implements it.
824#[derive(Clone)]
825pub struct Relay<'a> {
826    /// A router descriptor for this relay.
827    rs: &'a netstatus::MdRouterStatus,
828    /// A microdescriptor for this relay.
829    md: &'a MicrodescAndHash,
830    /// The country code this relay is in, if we know one.
831    #[cfg(feature = "geoip")]
832    cc: Option<CountryCode>,
833}
834
835/// A relay that we haven't checked for validity or usability in
836/// routing.
837#[derive(Debug)]
838pub struct UncheckedRelay<'a> {
839    /// A router descriptor for this relay.
840    rs: &'a netstatus::MdRouterStatus,
841    /// A microdescriptor for this relay, if there is one.
842    md: Option<&'a MicrodescAndHash>,
843    /// The country code this relay is in, if we know one.
844    #[cfg(feature = "geoip")]
845    cc: Option<CountryCode>,
846}
847
848/// A partial or full network directory that we can download
849/// microdescriptors for.
850pub trait MdReceiver {
851    /// Return an iterator over the digests for all of the microdescriptors
852    /// that this netdir is missing.
853    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_>;
854    /// Add a microdescriptor to this netdir, if it was wanted.
855    ///
856    /// Return true if it was indeed wanted.
857    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool;
858    /// Return the number of missing microdescriptors.
859    fn n_missing(&self) -> usize;
860}
861
862impl PartialNetDir {
863    /// Create a new PartialNetDir with a given consensus, and no
864    /// microdescriptors loaded.
865    ///
866    /// If `replacement_params` is provided, override network parameters from
867    /// the consensus with those from `replacement_params`.
868    pub fn new(
869        consensus: MdConsensus,
870        replacement_params: Option<&netstatus::NetParams<i32>>,
871    ) -> Self {
872        Self::new_inner(
873            consensus,
874            replacement_params,
875            #[cfg(feature = "geoip")]
876            None,
877        )
878    }
879
880    /// Create a new PartialNetDir with GeoIP support.
881    ///
882    /// This does the same thing as `new()`, except the provided GeoIP database is used to add
883    /// country codes to relays.
884    #[cfg(feature = "geoip")]
885    pub fn new_with_geoip(
886        consensus: MdConsensus,
887        replacement_params: Option<&netstatus::NetParams<i32>>,
888        geoip_db: &GeoipDb,
889    ) -> Self {
890        Self::new_inner(consensus, replacement_params, Some(geoip_db))
891    }
892
893    /// Implementation of the `new()` functions.
894    fn new_inner(
895        consensus: MdConsensus,
896        replacement_params: Option<&netstatus::NetParams<i32>>,
897        #[cfg(feature = "geoip")] geoip_db: Option<&GeoipDb>,
898    ) -> Self {
899        let mut params = NetParameters::default();
900
901        // (We ignore unrecognized options here, since they come from
902        // the consensus, and we don't expect to recognize everything
903        // there.)
904        let _ = params.saturating_update(consensus.params().iter());
905
906        // Now see if the user has any parameters to override.
907        // (We have to do this now, or else changes won't be reflected in our
908        // weights.)
909        if let Some(replacement) = replacement_params {
910            for u in params.saturating_update(replacement.iter()) {
911                warn!("Unrecognized option: override_net_params.{}", u);
912            }
913        }
914
915        // Compute the weights we'll want to use for these relays.
916        let weights = weight::WeightSet::from_consensus(&consensus, &params);
917
918        let n_relays = consensus.c_relays().len();
919
920        let rsidx_by_missing = consensus
921            .c_relays()
922            .iter_enumerated()
923            .map(|(rsidx, rs)| (*rs.md_digest(), rsidx))
924            .collect();
925
926        let rsidx_by_rsa = consensus
927            .c_relays()
928            .iter_enumerated()
929            .map(|(rsidx, rs)| (*rs.rsa_identity(), rsidx))
930            .collect();
931
932        #[cfg(feature = "geoip")]
933        let country_codes = if let Some(db) = geoip_db {
934            consensus
935                .c_relays()
936                .iter()
937                .map(|rs| {
938                    db.lookup_country_code_multi(rs.addrs().map(|x| x.ip()))
939                        .cloned()
940                })
941                .collect()
942        } else {
943            Default::default()
944        };
945
946        #[cfg(feature = "hs-common")]
947        let hsdir_rings = Arc::new({
948            let params = HsDirParams::compute(&consensus, &params).expect("Invalid consensus!");
949            // TODO: It's a bit ugly to use expect above, but this function does
950            // not return a Result. On the other hand, the error conditions under which
951            // HsDirParams::compute can return Err are _very_ narrow and hard to
952            // hit; see documentation in that function.  As such, we probably
953            // don't need to have this return a Result.
954
955            params.map(HsDirRing::empty_from_params)
956        });
957
958        let netdir = NetDir {
959            consensus: Arc::new(consensus),
960            params,
961            mds: vec![None; n_relays].into(),
962            rsidx_by_missing,
963            rsidx_by_rsa: Arc::new(rsidx_by_rsa),
964            rsidx_by_ed: HashMap::with_capacity(n_relays),
965            #[cfg(feature = "hs-common")]
966            hsdir_rings,
967            weights,
968            #[cfg(feature = "geoip")]
969            country_codes,
970        };
971
972        PartialNetDir {
973            netdir,
974            #[cfg(feature = "hs-common")]
975            prev_netdir: None,
976        }
977    }
978
979    /// Return the declared lifetime of this PartialNetDir.
980    pub fn lifetime(&self) -> &netstatus::Lifetime {
981        self.netdir.lifetime()
982    }
983
984    /// Record a previous netdir, which can be used for reusing cached information
985    //
986    // Fills in as many missing microdescriptors as possible in this
987    // netdir, using the microdescriptors from the previous netdir.
988    //
989    // With HS enabled, stores the netdir for reuse of relay hash ring index values.
990    #[allow(clippy::needless_pass_by_value)] // prev might, or might not, be stored
991    pub fn fill_from_previous_netdir(&mut self, prev: Arc<NetDir>) {
992        for md in prev.mds.iter().flatten() {
993            self.netdir.add_arc_microdesc(md.clone());
994        }
995
996        #[cfg(feature = "hs-common")]
997        {
998            self.prev_netdir = Some(prev);
999        }
1000    }
1001
1002    /// Compute the hash ring(s) for this NetDir
1003    #[cfg(feature = "hs-common")]
1004    fn compute_rings(&mut self) {
1005        let params = HsDirParams::compute(&self.netdir.consensus, &self.netdir.params)
1006            .expect("Invalid consensus");
1007        // TODO: see TODO by similar expect in new()
1008
1009        self.netdir.hsdir_rings =
1010            Arc::new(params.map(|params| {
1011                HsDirRing::compute(params, &self.netdir, self.prev_netdir.as_deref())
1012            }));
1013    }
1014
1015    /// Return true if this are enough information in this directory
1016    /// to build multihop paths.
1017    pub fn have_enough_paths(&self) -> bool {
1018        self.netdir.have_enough_paths()
1019    }
1020    /// If this directory has enough information to build multihop
1021    /// circuits, return it.
1022    pub fn unwrap_if_sufficient(
1023        #[allow(unused_mut)] mut self,
1024    ) -> std::result::Result<NetDir, PartialNetDir> {
1025        if self.netdir.have_enough_paths() {
1026            #[cfg(feature = "hs-common")]
1027            self.compute_rings();
1028            Ok(self.netdir)
1029        } else {
1030            Err(self)
1031        }
1032    }
1033}
1034
1035impl MdReceiver for PartialNetDir {
1036    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_> {
1037        self.netdir.missing_microdescs()
1038    }
1039    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool {
1040        self.netdir.add_microdesc(md)
1041    }
1042    fn n_missing(&self) -> usize {
1043        self.netdir.n_missing()
1044    }
1045}
1046
1047impl NetDir {
1048    /// Return the declared lifetime of this NetDir.
1049    pub fn lifetime(&self) -> &netstatus::Lifetime {
1050        self.consensus.lifetime()
1051    }
1052
1053    /// Add `md` to this NetDir.
1054    ///
1055    /// Return true if we wanted it, and false otherwise.
1056    fn add_arc_microdesc(&mut self, md: Arc<MicrodescAndHash>) -> bool {
1057        if let Some(rsidx) = self.rsidx_by_missing.remove(md.digest()) {
1058            assert_eq!(self.c_relays()[rsidx].md_digest(), md.digest());
1059
1060            // There should never be two approved MDs in the same
1061            // consensus listing the same ID... but if there is,
1062            // we'll let the most recent one win.
1063            self.rsidx_by_ed.insert(*md.ed25519_id(), rsidx);
1064
1065            // Happy path: we did indeed want this one.
1066            self.mds[rsidx] = Some(md);
1067
1068            // Save some space in the missing-descriptor list.
1069            if self.rsidx_by_missing.len() < self.rsidx_by_missing.capacity() / 4 {
1070                self.rsidx_by_missing.shrink_to_fit();
1071            }
1072
1073            return true;
1074        }
1075
1076        // Either we already had it, or we never wanted it at all.
1077        false
1078    }
1079
1080    /// Construct a (possibly invalid) Relay object from a routerstatus and its
1081    /// index within the consensus.
1082    fn relay_from_rs_and_rsidx<'a>(
1083        &'a self,
1084        rs: &'a netstatus::MdRouterStatus,
1085        rsidx: RouterStatusIdx,
1086    ) -> UncheckedRelay<'a> {
1087        debug_assert_eq!(self.c_relays()[rsidx].rsa_identity(), rs.rsa_identity());
1088        let md = self.mds[rsidx].as_deref();
1089        if let Some(md) = md {
1090            debug_assert_eq!(rs.md_digest(), md.digest());
1091        }
1092
1093        UncheckedRelay {
1094            rs,
1095            md,
1096            #[cfg(feature = "geoip")]
1097            cc: self.country_codes.get(rsidx.0).copied().flatten(),
1098        }
1099    }
1100
1101    /// Return the value of the hsdir_n_replicas param.
1102    #[cfg(feature = "hs-common")]
1103    fn n_replicas(&self) -> u8 {
1104        self.params
1105            .hsdir_n_replicas
1106            .get()
1107            .try_into()
1108            .expect("BoundedInt did not enforce bounds")
1109    }
1110
1111    /// Return the spread parameter for the specified `op`.
1112    #[cfg(feature = "hs-common")]
1113    fn spread(&self, op: HsDirOp) -> usize {
1114        let spread = match op {
1115            HsDirOp::Download => self.params.hsdir_spread_fetch,
1116            #[cfg(feature = "hs-service")]
1117            HsDirOp::Upload => self.params.hsdir_spread_store,
1118        };
1119
1120        spread
1121            .get()
1122            .try_into()
1123            .expect("BoundedInt did not enforce bounds!")
1124    }
1125
1126    /// Select `spread` hsdir relays for the specified `hsid` from a given `ring`.
1127    ///
1128    /// Algorithm:
1129    ///
1130    /// for idx in 1..=n_replicas:
1131    ///       - let H = hsdir_ring::onion_service_index(id, replica, rand,
1132    ///         period).
1133    ///       - Find the position of H within hsdir_ring.
1134    ///       - Take elements from hsdir_ring starting at that position,
1135    ///         adding them to Dirs until we have added `spread` new elements
1136    ///         that were not there before.
1137    #[cfg(feature = "hs-common")]
1138    fn select_hsdirs<'h, 'r: 'h>(
1139        &'r self,
1140        hsid: HsBlindId,
1141        ring: &'h HsDirRing,
1142        spread: usize,
1143    ) -> impl Iterator<Item = Relay<'r>> + 'h {
1144        let n_replicas = self.n_replicas();
1145
1146        (1..=n_replicas) // 1-indexed !
1147            .flat_map({
1148                let mut selected_nodes = HashSet::new();
1149
1150                move |replica: u8| {
1151                    let hsdir_idx = hsdir_ring::service_hsdir_index(&hsid, replica, ring.params());
1152
1153                    ring.ring_items_at(hsdir_idx, spread, |(hsdir_idx, _)| {
1154                        // According to rend-spec 2.2.3:
1155                        //                                                  ... If any of those
1156                        // nodes have already been selected for a lower-numbered replica of the
1157                        // service, any nodes already chosen are disregarded (i.e. skipped over)
1158                        // when choosing a replica's hsdir_spread_store nodes.
1159                        selected_nodes.insert(*hsdir_idx)
1160                    })
1161                    .collect::<Vec<_>>()
1162                }
1163            })
1164            .filter_map(move |(_hsdir_idx, rs_idx)| {
1165                // This ought not to be None but let's not panic or bail if it is
1166                self.relay_by_rs_idx(*rs_idx)
1167            })
1168    }
1169
1170    /// Replace the overridden parameters in this netdir with `new_replacement`.
1171    ///
1172    /// After this function is done, the netdir's parameters will be those in
1173    /// the consensus, overridden by settings from `new_replacement`.  Any
1174    /// settings in the old replacement parameters will be discarded.
1175    pub fn replace_overridden_parameters(&mut self, new_replacement: &netstatus::NetParams<i32>) {
1176        // TODO(nickm): This is largely duplicate code from PartialNetDir::new().
1177        let mut new_params = NetParameters::default();
1178        let _ = new_params.saturating_update(self.consensus.params().iter());
1179        for u in new_params.saturating_update(new_replacement.iter()) {
1180            warn!("Unrecognized option: override_net_params.{}", u);
1181        }
1182
1183        self.params = new_params;
1184    }
1185
1186    /// Return an iterator over all Relay objects, including invalid ones
1187    /// that we can't use.
1188    pub fn all_relays(&self) -> impl Iterator<Item = UncheckedRelay<'_>> {
1189        // TODO: I'd like if we could memoize this so we don't have to
1190        // do so many hashtable lookups.
1191        self.c_relays()
1192            .iter_enumerated()
1193            .map(move |(rsidx, rs)| self.relay_from_rs_and_rsidx(rs, rsidx))
1194    }
1195    /// Return an iterator over all [usable](NetDir#usable) Relays.
1196    pub fn relays(&self) -> impl Iterator<Item = Relay<'_>> {
1197        self.all_relays().filter_map(UncheckedRelay::into_relay)
1198    }
1199
1200    /// Look up a relay's [`MicrodescAndHash`] by its [`RouterStatusIdx`]
1201    #[cfg_attr(not(feature = "hs-common"), allow(dead_code))]
1202    pub(crate) fn md_by_rsidx(&self, rsidx: RouterStatusIdx) -> Option<&MicrodescAndHash> {
1203        self.mds.get(rsidx)?.as_deref()
1204    }
1205
1206    /// Return a relay matching a given identity, if we have a
1207    /// _usable_ relay with that key.
1208    ///
1209    /// (Does not return [unusable](NetDir#usable) relays.)
1210    ///
1211    ///
1212    /// Note that a `None` answer is not always permanent: if a microdescriptor
1213    /// is subsequently added for a relay with this ID, the ID may become usable
1214    /// even if it was not usable before.
1215    pub fn by_id<'a, T>(&self, id: T) -> Option<Relay<'_>>
1216    where
1217        T: Into<RelayIdRef<'a>>,
1218    {
1219        let id = id.into();
1220        let answer = match id {
1221            RelayIdRef::Ed25519(ed25519) => {
1222                let rsidx = *self.rsidx_by_ed.get(ed25519)?;
1223                let rs = self.c_relays().get(rsidx).expect("Corrupt index");
1224
1225                self.relay_from_rs_and_rsidx(rs, rsidx).into_relay()?
1226            }
1227            RelayIdRef::Rsa(rsa) => self
1228                .by_rsa_id_unchecked(rsa)
1229                .and_then(UncheckedRelay::into_relay)?,
1230            other_type => self.relays().find(|r| r.has_identity(other_type))?,
1231        };
1232        assert!(answer.has_identity(id));
1233        Some(answer)
1234    }
1235
1236    /// Obtain a `Relay` given a `RouterStatusIdx`
1237    ///
1238    /// Differs from `relay_from_rs_and_rsi` as follows:
1239    ///  * That function expects the caller to already have an `MdRouterStatus`;
1240    ///    it checks with `debug_assert` that the relay in the netdir matches.
1241    ///  * That function panics if the `RouterStatusIdx` is invalid; this one returns `None`.
1242    ///  * That function returns an `UncheckedRelay`; this one a `Relay`.
1243    ///
1244    /// `None` could be returned here, even with a valid `rsi`,
1245    /// if `rsi` refers to an [unusable](NetDir#usable) relay.
1246    #[cfg_attr(not(feature = "hs-common"), allow(dead_code))]
1247    pub(crate) fn relay_by_rs_idx(&self, rs_idx: RouterStatusIdx) -> Option<Relay<'_>> {
1248        let rs = self.c_relays().get(rs_idx)?;
1249        let md = self.mds.get(rs_idx)?.as_deref();
1250        UncheckedRelay {
1251            rs,
1252            md,
1253            #[cfg(feature = "geoip")]
1254            cc: self.country_codes.get(rs_idx.0).copied().flatten(),
1255        }
1256        .into_relay()
1257    }
1258
1259    /// Return a relay with the same identities as those in `target`, if one
1260    /// exists.
1261    ///
1262    /// Does not return [unusable](NetDir#usable) relays.
1263    ///
1264    /// Note that a negative result from this method is not necessarily permanent:
1265    /// it may be the case that a relay exists,
1266    /// but we don't yet have enough information about it to know all of its IDs.
1267    /// To test whether a relay is *definitely* absent,
1268    /// use [`by_ids_detailed`](Self::by_ids_detailed)
1269    /// or [`ids_listed`](Self::ids_listed).
1270    ///
1271    /// # Limitations
1272    ///
1273    /// This will be very slow if `target` does not have an Ed25519 or RSA
1274    /// identity.
1275    pub fn by_ids<T>(&self, target: &T) -> Option<Relay<'_>>
1276    where
1277        T: HasRelayIds + ?Sized,
1278    {
1279        let mut identities = target.identities();
1280        // Don't try if there are no identities.
1281        let first_id = identities.next()?;
1282
1283        // Since there is at most one relay with each given ID type,
1284        // we only need to check the first relay we find.
1285        let candidate = self.by_id(first_id)?;
1286        if identities.all(|wanted_id| candidate.has_identity(wanted_id)) {
1287            Some(candidate)
1288        } else {
1289            None
1290        }
1291    }
1292
1293    /// Check whether there is a relay that has at least one identity from
1294    /// `target`, and which _could_ have every identity from `target`.
1295    /// If so, return such a relay.
1296    ///
1297    /// Return `Ok(None)` if we did not find a relay with any identity from `target`.
1298    ///
1299    /// Return `RelayLookupError::Impossible` if we found a relay with at least
1300    /// one identity from `target`, but that relay's other identities contradict
1301    /// what we learned from `target`.
1302    ///
1303    /// Does not return [unusable](NetDir#usable) relays.
1304    ///
1305    /// (This function is only useful if you need to distinguish the
1306    /// "impossible" case from the "no such relay known" case.)
1307    ///
1308    /// # Limitations
1309    ///
1310    /// This will be very slow if `target` does not have an Ed25519 or RSA
1311    /// identity.
1312    //
1313    // TODO HS: This function could use a better name.
1314    //
1315    // TODO: We could remove the feature restriction here once we think this API is
1316    // stable.
1317    #[cfg(feature = "hs-common")]
1318    pub fn by_ids_detailed<T>(
1319        &self,
1320        target: &T,
1321    ) -> std::result::Result<Option<Relay<'_>>, RelayLookupError>
1322    where
1323        T: HasRelayIds + ?Sized,
1324    {
1325        let candidate = target
1326            .identities()
1327            // Find all the relays that share any identity with this set of identities.
1328            .filter_map(|id| self.by_id(id))
1329            // We might find the same relay more than once under a different
1330            // identity, so we remove the duplicates.
1331            //
1332            // Since there is at most one relay per rsa identity per consensus,
1333            // this is a true uniqueness check under current construction rules.
1334            .unique_by(|r| r.rs.rsa_identity())
1335            // If we find two or more distinct relays, then have a contradiction.
1336            .at_most_one()
1337            .map_err(|_| RelayLookupError::Impossible)?;
1338
1339        // If we have no candidate, return None early.
1340        let candidate = match candidate {
1341            Some(relay) => relay,
1342            None => return Ok(None),
1343        };
1344
1345        // Now we know we have a single candidate.  Make sure that it does not have any
1346        // identity that does not match the target.
1347        if target
1348            .identities()
1349            .all(|wanted_id| match candidate.identity(wanted_id.id_type()) {
1350                None => true,
1351                Some(id) => id == wanted_id,
1352            })
1353        {
1354            Ok(Some(candidate))
1355        } else {
1356            Err(RelayLookupError::Impossible)
1357        }
1358    }
1359
1360    /// Return a boolean if this consensus definitely has (or does not have) a
1361    /// relay matching the listed identities.
1362    ///
1363    /// `Some(true)` indicates that the relay exists.
1364    /// `Some(false)` indicates that the relay definitely does not exist.
1365    /// `None` indicates that we can't yet tell whether such a relay exists,
1366    ///  due to missing information.
1367    fn id_pair_listed(&self, ed_id: &Ed25519Identity, rsa_id: &RsaIdentity) -> Option<bool> {
1368        let r = self.by_rsa_id_unchecked(rsa_id);
1369        match r {
1370            Some(unchecked) => {
1371                if !unchecked.rs.ed25519_id_is_usable() {
1372                    return Some(false);
1373                }
1374                // If md is present, then it's listed iff we have the right
1375                // ed id.  Otherwise we don't know if it's listed.
1376                unchecked.md.map(|md| md.ed25519_id() == ed_id)
1377            }
1378            None => {
1379                // Definitely not listed.
1380                Some(false)
1381            }
1382        }
1383    }
1384
1385    /// Check whether a relay exists (or may exist)
1386    /// with the same identities as those in `target`.
1387    ///
1388    /// `Some(true)` indicates that the relay exists.
1389    /// `Some(false)` indicates that the relay definitely does not exist.
1390    /// `None` indicates that we can't yet tell whether such a relay exists,
1391    ///  due to missing information.
1392    pub fn ids_listed<T>(&self, target: &T) -> Option<bool>
1393    where
1394        T: HasRelayIds + ?Sized,
1395    {
1396        let rsa_id = target.rsa_identity();
1397        let ed25519_id = target.ed_identity();
1398
1399        // TODO: If we later support more identity key types, this will
1400        // become incorrect.  This assertion might help us recognize that case.
1401        const _: () = assert!(RelayIdType::COUNT == 2);
1402
1403        match (rsa_id, ed25519_id) {
1404            (Some(r), Some(e)) => self.id_pair_listed(e, r),
1405            (Some(r), None) => Some(self.rsa_id_is_listed(r)),
1406            (None, Some(e)) => {
1407                if self.rsidx_by_ed.contains_key(e) {
1408                    Some(true)
1409                } else {
1410                    None
1411                }
1412            }
1413            (None, None) => None,
1414        }
1415    }
1416
1417    /// Return a (possibly [unusable](NetDir#usable)) relay with a given RSA identity.
1418    ///
1419    /// This API can be used to find information about a relay that is listed in
1420    /// the current consensus, even if we don't yet have enough information
1421    /// (like a microdescriptor) about the relay to use it.
1422    #[cfg_attr(feature = "experimental-api", visibility::make(pub))]
1423    #[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
1424    fn by_rsa_id_unchecked(&self, rsa_id: &RsaIdentity) -> Option<UncheckedRelay<'_>> {
1425        let rsidx = *self.rsidx_by_rsa.get(rsa_id)?;
1426        let rs = self.c_relays().get(rsidx).expect("Corrupt index");
1427        assert_eq!(rs.rsa_identity(), rsa_id);
1428        Some(self.relay_from_rs_and_rsidx(rs, rsidx))
1429    }
1430    /// Return the relay with a given RSA identity, if we have one
1431    /// and it is [usable](NetDir#usable).
1432    fn by_rsa_id(&self, rsa_id: &RsaIdentity) -> Option<Relay<'_>> {
1433        self.by_rsa_id_unchecked(rsa_id)?.into_relay()
1434    }
1435    /// Return true if `rsa_id` is listed in this directory, even if it isn't
1436    /// currently usable.
1437    ///
1438    /// (An "[unusable](NetDir#usable)" relay in this context is one for which we don't have full
1439    /// directory information.)
1440    #[cfg_attr(feature = "experimental-api", visibility::make(pub))]
1441    #[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
1442    fn rsa_id_is_listed(&self, rsa_id: &RsaIdentity) -> bool {
1443        self.by_rsa_id_unchecked(rsa_id).is_some()
1444    }
1445
1446    /// List the hsdirs in this NetDir, that should be in the HSDir rings
1447    ///
1448    /// The results are not returned in any particular order.
1449    #[cfg(feature = "hs-common")]
1450    fn all_hsdirs(&self) -> impl Iterator<Item = (RouterStatusIdx, Relay<'_>)> {
1451        self.c_relays().iter_enumerated().filter_map(|(rsidx, rs)| {
1452            let relay = self.relay_from_rs_and_rsidx(rs, rsidx);
1453            relay.is_hsdir_for_ring().then_some(())?;
1454            let relay = relay.into_relay()?;
1455            Some((rsidx, relay))
1456        })
1457    }
1458
1459    /// Return the parameters from the consensus, clamped to the
1460    /// correct ranges, with defaults filled in.
1461    ///
1462    /// NOTE: that unsupported parameters aren't returned here; only those
1463    /// values configured in the `params` module are available.
1464    pub fn params(&self) -> &NetParameters {
1465        &self.params
1466    }
1467
1468    /// Return a [`ProtoStatus`](netstatus::ProtoStatus) that lists the
1469    /// network's current requirements and recommendations for the list of
1470    /// protocols that every relay must implement.
1471    //
1472    // TODO HS: I am not sure this is the right API; other alternatives would be:
1473    //    * To expose the _required_ relay protocol list instead (since that's all that
1474    //      onion service implementations need).
1475    //    * To expose the client protocol list as well (for symmetry).
1476    //    * To expose the MdConsensus instead (since that's more general, although
1477    //      it restricts the future evolution of this API).
1478    //
1479    // I think that this is a reasonably good compromise for now, but I'm going
1480    // to put it behind the `hs-common` feature to give us time to consider more.
1481    #[cfg(feature = "hs-common")]
1482    pub fn relay_protocol_status(&self) -> &netstatus::ProtoStatus {
1483        self.consensus.relay_protocol_status()
1484    }
1485
1486    /// Return a [`ProtoStatus`](netstatus::ProtoStatus) that lists the
1487    /// network's current requirements and recommendations for the list of
1488    /// protocols that every relay must implement.
1489    //
1490    // TODO HS: See notes on relay_protocol_status above.
1491    #[cfg(feature = "hs-common")]
1492    pub fn client_protocol_status(&self) -> &netstatus::ProtoStatus {
1493        self.consensus.client_protocol_status()
1494    }
1495
1496    /// Construct a `CircTarget` from an externally provided list of link specifiers,
1497    /// and an externally provided onion key.
1498    ///
1499    /// This method is used in the onion service protocol,
1500    /// where introduction points and rendezvous points are specified using these inputs.
1501    ///
1502    /// This function is a member of `NetDir` so that it can provide a reasonable list of
1503    /// [`Protocols`](tor_protover::Protocols) capabilities for the generated `CircTarget`.
1504    /// It does not (and should not!) look up anything else from the directory.
1505    #[cfg(feature = "hs-common")]
1506    pub fn circ_target_from_verbatim_linkspecs(
1507        &self,
1508        linkspecs: &[tor_linkspec::EncodedLinkSpec],
1509        ntor_onion_key: &curve25519::PublicKey,
1510    ) -> StdResult<VerbatimLinkSpecCircTarget<OwnedCircTarget>, VerbatimCircTargetDecodeError> {
1511        use VerbatimCircTargetDecodeError as E;
1512        use tor_linkspec::CircTarget as _;
1513        use tor_linkspec::decode::Strictness;
1514
1515        let mut bld = OwnedCircTarget::builder();
1516        use tor_error::into_internal;
1517
1518        *bld.chan_target() =
1519            OwnedChanTargetBuilder::from_encoded_linkspecs(Strictness::Standard, linkspecs)?;
1520        let protocols = {
1521            let chan_target = bld.chan_target().build().map_err(into_internal!(
1522                "from_encoded_linkspecs gave an invalid output"
1523            ))?;
1524            match self
1525                .by_ids_detailed(&chan_target)
1526                .map_err(E::ImpossibleIds)?
1527            {
1528                Some(relay) => relay.protovers().clone(),
1529                None => self.relay_protocol_status().required_protocols().clone(),
1530            }
1531        };
1532        bld.protocols(protocols);
1533        bld.ntor_onion_key(*ntor_onion_key);
1534        Ok(VerbatimLinkSpecCircTarget::new(
1535            bld.build()
1536                .map_err(into_internal!("Failed to construct a valid circtarget"))?,
1537            linkspecs.to_vec(),
1538        ))
1539    }
1540
1541    /// Return weighted the fraction of relays we can use.  We only
1542    /// consider relays that match the predicate `usable`.  We weight
1543    /// this bandwidth according to the provided `role`.
1544    ///
1545    /// If _no_ matching relays in the consensus have a nonzero
1546    /// weighted bandwidth value, we fall back to looking at the
1547    /// unweighted fraction of matching relays.
1548    ///
1549    /// If there are no matching relays in the consensus, we return 0.0.
1550    fn frac_for_role<'a, F>(&'a self, role: WeightRole, usable: F) -> f64
1551    where
1552        F: Fn(&UncheckedRelay<'a>) -> bool,
1553    {
1554        let mut total_weight = 0_u64;
1555        let mut have_weight = 0_u64;
1556        let mut have_count = 0_usize;
1557        let mut total_count = 0_usize;
1558
1559        for r in self.all_relays() {
1560            if !usable(&r) {
1561                continue;
1562            }
1563            let w = self.weights.weight_rs_for_role(r.rs, role);
1564            total_weight += w;
1565            total_count += 1;
1566            if r.is_usable() {
1567                have_weight += w;
1568                have_count += 1;
1569            }
1570        }
1571
1572        if total_weight > 0 {
1573            // The consensus lists some weighted bandwidth so return the
1574            // fraction of the weighted bandwidth for which we have
1575            // descriptors.
1576            (have_weight as f64) / (total_weight as f64)
1577        } else if total_count > 0 {
1578            // The consensus lists no weighted bandwidth for these relays,
1579            // but at least it does list relays. Return the fraction of
1580            // relays for which it we have descriptors.
1581            (have_count as f64) / (total_count as f64)
1582        } else {
1583            // There are no relays of this kind in the consensus.  Return
1584            // 0.0, to avoid dividing by zero and giving NaN.
1585            0.0
1586        }
1587    }
1588    /// Return the estimated fraction of possible paths that we have
1589    /// enough microdescriptors to build.
1590    fn frac_usable_paths(&self) -> f64 {
1591        // TODO #504, TODO SPEC: We may want to add a set of is_flagged_fast() and/or
1592        // is_flagged_stable() checks here.  This will require spec clarification.
1593        let f_g = self.frac_for_role(WeightRole::Guard, |u| {
1594            u.low_level_details().is_suitable_as_guard()
1595        });
1596        let f_m = self.frac_for_role(WeightRole::Middle, |_| true);
1597        let f_e = if self.all_relays().any(|u| u.rs.is_flagged_exit()) {
1598            self.frac_for_role(WeightRole::Exit, |u| u.rs.is_flagged_exit())
1599        } else {
1600            // If there are no exits at all, we use f_m here.
1601            f_m
1602        };
1603        f_g * f_m * f_e
1604    }
1605    /// Return true if there is enough information in this NetDir to build
1606    /// multihop circuits.
1607    fn have_enough_paths(&self) -> bool {
1608        // TODO-A001: This should check for our guards as well, and
1609        // make sure that if they're listed in the consensus, we have
1610        // the descriptors for them.
1611
1612        // If we can build a randomly chosen path with at least this
1613        // probability, we know enough information to participate
1614        // on the network.
1615
1616        let min_frac_paths: f64 = self.params().min_circuit_path_threshold.as_fraction();
1617
1618        // What fraction of paths can we build?
1619        let available = self.frac_usable_paths();
1620
1621        available >= min_frac_paths
1622    }
1623    /// Choose a relay at random.
1624    ///
1625    /// Each relay is chosen with probability proportional to its weight
1626    /// in the role `role`, and is only selected if the predicate `usable`
1627    /// returns true for it.
1628    ///
1629    /// This function returns None if (and only if) there are no relays
1630    /// where `usable` returned true.
1631    ///
1632    /// A relay with zero weight will be chosen iff all `usable` relays have
1633    /// zero weight.
1634    //
1635    // TODO this API, with the `usable` closure, invites mistakes where we fail to
1636    // check conditions that are implied by the role we have selected for the relay:
1637    // call sites must include a call to `Relay::is_polarity_inverter()` or whatever.
1638    // IMO the `WeightRole` ought to imply a condition (and it should therefore probably
1639    // be renamed.)  -Diziet
1640    pub fn pick_relay<'a, R, P>(
1641        &'a self,
1642        rng: &mut R,
1643        role: WeightRole,
1644        usable: P,
1645    ) -> Option<Relay<'a>>
1646    where
1647        R: rand::Rng,
1648        P: FnMut(&Relay<'a>) -> bool,
1649    {
1650        let relays: Vec<_> = self.relays().filter(usable).collect();
1651
1652        tracing::trace!(?role, "picking from {} relays", relays.len());
1653
1654        // Preemptively check for and handle an empty sequence ourselves, since it's
1655        // cheap to do so and the `choose_weighted` behavior for this edge-case
1656        // is a bit unpredictable.
1657        // See e.g. <https://github.com/rust-random/rand/issues/1783>
1658        if relays.is_empty() {
1659            tracing::debug!(?role, "No eligible relays");
1660            return None;
1661        }
1662
1663        // This algorithm uses rand::distr::WeightedIndex, and uses
1664        // gives O(n) time and space  to build the index, plus O(log n)
1665        // sampling time.
1666        //
1667        // We might be better off building a WeightedIndex in advance
1668        // for each `role`, and then sampling it repeatedly until we
1669        // get a relay that satisfies `usable`.  Or we might not --
1670        // that depends heavily on the actual particulars of our
1671        // inputs.  We probably shouldn't make any changes there
1672        // unless profiling tells us that this function is in a hot
1673        // path.
1674        //
1675        // The C Tor sampling implementation goes through some trouble
1676        // here to try to make its path selection constant-time.  I
1677        // believe that there is no actual remotely exploitable
1678        // side-channel here however.  It could be worth analyzing in
1679        // the future.
1680        //
1681        // This code will give the wrong result if the total of all weights
1682        // can exceed u64::MAX.  We make sure that can't happen when we
1683        // set up `self.weights`.
1684        match relays[..].choose_weighted(rng, |r| {
1685            let weight = self.weights.weight_rs_for_role(r.rs, role);
1686            tracing::trace!("relay:{id:?} role:{role:?} weight:{weight}", id = r.id());
1687            weight
1688        }) {
1689            Ok(relay) => Some(relay.clone()),
1690            Err(WeightError::InsufficientNonZero) => {
1691                warn!(?self.weights, ?role,
1692                        "After filtering, all {} relays had zero weight. Choosing one at random. See bug #1907.",
1693                        relays.len());
1694                relays.choose(rng).cloned()
1695            }
1696            Err(e) => {
1697                warn_report!(
1698                    e,
1699                    "Unexpected error while choosing from {} relays for role {:?}",
1700                    relays.len(),
1701                    role
1702                );
1703                None
1704            }
1705        }
1706    }
1707
1708    /// Choose `n` items (relays) at random, using the provided weights.
1709    ///
1710    /// This is intended as an internal, easier-to-test, implementation of
1711    /// `pick_n_relays`. `T` is generic for testing, but intended to be `Relay`.
1712    ///
1713    /// Items are chosen without replacement: no item will be returned twice.
1714    ///
1715    /// If *all* items have zero-weight, then up to `n` will be chosen randomly
1716    /// and returned. Otherwise, never returns items with zero-weight.
1717    ///
1718    /// May return fewer than `n` items if there are fewer than `n` with non-zero weight
1719    /// (or all have zero-weight but there are fewer than `n` total).
1720    fn pick_n_weighted<R, T>(rng: &mut R, n: usize, weighted_items: &[(T, u64)]) -> Vec<T>
1721    where
1722        R: rand::Rng,
1723        T: Clone,
1724    {
1725        let mut sampled_items = match weighted_items[..]
1726            .sample_weighted(rng, n, |(_r, w)| *w as f64)
1727        {
1728            Err(e) => {
1729                warn_report!(e, "Unexpected error while sampling a set of items");
1730                Vec::new()
1731            }
1732            Ok(sampled_items) => {
1733                if sampled_items.len() < n {
1734                    // Too few items had nonzero weights: return all of those that are okay.
1735                    let nonzero_weight_items: Vec<_> = weighted_items
1736                        .iter()
1737                        .filter_map(|(i, w)| if *w > 0 { Some(i) } else { None })
1738                        .cloned()
1739                        .collect();
1740                    if nonzero_weight_items.is_empty() {
1741                        tracing::debug!(
1742                            "All {} items had zero weight! Picking some at random. See bug #1907.",
1743                            weighted_items.len()
1744                        );
1745                        let items: Vec<_> =
1746                            weighted_items.iter().map(|(i, _w)| i.clone()).collect();
1747                        if items.len() >= n {
1748                            items.sample(rng, n).cloned().collect()
1749                        } else {
1750                            items
1751                        }
1752                    } else {
1753                        tracing::debug!(
1754                            "After filtering, only had {}/{} items with nonzero weight. Returning them all. See bug #1907.",
1755                            nonzero_weight_items.len(),
1756                            weighted_items.len()
1757                        );
1758                        nonzero_weight_items
1759                    }
1760                } else {
1761                    sampled_items.map(|(i, _w)| i.clone()).collect()
1762                }
1763            }
1764        };
1765        sampled_items.shuffle(rng);
1766        sampled_items
1767    }
1768
1769    /// Choose `n` relay at random.
1770    ///
1771    /// Each relay is chosen with probability proportional to its weight
1772    /// in the role `role`, and is only selected if the predicate `usable`
1773    /// returns true for it.
1774    ///
1775    /// Relays are chosen without replacement: no relay will be
1776    /// returned twice. Therefore, the resulting vector may be smaller
1777    /// than `n` if we happen to have fewer than `n` appropriate relays.
1778    ///
1779    /// Relays with zero-weight will be chosen only if there are *no* usable
1780    /// relays with nonzero-weight.
1781    ///
1782    /// This function returns an empty vector if (and only if) there are no
1783    /// relays where `usable` returned true.
1784    pub fn pick_n_relays<'a, R, P>(
1785        &'a self,
1786        rng: &mut R,
1787        n: usize,
1788        role: WeightRole,
1789        usable: P,
1790    ) -> Vec<Relay<'a>>
1791    where
1792        R: rand::Rng,
1793        P: FnMut(&Relay<'a>) -> bool,
1794    {
1795        let filtered_weighted_relays: Vec<(Relay<'a>, u64)> = self
1796            .relays()
1797            .filter(usable)
1798            .map(|r| (r.clone(), self.weights.weight_rs_for_role(r.rs, role)))
1799            .collect();
1800        let res = NetDir::pick_n_weighted(rng, n, filtered_weighted_relays.as_slice());
1801        let n_found = res.len();
1802        if n_found < n {
1803            warn!(?self.weights, ?role,
1804                "Requested {n} relays, but only {n_usable} were usable, and only {n_found} were chosen after weighting {role:?}.",
1805                n_usable=filtered_weighted_relays.len(),
1806            );
1807        }
1808        res
1809    }
1810
1811    /// Compute the weight with which `relay` will be selected for a given
1812    /// `role`.
1813    pub fn relay_weight<'a>(&'a self, relay: &Relay<'a>, role: WeightRole) -> RelayWeight {
1814        RelayWeight(self.weights.weight_rs_for_role(relay.rs, role))
1815    }
1816
1817    /// Compute the total weight with which any relay matching `usable`
1818    /// will be selected for a given `role`.
1819    ///
1820    /// Note: because this function is used to assess the total
1821    /// properties of the consensus, the `usable` predicate takes a
1822    /// [`MdRouterStatus`] rather than a [`Relay`].
1823    pub fn total_weight<P>(&self, role: WeightRole, usable: P) -> RelayWeight
1824    where
1825        P: Fn(&UncheckedRelay<'_>) -> bool,
1826    {
1827        self.all_relays()
1828            .filter_map(|unchecked| {
1829                if usable(&unchecked) {
1830                    Some(RelayWeight(
1831                        self.weights.weight_rs_for_role(unchecked.rs, role),
1832                    ))
1833                } else {
1834                    None
1835                }
1836            })
1837            .sum()
1838    }
1839
1840    /// Compute the weight with which a relay with ID `rsa_id` would be
1841    /// selected for a given `role`.
1842    ///
1843    /// Note that weight returned by this function assumes that the
1844    /// relay with that ID is actually [usable](NetDir#usable); if it isn't usable,
1845    /// then other weight-related functions will call its weight zero.
1846    pub fn weight_by_rsa_id(&self, rsa_id: &RsaIdentity, role: WeightRole) -> Option<RelayWeight> {
1847        self.by_rsa_id_unchecked(rsa_id)
1848            .map(|unchecked| RelayWeight(self.weights.weight_rs_for_role(unchecked.rs, role)))
1849    }
1850
1851    /// Return all relays in this NetDir known to be in the same family as
1852    /// `relay`.
1853    ///
1854    /// This list of members will **not** necessarily include `relay` itself.
1855    ///
1856    /// # Limitations
1857    ///
1858    /// Two relays only belong to the same family if _each_ relay
1859    /// claims to share a family with the other.  But if we are
1860    /// missing a microdescriptor for one of the relays listed by this
1861    /// relay, we cannot know whether it acknowledges family
1862    /// membership with this relay or not.  Therefore, this function
1863    /// can omit family members for which there is not (as yet) any
1864    /// Relay object.
1865    pub fn known_family_members<'a>(
1866        &'a self,
1867        relay: &'a Relay<'a>,
1868    ) -> impl Iterator<Item = Relay<'a>> {
1869        let relay_rsa_id = relay.rsa_id();
1870        relay.md.family().members().filter_map(move |other_rsa_id| {
1871            self.by_rsa_id(other_rsa_id)
1872                .filter(|other_relay| other_relay.md.family().contains(relay_rsa_id))
1873        })
1874    }
1875
1876    /// Return the current hidden service directory "time period".
1877    ///
1878    /// Specifically, this returns the time period that contains the beginning
1879    /// of the validity period of this `NetDir`'s consensus.  That time period
1880    /// is the one we use when acting as an hidden service client.
1881    #[cfg(feature = "hs-common")]
1882    pub fn hs_time_period(&self) -> TimePeriod {
1883        self.hsdir_rings.current.time_period()
1884    }
1885
1886    /// Return the [`HsDirParams`] of all the relevant hidden service directory "time periods"
1887    ///
1888    /// This includes the current time period (as from
1889    /// [`.hs_time_period`](NetDir::hs_time_period))
1890    /// plus additional time periods that we publish descriptors for when we are
1891    /// acting as a hidden service.
1892    #[cfg(feature = "hs-service")]
1893    pub fn hs_all_time_periods(&self) -> Vec<HsDirParams> {
1894        self.hsdir_rings
1895            .iter()
1896            .map(|r| r.params().clone())
1897            .collect()
1898    }
1899
1900    /// Return the relays in this network directory that will be used as hidden service directories
1901    ///
1902    /// These are suitable to retrieve a given onion service's descriptor at a given time period.
1903    #[cfg(feature = "hs-common")]
1904    pub fn hs_dirs_download<'r, R>(
1905        &'r self,
1906        hsid: HsBlindId,
1907        period: TimePeriod,
1908        rng: &mut R,
1909    ) -> std::result::Result<Vec<Relay<'r>>, Bug>
1910    where
1911        R: rand::Rng,
1912    {
1913        // Algorithm:
1914        //
1915        // 1. Determine which HsDirRing to use, based on the time period.
1916        // 2. Find the shared random value that's associated with that HsDirRing.
1917        // 3. Choose spread = the parameter `hsdir_spread_fetch`
1918        // 4. Let n_replicas = the parameter `hsdir_n_replicas`.
1919        // 5. Initialize Dirs = []
1920        // 6. for idx in 1..=n_replicas:
1921        //       - let H = hsdir_ring::onion_service_index(id, replica, rand,
1922        //         period).
1923        //       - Find the position of H within hsdir_ring.
1924        //       - Take elements from hsdir_ring starting at that position,
1925        //         adding them to Dirs until we have added `spread` new elements
1926        //         that were not there before.
1927        // 7. Shuffle Dirs
1928        // 8. return Dirs.
1929
1930        let spread = self.spread(HsDirOp::Download);
1931
1932        // When downloading, only look at relays on current ring.
1933        let ring = &self.hsdir_rings.current;
1934
1935        if ring.params().time_period != period {
1936            return Err(internal!(
1937                "our current ring is not associated with the requested time period!"
1938            ));
1939        }
1940
1941        let mut hs_dirs = self.select_hsdirs(hsid, ring, spread).collect_vec();
1942
1943        // When downloading, the order of the returned relays is random.
1944        hs_dirs.shuffle(rng);
1945
1946        Ok(hs_dirs)
1947    }
1948
1949    /// Return the relays in this network directory that will be used as hidden service directories
1950    ///
1951    /// Returns the relays that are suitable for storing a given onion service's descriptors at the
1952    /// given time period.
1953    #[cfg(feature = "hs-service")]
1954    pub fn hs_dirs_upload(
1955        &self,
1956        hsid: HsBlindId,
1957        period: TimePeriod,
1958    ) -> std::result::Result<impl Iterator<Item = Relay<'_>>, Bug> {
1959        // Algorithm:
1960        //
1961        // 1. Choose spread = the parameter `hsdir_spread_store`
1962        // 2. Determine which HsDirRing to use, based on the time period.
1963        // 3. Find the shared random value that's associated with that HsDirRing.
1964        // 4. Let n_replicas = the parameter `hsdir_n_replicas`.
1965        // 5. Initialize Dirs = []
1966        // 6. for idx in 1..=n_replicas:
1967        //       - let H = hsdir_ring::onion_service_index(id, replica, rand,
1968        //         period).
1969        //       - Find the position of H within hsdir_ring.
1970        //       - Take elements from hsdir_ring starting at that position,
1971        //         adding them to Dirs until we have added `spread` new elements
1972        //         that were not there before.
1973        // 3. return Dirs.
1974        let spread = self.spread(HsDirOp::Upload);
1975
1976        // For each HsBlindId, determine which HsDirRing to use.
1977        let rings = self
1978            .hsdir_rings
1979            .iter()
1980            .filter_map(move |ring| {
1981                // Make sure the ring matches the TP of the hsid it's matched with.
1982                (ring.params().time_period == period).then_some((ring, hsid, period))
1983            })
1984            .collect::<Vec<_>>();
1985
1986        // The specified period should have an associated ring.
1987        if !rings.iter().any(|(_, _, tp)| *tp == period) {
1988            return Err(internal!(
1989                "the specified time period does not have an associated ring"
1990            ));
1991        };
1992
1993        // Now that we've matched each `hsid` with the ring associated with its TP, we can start
1994        // selecting replicas from each ring.
1995        Ok(rings.into_iter().flat_map(move |(ring, hsid, period)| {
1996            assert_eq!(period, ring.params().time_period());
1997            self.select_hsdirs(hsid, ring, spread)
1998        }))
1999    }
2000
2001    /// Return the relays in this network directory that will be used as hidden service directories
2002    ///
2003    /// Depending on `op`,
2004    /// these are suitable to either store, or retrieve, a
2005    /// given onion service's descriptor at a given time period.
2006    ///
2007    /// When `op` is `Download`, the order is random.
2008    /// When `op` is `Upload`, the order is not specified.
2009    ///
2010    /// Return an error if the time period is not one returned by
2011    /// `onion_service_time_period` or `onion_service_secondary_time_periods`.
2012    //
2013    // TODO: make HsDirOp pub(crate) once this is removed
2014    #[cfg(feature = "hs-common")]
2015    #[deprecated(note = "Use hs_dirs_upload or hs_dirs_download instead")]
2016    pub fn hs_dirs<'r, R>(&'r self, hsid: &HsBlindId, op: HsDirOp, rng: &mut R) -> Vec<Relay<'r>>
2017    where
2018        R: rand::Rng,
2019    {
2020        // Algorithm:
2021        //
2022        // 1. Determine which HsDirRing to use, based on the time period.
2023        // 2. Find the shared random value that's associated with that HsDirRing.
2024        // 3. Choose spread = the parameter `hsdir_spread_store` or
2025        //    `hsdir_spread_fetch` based on `op`.
2026        // 4. Let n_replicas = the parameter `hsdir_n_replicas`.
2027        // 5. Initialize Dirs = []
2028        // 6. for idx in 1..=n_replicas:
2029        //       - let H = hsdir_ring::onion_service_index(id, replica, rand,
2030        //         period).
2031        //       - Find the position of H within hsdir_ring.
2032        //       - Take elements from hsdir_ring starting at that position,
2033        //         adding them to Dirs until we have added `spread` new elements
2034        //         that were not there before.
2035        // 7. return Dirs.
2036        let n_replicas = self
2037            .params
2038            .hsdir_n_replicas
2039            .get()
2040            .try_into()
2041            .expect("BoundedInt did not enforce bounds");
2042
2043        let spread = match op {
2044            HsDirOp::Download => self.params.hsdir_spread_fetch,
2045            #[cfg(feature = "hs-service")]
2046            HsDirOp::Upload => self.params.hsdir_spread_store,
2047        };
2048
2049        let spread = spread
2050            .get()
2051            .try_into()
2052            .expect("BoundedInt did not enforce bounds!");
2053
2054        // TODO: I may be wrong here but I suspect that this function may
2055        // need refactoring so that it does not look at _all_ of the HsDirRings,
2056        // but only at the ones that corresponds to time periods for which
2057        // HsBlindId is valid.  Or I could be mistaken, in which case we should
2058        // have a comment to explain why I am, since the logic is subtle.
2059        // (For clients, there is only one ring.) -nickm
2060        //
2061        // (Actually, there is no need to follow through with the above TODO,
2062        // since this function is deprecated, and not used anywhere but the
2063        // tests.)
2064
2065        let mut hs_dirs = self
2066            .hsdir_rings
2067            .iter_for_op(op)
2068            .cartesian_product(1..=n_replicas) // 1-indexed !
2069            .flat_map({
2070                let mut selected_nodes = HashSet::new();
2071
2072                move |(ring, replica): (&HsDirRing, u8)| {
2073                    let hsdir_idx = hsdir_ring::service_hsdir_index(hsid, replica, ring.params());
2074
2075                    ring.ring_items_at(hsdir_idx, spread, |(hsdir_idx, _)| {
2076                        // According to rend-spec 2.2.3:
2077                        //                                                  ... If any of those
2078                        // nodes have already been selected for a lower-numbered replica of the
2079                        // service, any nodes already chosen are disregarded (i.e. skipped over)
2080                        // when choosing a replica's hsdir_spread_store nodes.
2081                        selected_nodes.insert(*hsdir_idx)
2082                    })
2083                    .collect::<Vec<_>>()
2084                }
2085            })
2086            .filter_map(|(_hsdir_idx, rs_idx)| {
2087                // This ought not to be None but let's not panic or bail if it is
2088                self.relay_by_rs_idx(*rs_idx)
2089            })
2090            .collect_vec();
2091
2092        match op {
2093            HsDirOp::Download => {
2094                // When `op` is `Download`, the order is random.
2095                hs_dirs.shuffle(rng);
2096            }
2097            #[cfg(feature = "hs-service")]
2098            HsDirOp::Upload => {
2099                // When `op` is `Upload`, the order is not specified.
2100            }
2101        }
2102
2103        hs_dirs
2104    }
2105}
2106
2107impl MdReceiver for NetDir {
2108    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_> {
2109        Box::new(self.rsidx_by_missing.keys())
2110    }
2111    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool {
2112        self.add_arc_microdesc(Arc::new(md))
2113    }
2114    fn n_missing(&self) -> usize {
2115        self.rsidx_by_missing.len()
2116    }
2117}
2118
2119impl<'a> UncheckedRelay<'a> {
2120    /// Return an [`UncheckedRelayDetails`](details::UncheckedRelayDetails) for this relay.
2121    ///
2122    /// Callers should generally avoid using this information directly if they can;
2123    /// it's better to use a higher-level function that exposes semantic information
2124    /// rather than these properties.
2125    pub fn low_level_details(&self) -> details::UncheckedRelayDetails<'_> {
2126        details::UncheckedRelayDetails(self)
2127    }
2128
2129    /// Return true if this relay is valid and [usable](NetDir#usable).
2130    ///
2131    /// This function should return `true` for every Relay we expose
2132    /// to the user.
2133    pub fn is_usable(&self) -> bool {
2134        // No need to check for 'valid' or 'running': they are implicit.
2135        self.md.is_some() && self.rs.ed25519_id_is_usable()
2136    }
2137    /// If this is [usable](NetDir#usable), return a corresponding Relay object.
2138    pub fn into_relay(self) -> Option<Relay<'a>> {
2139        if self.is_usable() {
2140            Some(Relay {
2141                rs: self.rs,
2142                md: self.md?,
2143                #[cfg(feature = "geoip")]
2144                cc: self.cc,
2145            })
2146        } else {
2147            None
2148        }
2149    }
2150
2151    /// Return true if this relay is a hidden service directory
2152    ///
2153    /// Ie, if it is to be included in the hsdir ring.
2154    #[cfg(feature = "hs-common")]
2155    pub(crate) fn is_hsdir_for_ring(&self) -> bool {
2156        // TODO are there any other flags should we check?
2157        // rend-spec-v3 2.2.3 says just
2158        //   "each node listed in the current consensus with the HSDir flag"
2159        // Do we need to check ed25519_id_is_usable ?
2160        // See also https://gitlab.torproject.org/tpo/core/arti/-/issues/504
2161        self.rs.is_flagged_hsdir()
2162    }
2163}
2164
2165impl<'a> Relay<'a> {
2166    /// Return a [`RelayDetails`](details::RelayDetails) for this relay.
2167    ///
2168    /// Callers should generally avoid using this information directly if they can;
2169    /// it's better to use a higher-level function that exposes semantic information
2170    /// rather than these properties.
2171    pub fn low_level_details(&self) -> details::RelayDetails<'_> {
2172        details::RelayDetails(self)
2173    }
2174
2175    /// Return the Ed25519 ID for this relay.
2176    pub fn id(&self) -> &Ed25519Identity {
2177        self.md.ed25519_id()
2178    }
2179    /// Return the RsaIdentity for this relay.
2180    pub fn rsa_id(&self) -> &RsaIdentity {
2181        self.rs.rsa_identity()
2182    }
2183
2184    /// Return a reference to this relay's "router status" entry in
2185    /// the consensus.
2186    ///
2187    /// The router status entry contains information about the relay
2188    /// that the authorities voted on directly.  For most use cases,
2189    /// you shouldn't need them.
2190    ///
2191    /// This function is only available if the crate was built with
2192    /// its `experimental-api` feature.
2193    #[cfg(feature = "experimental-api")]
2194    pub fn rs(&self) -> &netstatus::MdRouterStatus {
2195        self.rs
2196    }
2197    /// Return a reference to this relay's "microdescriptor" entry in
2198    /// the consensus.
2199    ///
2200    /// A "microdescriptor" is a synopsis of the information about a relay,
2201    /// used to determine its capabilities and route traffic through it.
2202    /// For most use cases, you shouldn't need it.
2203    ///
2204    /// This function is only available if the crate was built with
2205    /// its `experimental-api` feature.
2206    #[cfg(feature = "experimental-api")]
2207    pub fn md(&self) -> &MicrodescAndHash {
2208        self.md
2209    }
2210}
2211
2212/// An error value returned from [`NetDir::by_ids_detailed`].
2213#[cfg(feature = "hs-common")]
2214#[derive(Clone, Debug, thiserror::Error)]
2215#[non_exhaustive]
2216pub enum RelayLookupError {
2217    /// We found a relay whose presence indicates that the provided set of
2218    /// identities is impossible to resolve.
2219    #[error("Provided set of identities is impossible according to consensus.")]
2220    Impossible,
2221}
2222
2223impl<'a> HasAddrs for Relay<'a> {
2224    fn addrs(&self) -> impl Iterator<Item = std::net::SocketAddr> {
2225        self.rs.addrs()
2226    }
2227}
2228#[cfg(feature = "geoip")]
2229impl<'a> HasCountryCode for Relay<'a> {
2230    fn country_code(&self) -> Option<CountryCode> {
2231        self.cc
2232    }
2233}
2234impl<'a> tor_linkspec::HasRelayIdsLegacy for Relay<'a> {
2235    fn ed_identity(&self) -> &Ed25519Identity {
2236        self.id()
2237    }
2238    fn rsa_identity(&self) -> &RsaIdentity {
2239        self.rsa_id()
2240    }
2241}
2242
2243impl<'a> HasRelayIds for UncheckedRelay<'a> {
2244    fn identity(&self, key_type: RelayIdType) -> Option<RelayIdRef<'_>> {
2245        match key_type {
2246            RelayIdType::Ed25519 if self.rs.ed25519_id_is_usable() => {
2247                self.md.map(|m| m.ed25519_id().into())
2248            }
2249            RelayIdType::Rsa => Some(self.rs.rsa_identity().into()),
2250            _ => None,
2251        }
2252    }
2253}
2254#[cfg(feature = "geoip")]
2255impl<'a> HasCountryCode for UncheckedRelay<'a> {
2256    fn country_code(&self) -> Option<CountryCode> {
2257        self.cc
2258    }
2259}
2260
2261impl<'a> DirectChanMethodsHelper for Relay<'a> {}
2262impl<'a> ChanTarget for Relay<'a> {}
2263
2264impl<'a> tor_linkspec::CircTarget for Relay<'a> {
2265    fn ntor_onion_key(&self) -> &ll::pk::curve25519::PublicKey {
2266        self.md.ntor_key()
2267    }
2268    fn protovers(&self) -> &tor_protover::Protocols {
2269        self.rs.protovers()
2270    }
2271}
2272
2273#[cfg(test)]
2274mod test {
2275    // @@ begin test lint list maintained by maint/add_warning @@
2276    #![allow(clippy::bool_assert_comparison)]
2277    #![allow(clippy::clone_on_copy)]
2278    #![allow(clippy::dbg_macro)]
2279    #![allow(clippy::mixed_attributes_style)]
2280    #![allow(clippy::print_stderr)]
2281    #![allow(clippy::print_stdout)]
2282    #![allow(clippy::single_char_pattern)]
2283    #![allow(clippy::unwrap_used)]
2284    #![allow(clippy::unchecked_time_subtraction)]
2285    #![allow(clippy::useless_vec)]
2286    #![allow(clippy::needless_pass_by_value)]
2287    #![allow(clippy::string_slice)] // See arti#2571
2288    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
2289    use super::*;
2290    use crate::testnet::*;
2291    use float_eq::assert_float_eq;
2292    use std::collections::HashSet;
2293    use std::time::Duration;
2294    use tor_basic_utils::test_rng::{self, testing_rng};
2295    use tor_linkspec::{RelayIdType, RelayIds};
2296
2297    #[cfg(feature = "hs-common")]
2298    fn dummy_hs_blind_id() -> HsBlindId {
2299        let hsid = [2, 1, 1, 1].iter().cycle().take(32).cloned().collect_vec();
2300        let hsid = Ed25519Identity::new(hsid[..].try_into().unwrap());
2301        HsBlindId::from(hsid)
2302    }
2303
2304    // Basic functionality for a partial netdir: Add microdescriptors,
2305    // then you have a netdir.
2306    #[test]
2307    fn partial_netdir() {
2308        let (consensus, microdescs) = construct_network().unwrap();
2309        let dir = PartialNetDir::new(consensus, None);
2310
2311        // Check the lifetime
2312        let lifetime = dir.lifetime();
2313        assert_eq!(
2314            lifetime
2315                .valid_until()
2316                .duration_since(lifetime.valid_after())
2317                .unwrap(),
2318            Duration::new(86400, 0)
2319        );
2320
2321        // No microdescriptors, so we don't have enough paths, and can't
2322        // advance.
2323        assert!(!dir.have_enough_paths());
2324        let mut dir = match dir.unwrap_if_sufficient() {
2325            Ok(_) => panic!(),
2326            Err(d) => d,
2327        };
2328
2329        let missing: HashSet<_> = dir.missing_microdescs().collect();
2330        assert_eq!(missing.len(), 40);
2331        assert_eq!(missing.len(), dir.netdir.c_relays().len());
2332        for md in &microdescs {
2333            assert!(missing.contains(md.digest()));
2334        }
2335
2336        // Now add all the mds and try again.
2337        for md in microdescs {
2338            let wanted = dir.add_microdesc(md);
2339            assert!(wanted);
2340        }
2341
2342        let missing: HashSet<_> = dir.missing_microdescs().collect();
2343        assert!(missing.is_empty());
2344        assert!(dir.have_enough_paths());
2345        let _complete = match dir.unwrap_if_sufficient() {
2346            Ok(d) => d,
2347            Err(_) => panic!(),
2348        };
2349    }
2350
2351    #[test]
2352    fn override_params() {
2353        let (consensus, _microdescs) = construct_network().unwrap();
2354        let override_p = "bwweightscale=2 doesnotexist=77 circwindow=500"
2355            .parse()
2356            .unwrap();
2357        let dir = PartialNetDir::new(consensus.clone(), Some(&override_p));
2358        let params = &dir.netdir.params;
2359        assert_eq!(params.bw_weight_scale.get(), 2);
2360        assert_eq!(params.circuit_window.get(), 500_i32);
2361
2362        // try again without the override.
2363        let dir = PartialNetDir::new(consensus, None);
2364        let params = &dir.netdir.params;
2365        assert_eq!(params.bw_weight_scale.get(), 1_i32);
2366        assert_eq!(params.circuit_window.get(), 1000_i32);
2367    }
2368
2369    #[test]
2370    fn fill_from_previous() {
2371        let (consensus, microdescs) = construct_network().unwrap();
2372
2373        let mut dir = PartialNetDir::new(consensus.clone(), None);
2374        for md in microdescs.iter().skip(2) {
2375            let wanted = dir.add_microdesc(md.clone());
2376            assert!(wanted);
2377        }
2378        let dir1 = dir.unwrap_if_sufficient().unwrap();
2379        assert_eq!(dir1.missing_microdescs().count(), 2);
2380
2381        let mut dir = PartialNetDir::new(consensus, None);
2382        assert_eq!(dir.missing_microdescs().count(), 40);
2383        dir.fill_from_previous_netdir(Arc::new(dir1));
2384        assert_eq!(dir.missing_microdescs().count(), 2);
2385    }
2386
2387    #[test]
2388    fn path_count() {
2389        let low_threshold = "min_paths_for_circs_pct=64".parse().unwrap();
2390        let high_threshold = "min_paths_for_circs_pct=65".parse().unwrap();
2391
2392        let (consensus, microdescs) = construct_network().unwrap();
2393
2394        let mut dir = PartialNetDir::new(consensus.clone(), Some(&low_threshold));
2395        for (pos, md) in microdescs.iter().enumerate() {
2396            if pos % 7 == 2 {
2397                continue; // skip a few relays.
2398            }
2399            dir.add_microdesc(md.clone());
2400        }
2401        let dir = dir.unwrap_if_sufficient().unwrap();
2402
2403        // We  have 40 relays that we know about from the consensus.
2404        assert_eq!(dir.all_relays().count(), 40);
2405
2406        // But only 34 are usable.
2407        assert_eq!(dir.relays().count(), 34);
2408
2409        // For guards: mds 20..=39 correspond to Guard relays.
2410        // Their bandwidth is 2*(1000+2000+...10000) = 110_000.
2411        // We skipped 23, 30, and 37.  They have bandwidth
2412        // 4000 + 1000 + 8000 = 13_000.  So our fractional bandwidth
2413        // should be (110-13)/110.
2414        let f = dir.frac_for_role(WeightRole::Guard, |u| u.rs.is_flagged_guard());
2415        assert!(((97.0 / 110.0) - f).abs() < 0.000001);
2416
2417        // For exits: mds 10..=19 and 30..=39 correspond to Exit relays.
2418        // We skipped 16, 30,  and 37. Per above our fractional bandwidth is
2419        // (110-16)/110.
2420        let f = dir.frac_for_role(WeightRole::Exit, |u| u.rs.is_flagged_exit());
2421        assert!(((94.0 / 110.0) - f).abs() < 0.000001);
2422
2423        // For middles: all relays are middles. We skipped 2, 9, 16,
2424        // 23, 30, and 37. Per above our fractional bandwidth is
2425        // (220-33)/220
2426        let f = dir.frac_for_role(WeightRole::Middle, |_| true);
2427        assert!(((187.0 / 220.0) - f).abs() < 0.000001);
2428
2429        // Multiplying those together, we get the fraction of paths we can
2430        // build at ~0.64052066, which is above the threshold we set above for
2431        // MinPathsForCircsPct.
2432        let f = dir.frac_usable_paths();
2433        assert!((f - 0.64052066).abs() < 0.000001);
2434
2435        // But if we try again with a slightly higher threshold...
2436        let mut dir = PartialNetDir::new(consensus, Some(&high_threshold));
2437        for (pos, md) in microdescs.into_iter().enumerate() {
2438            if pos % 7 == 2 {
2439                continue; // skip a few relays.
2440            }
2441            dir.add_microdesc(md);
2442        }
2443        assert!(dir.unwrap_if_sufficient().is_err());
2444    }
2445
2446    /// Return a 3-tuple for use by `test_pick_*()` of an Rng, a number of
2447    /// iterations, and a tolerance.
2448    ///
2449    /// If the Rng is deterministic (the default), we can use a faster setup,
2450    /// with a higher tolerance and fewer iterations.  But if you've explicitly
2451    /// opted into randomization (or are replaying a seed from an earlier
2452    /// randomized test), we give you more iterations and a tighter tolerance.
2453    fn testing_rng_with_tolerances() -> (impl rand::Rng, usize, f64) {
2454        // Use a deterministic RNG if none is specified, since this is slow otherwise.
2455        let config = test_rng::Config::from_env().unwrap_or(test_rng::Config::Deterministic);
2456        let (iters, tolerance) = match config {
2457            test_rng::Config::Deterministic => (5000, 0.02),
2458            _ => (50000, 0.01),
2459        };
2460        (config.into_rng(), iters, tolerance)
2461    }
2462
2463    #[test]
2464    fn test_pick() {
2465        let (consensus, microdescs) = construct_network().unwrap();
2466        let mut dir = PartialNetDir::new(consensus, None);
2467        for md in microdescs.into_iter() {
2468            let wanted = dir.add_microdesc(md.clone());
2469            assert!(wanted);
2470        }
2471        let dir = dir.unwrap_if_sufficient().unwrap();
2472
2473        let (mut rng, total, tolerance) = testing_rng_with_tolerances();
2474
2475        let mut picked = [0_isize; 40];
2476        for _ in 0..total {
2477            let r = dir.pick_relay(&mut rng, WeightRole::Middle, |r| {
2478                r.low_level_details().supports_exit_port_ipv4(80)
2479            });
2480            let r = r.unwrap();
2481            let id_byte = r.identity(RelayIdType::Rsa).unwrap().as_bytes()[0];
2482            picked[id_byte as usize] += 1;
2483        }
2484        // non-exits should never get picked.
2485        picked[0..10].iter().for_each(|x| assert_eq!(*x, 0));
2486        picked[20..30].iter().for_each(|x| assert_eq!(*x, 0));
2487
2488        let picked_f: Vec<_> = picked.iter().map(|x| *x as f64 / total as f64).collect();
2489
2490        // We didn't we any non-default weights, so the other relays get
2491        // weighted proportional to their bandwidth.
2492        assert_float_eq!(picked_f[19], (10.0 / 110.0), abs <= tolerance);
2493        assert_float_eq!(picked_f[38], (9.0 / 110.0), abs <= tolerance);
2494        assert_float_eq!(picked_f[39], (10.0 / 110.0), abs <= tolerance);
2495    }
2496
2497    #[test]
2498    fn test_pick_multiple() {
2499        // This is mostly a copy of test_pick, except that it uses
2500        // pick_n_relays to pick several relays at once.
2501
2502        let dir = construct_netdir().unwrap_if_sufficient().unwrap();
2503
2504        let (mut rng, total, tolerance) = testing_rng_with_tolerances();
2505
2506        let mut picked = [0_isize; 40];
2507        for _ in 0..total / 4 {
2508            let relays = dir.pick_n_relays(&mut rng, 4, WeightRole::Middle, |r| {
2509                r.low_level_details().supports_exit_port_ipv4(80)
2510            });
2511            assert_eq!(relays.len(), 4);
2512            for r in relays {
2513                let id_byte = r.identity(RelayIdType::Rsa).unwrap().as_bytes()[0];
2514                picked[id_byte as usize] += 1;
2515            }
2516        }
2517        // non-exits should never get picked.
2518        picked[0..10].iter().for_each(|x| assert_eq!(*x, 0));
2519        picked[20..30].iter().for_each(|x| assert_eq!(*x, 0));
2520
2521        let picked_f: Vec<_> = picked.iter().map(|x| *x as f64 / total as f64).collect();
2522
2523        // We didn't we any non-default weights, so the other relays get
2524        // weighted proportional to their bandwidth.
2525        assert_float_eq!(picked_f[19], (10.0 / 110.0), abs <= tolerance);
2526        assert_float_eq!(picked_f[36], (7.0 / 110.0), abs <= tolerance);
2527        assert_float_eq!(picked_f[39], (10.0 / 110.0), abs <= tolerance);
2528    }
2529
2530    #[test]
2531    fn test_pick_multiple_from_insufficient() {
2532        // This is intended to test `NetDir::pick_n_relays`, but targets the internal,
2533        // easier-to-test `NetDir::pick_n_weighted` that is used to implement it.
2534
2535        let mut rng = testing_rng();
2536
2537        // If *any* item (relay) has non-zero weight, then we return only those, even if we asked for more.
2538        let mostly_zeros = vec![("dud1", 0), ("dud2", 0), ("ok", 1), ("dud3", 0)];
2539        for n in [1, 2, 10] {
2540            assert_eq!(
2541                NetDir::pick_n_weighted(&mut rng, n, &mostly_zeros[..]),
2542                vec!["ok"],
2543                "where n={n}"
2544            );
2545        }
2546
2547        // If *all* items have zero weight, and we ask for as many or more than
2548        // we have, we get back all of them.
2549        let all_zeros = vec![("dud1", 0), ("dud2", 0), ("dud3", 0)];
2550        let all_zeros_items = all_zeros.iter().map(|(x, _w)| *x).collect::<Vec<_>>();
2551        for n in [all_zeros.len(), all_zeros.len() + 10] {
2552            let mut res = NetDir::pick_n_weighted(&mut rng, n, &all_zeros[..]);
2553            res.sort();
2554            assert_eq!(res, all_zeros_items, "where n={n}");
2555        }
2556
2557        // If *all* items have zero weight, and we ask for fewer than we have,
2558        // we get back as many as we asked for.
2559        let n = all_zeros.len() / 2;
2560        let res = NetDir::pick_n_weighted(&mut rng, n, &all_zeros[..]);
2561        assert_eq!(res.len(), n);
2562    }
2563
2564    #[test]
2565    fn subnets() {
2566        let cfg = SubnetConfig::default();
2567
2568        fn same_net(cfg: &SubnetConfig, a: &str, b: &str) -> bool {
2569            cfg.addrs_in_same_subnet(&a.parse().unwrap(), &b.parse().unwrap())
2570        }
2571
2572        assert!(same_net(&cfg, "127.15.3.3", "127.15.9.9"));
2573        assert!(!same_net(&cfg, "127.15.3.3", "127.16.9.9"));
2574
2575        assert!(!same_net(&cfg, "127.15.3.3", "127::"));
2576
2577        assert!(same_net(&cfg, "ffff:ffff:90:33::", "ffff:ffff:91:34::"));
2578        assert!(!same_net(&cfg, "ffff:ffff:90:33::", "ffff:fffe:91:34::"));
2579
2580        let cfg = SubnetConfig {
2581            subnets_family_v4: 32,
2582            subnets_family_v6: 128,
2583        };
2584        assert!(!same_net(&cfg, "127.15.3.3", "127.15.9.9"));
2585        assert!(!same_net(&cfg, "ffff:ffff:90:33::", "ffff:ffff:91:34::"));
2586
2587        assert!(same_net(&cfg, "127.0.0.1", "127.0.0.1"));
2588        assert!(!same_net(&cfg, "127.0.0.1", "127.0.0.2"));
2589        assert!(same_net(&cfg, "ffff:ffff:90:33::", "ffff:ffff:90:33::"));
2590
2591        let cfg = SubnetConfig {
2592            subnets_family_v4: 33,
2593            subnets_family_v6: 129,
2594        };
2595        assert!(!same_net(&cfg, "127.0.0.1", "127.0.0.1"));
2596        assert!(!same_net(&cfg, "::", "::"));
2597    }
2598
2599    #[test]
2600    fn subnet_union() {
2601        let cfg1 = SubnetConfig {
2602            subnets_family_v4: 16,
2603            subnets_family_v6: 64,
2604        };
2605        let cfg2 = SubnetConfig {
2606            subnets_family_v4: 24,
2607            subnets_family_v6: 32,
2608        };
2609        let a1 = "1.2.3.4".parse().unwrap();
2610        let a2 = "1.2.10.10".parse().unwrap();
2611
2612        let a3 = "ffff:ffff::7".parse().unwrap();
2613        let a4 = "ffff:ffff:1234::8".parse().unwrap();
2614
2615        assert_eq!(cfg1.addrs_in_same_subnet(&a1, &a2), true);
2616        assert_eq!(cfg2.addrs_in_same_subnet(&a1, &a2), false);
2617
2618        assert_eq!(cfg1.addrs_in_same_subnet(&a3, &a4), false);
2619        assert_eq!(cfg2.addrs_in_same_subnet(&a3, &a4), true);
2620
2621        let cfg_u = cfg1.union(&cfg2);
2622        assert_eq!(
2623            cfg_u,
2624            SubnetConfig {
2625                subnets_family_v4: 16,
2626                subnets_family_v6: 32,
2627            }
2628        );
2629        assert_eq!(cfg_u.addrs_in_same_subnet(&a1, &a2), true);
2630        assert_eq!(cfg_u.addrs_in_same_subnet(&a3, &a4), true);
2631
2632        assert_eq!(cfg1.union(&cfg1), cfg1);
2633
2634        assert_eq!(cfg1.union(&SubnetConfig::no_addresses_match()), cfg1);
2635    }
2636
2637    #[test]
2638    fn relay_funcs() {
2639        let (consensus, microdescs) = construct_custom_network(
2640            |pos, nb, _| {
2641                if pos == 15 {
2642                    nb.rs.add_or_port("[f0f0::30]:9001".parse().unwrap());
2643                } else if pos == 20 {
2644                    nb.rs.add_or_port("[f0f0::3131]:9001".parse().unwrap());
2645                }
2646            },
2647            None,
2648        )
2649        .unwrap();
2650        let subnet_config = SubnetConfig::default();
2651        let all_family_info = FamilyRules::all_family_info();
2652        let mut dir = PartialNetDir::new(consensus, None);
2653        for md in microdescs.into_iter() {
2654            let wanted = dir.add_microdesc(md.clone());
2655            assert!(wanted);
2656        }
2657        let dir = dir.unwrap_if_sufficient().unwrap();
2658
2659        // Pick out a few relays by ID.
2660        let k0 = Ed25519Identity::from([0; 32]);
2661        let k1 = Ed25519Identity::from([1; 32]);
2662        let k2 = Ed25519Identity::from([2; 32]);
2663        let k3 = Ed25519Identity::from([3; 32]);
2664        let k10 = Ed25519Identity::from([10; 32]);
2665        let k15 = Ed25519Identity::from([15; 32]);
2666        let k20 = Ed25519Identity::from([20; 32]);
2667
2668        let r0 = dir.by_id(&k0).unwrap();
2669        let r1 = dir.by_id(&k1).unwrap();
2670        let r2 = dir.by_id(&k2).unwrap();
2671        let r3 = dir.by_id(&k3).unwrap();
2672        let r10 = dir.by_id(&k10).unwrap();
2673        let r15 = dir.by_id(&k15).unwrap();
2674        let r20 = dir.by_id(&k20).unwrap();
2675
2676        assert_eq!(r0.id(), &[0; 32].into());
2677        assert_eq!(r0.rsa_id(), &[0; 20].into());
2678        assert_eq!(r1.id(), &[1; 32].into());
2679        assert_eq!(r1.rsa_id(), &[1; 20].into());
2680
2681        assert!(r0.same_relay_ids(&r0));
2682        assert!(r1.same_relay_ids(&r1));
2683        assert!(!r1.same_relay_ids(&r0));
2684
2685        assert!(r0.low_level_details().is_dir_cache());
2686        assert!(!r1.low_level_details().is_dir_cache());
2687        assert!(r2.low_level_details().is_dir_cache());
2688        assert!(!r3.low_level_details().is_dir_cache());
2689
2690        assert!(!r0.low_level_details().supports_exit_port_ipv4(80));
2691        assert!(!r1.low_level_details().supports_exit_port_ipv4(80));
2692        assert!(!r2.low_level_details().supports_exit_port_ipv4(80));
2693        assert!(!r3.low_level_details().supports_exit_port_ipv4(80));
2694
2695        assert!(!r0.low_level_details().policies_allow_some_port());
2696        assert!(!r1.low_level_details().policies_allow_some_port());
2697        assert!(!r2.low_level_details().policies_allow_some_port());
2698        assert!(!r3.low_level_details().policies_allow_some_port());
2699        assert!(r10.low_level_details().policies_allow_some_port());
2700
2701        assert!(r0.low_level_details().in_same_family(&r0, all_family_info));
2702        assert!(r0.low_level_details().in_same_family(&r1, all_family_info));
2703        assert!(r1.low_level_details().in_same_family(&r0, all_family_info));
2704        assert!(r1.low_level_details().in_same_family(&r1, all_family_info));
2705        assert!(!r0.low_level_details().in_same_family(&r2, all_family_info));
2706        assert!(!r2.low_level_details().in_same_family(&r0, all_family_info));
2707        assert!(r2.low_level_details().in_same_family(&r2, all_family_info));
2708        assert!(r2.low_level_details().in_same_family(&r3, all_family_info));
2709
2710        assert!(r0.low_level_details().in_same_subnet(&r10, &subnet_config));
2711        assert!(r10.low_level_details().in_same_subnet(&r10, &subnet_config));
2712        assert!(r0.low_level_details().in_same_subnet(&r0, &subnet_config));
2713        assert!(r1.low_level_details().in_same_subnet(&r1, &subnet_config));
2714        assert!(!r1.low_level_details().in_same_subnet(&r2, &subnet_config));
2715        assert!(!r2.low_level_details().in_same_subnet(&r3, &subnet_config));
2716
2717        // Make sure IPv6 families work.
2718        let subnet_config = SubnetConfig {
2719            subnets_family_v4: 128,
2720            subnets_family_v6: 96,
2721        };
2722        assert!(r15.low_level_details().in_same_subnet(&r20, &subnet_config));
2723        assert!(!r15.low_level_details().in_same_subnet(&r1, &subnet_config));
2724
2725        // Make sure that subnet configs can be disabled.
2726        let subnet_config = SubnetConfig {
2727            subnets_family_v4: 255,
2728            subnets_family_v6: 255,
2729        };
2730        assert!(!r15.low_level_details().in_same_subnet(&r20, &subnet_config));
2731    }
2732
2733    #[test]
2734    fn test_badexit() {
2735        // make a netdir where relays 10-19 are badexit, and everybody
2736        // exits to 443 on IPv6.
2737        use tor_netdoc::types::relay_flags::RelayFlag;
2738        let netdir = construct_custom_netdir(|pos, nb, _| {
2739            if (10..20).contains(&pos) {
2740                nb.rs.add_flags(RelayFlag::BadExit);
2741            }
2742            nb.md.parse_ipv6_policy("accept 443").unwrap();
2743        })
2744        .unwrap()
2745        .unwrap_if_sufficient()
2746        .unwrap();
2747
2748        let e12 = netdir.by_id(&Ed25519Identity::from([12; 32])).unwrap();
2749        let e32 = netdir.by_id(&Ed25519Identity::from([32; 32])).unwrap();
2750
2751        assert!(!e12.low_level_details().supports_exit_port_ipv4(80));
2752        assert!(e32.low_level_details().supports_exit_port_ipv4(80));
2753
2754        assert!(!e12.low_level_details().supports_exit_port_ipv6(443));
2755        assert!(e32.low_level_details().supports_exit_port_ipv6(443));
2756        assert!(!e32.low_level_details().supports_exit_port_ipv6(555));
2757
2758        assert!(!e12.low_level_details().policies_allow_some_port());
2759        assert!(e32.low_level_details().policies_allow_some_port());
2760
2761        assert!(!e12.low_level_details().ipv4_policy().allows_some_port());
2762        assert!(!e12.low_level_details().ipv6_policy().allows_some_port());
2763        assert!(e32.low_level_details().ipv4_policy().allows_some_port());
2764        assert!(e32.low_level_details().ipv6_policy().allows_some_port());
2765
2766        assert!(
2767            e12.low_level_details()
2768                .ipv4_declared_policy()
2769                .allows_some_port()
2770        );
2771        assert!(
2772            e12.low_level_details()
2773                .ipv6_declared_policy()
2774                .allows_some_port()
2775        );
2776    }
2777
2778    #[cfg(feature = "experimental-api")]
2779    #[test]
2780    fn test_accessors() {
2781        let netdir = construct_netdir().unwrap_if_sufficient().unwrap();
2782
2783        let r4 = netdir.by_id(&Ed25519Identity::from([4; 32])).unwrap();
2784        let r16 = netdir.by_id(&Ed25519Identity::from([16; 32])).unwrap();
2785
2786        assert!(!r4.md().ipv4_policy().allows_some_port());
2787        assert!(r16.md().ipv4_policy().allows_some_port());
2788
2789        assert!(!r4.rs().is_flagged_exit());
2790        assert!(r16.rs().is_flagged_exit());
2791    }
2792
2793    #[test]
2794    fn test_by_id() {
2795        // Make a netdir that omits the microdescriptor for 0xDDDDDD...
2796        let netdir = construct_custom_netdir(|pos, nb, _| {
2797            nb.omit_md = pos == 13;
2798        })
2799        .unwrap();
2800
2801        let netdir = netdir.unwrap_if_sufficient().unwrap();
2802
2803        let r = netdir.by_id(&Ed25519Identity::from([0; 32])).unwrap();
2804        assert_eq!(r.id().as_bytes(), &[0; 32]);
2805
2806        assert!(netdir.by_id(&Ed25519Identity::from([13; 32])).is_none());
2807
2808        let r = netdir.by_rsa_id(&[12; 20].into()).unwrap();
2809        assert_eq!(r.rsa_id().as_bytes(), &[12; 20]);
2810        assert!(netdir.rsa_id_is_listed(&[12; 20].into()));
2811
2812        assert!(netdir.by_rsa_id(&[13; 20].into()).is_none());
2813
2814        assert!(netdir.by_rsa_id_unchecked(&[99; 20].into()).is_none());
2815        assert!(!netdir.rsa_id_is_listed(&[99; 20].into()));
2816
2817        let r = netdir.by_rsa_id_unchecked(&[13; 20].into()).unwrap();
2818        assert_eq!(r.rs.rsa_identity().as_bytes(), &[13; 20]);
2819        assert!(netdir.rsa_id_is_listed(&[13; 20].into()));
2820
2821        let pair_13_13 = RelayIds::builder()
2822            .ed_identity([13; 32].into())
2823            .rsa_identity([13; 20].into())
2824            .build()
2825            .unwrap();
2826        let pair_14_14 = RelayIds::builder()
2827            .ed_identity([14; 32].into())
2828            .rsa_identity([14; 20].into())
2829            .build()
2830            .unwrap();
2831        let pair_14_99 = RelayIds::builder()
2832            .ed_identity([14; 32].into())
2833            .rsa_identity([99; 20].into())
2834            .build()
2835            .unwrap();
2836
2837        let r = netdir.by_ids(&pair_13_13);
2838        assert!(r.is_none());
2839        let r = netdir.by_ids(&pair_14_14).unwrap();
2840        assert_eq!(r.identity(RelayIdType::Rsa).unwrap().as_bytes(), &[14; 20]);
2841        assert_eq!(
2842            r.identity(RelayIdType::Ed25519).unwrap().as_bytes(),
2843            &[14; 32]
2844        );
2845        let r = netdir.by_ids(&pair_14_99);
2846        assert!(r.is_none());
2847
2848        assert_eq!(
2849            netdir.id_pair_listed(&[13; 32].into(), &[13; 20].into()),
2850            None
2851        );
2852        assert_eq!(
2853            netdir.id_pair_listed(&[15; 32].into(), &[15; 20].into()),
2854            Some(true)
2855        );
2856        assert_eq!(
2857            netdir.id_pair_listed(&[15; 32].into(), &[99; 20].into()),
2858            Some(false)
2859        );
2860    }
2861
2862    #[test]
2863    #[cfg(feature = "hs-common")]
2864    fn test_by_ids_detailed() {
2865        // Make a netdir that omits the microdescriptor for 0xDDDDDD...
2866        let netdir = construct_custom_netdir(|pos, nb, _| {
2867            nb.omit_md = pos == 13;
2868        })
2869        .unwrap();
2870
2871        let netdir = netdir.unwrap_if_sufficient().unwrap();
2872
2873        let id13_13 = RelayIds::builder()
2874            .ed_identity([13; 32].into())
2875            .rsa_identity([13; 20].into())
2876            .build()
2877            .unwrap();
2878        let id15_15 = RelayIds::builder()
2879            .ed_identity([15; 32].into())
2880            .rsa_identity([15; 20].into())
2881            .build()
2882            .unwrap();
2883        let id15_99 = RelayIds::builder()
2884            .ed_identity([15; 32].into())
2885            .rsa_identity([99; 20].into())
2886            .build()
2887            .unwrap();
2888        let id99_15 = RelayIds::builder()
2889            .ed_identity([99; 32].into())
2890            .rsa_identity([15; 20].into())
2891            .build()
2892            .unwrap();
2893        let id99_99 = RelayIds::builder()
2894            .ed_identity([99; 32].into())
2895            .rsa_identity([99; 20].into())
2896            .build()
2897            .unwrap();
2898        let id15_xx = RelayIds::builder()
2899            .ed_identity([15; 32].into())
2900            .build()
2901            .unwrap();
2902        let idxx_15 = RelayIds::builder()
2903            .rsa_identity([15; 20].into())
2904            .build()
2905            .unwrap();
2906
2907        assert!(matches!(netdir.by_ids_detailed(&id13_13), Ok(None)));
2908        assert!(matches!(netdir.by_ids_detailed(&id15_15), Ok(Some(_))));
2909        assert!(matches!(
2910            netdir.by_ids_detailed(&id15_99),
2911            Err(RelayLookupError::Impossible)
2912        ));
2913        assert!(matches!(
2914            netdir.by_ids_detailed(&id99_15),
2915            Err(RelayLookupError::Impossible)
2916        ));
2917        assert!(matches!(netdir.by_ids_detailed(&id99_99), Ok(None)));
2918        assert!(matches!(netdir.by_ids_detailed(&id15_xx), Ok(Some(_))));
2919        assert!(matches!(netdir.by_ids_detailed(&idxx_15), Ok(Some(_))));
2920    }
2921
2922    #[test]
2923    fn weight_type() {
2924        let r0 = RelayWeight(0);
2925        let r100 = RelayWeight(100);
2926        let r200 = RelayWeight(200);
2927        let r300 = RelayWeight(300);
2928        assert_eq!(r100 + r200, r300);
2929        assert_eq!(r100.checked_div(r200), Some(0.5));
2930        assert!(r100.checked_div(r0).is_none());
2931        assert_eq!(r200.ratio(0.5), Some(r100));
2932        assert!(r200.ratio(-1.0).is_none());
2933    }
2934
2935    #[test]
2936    fn weight_accessors() {
2937        // Make a netdir that omits the microdescriptor for 0xDDDDDD...
2938        let netdir = construct_netdir().unwrap_if_sufficient().unwrap();
2939
2940        let g_total = netdir.total_weight(WeightRole::Guard, |r| r.rs.is_flagged_guard());
2941        // This is just the total guard weight, since all our Wxy = 1.
2942        assert_eq!(g_total, RelayWeight(110_000));
2943
2944        let g_total = netdir.total_weight(WeightRole::Guard, |_| false);
2945        assert_eq!(g_total, RelayWeight(0));
2946
2947        let relay = netdir.by_id(&Ed25519Identity::from([35; 32])).unwrap();
2948        assert!(relay.rs.is_flagged_guard());
2949        let w = netdir.relay_weight(&relay, WeightRole::Guard);
2950        assert_eq!(w, RelayWeight(6_000));
2951
2952        let w = netdir
2953            .weight_by_rsa_id(&[33; 20].into(), WeightRole::Guard)
2954            .unwrap();
2955        assert_eq!(w, RelayWeight(4_000));
2956
2957        assert!(
2958            netdir
2959                .weight_by_rsa_id(&[99; 20].into(), WeightRole::Guard)
2960                .is_none()
2961        );
2962    }
2963
2964    #[test]
2965    fn family_list() {
2966        let netdir = construct_custom_netdir(|pos, n, _| {
2967            if pos == 0x0a {
2968                n.md.family(
2969                    "$0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B \
2970                     $0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C \
2971                     $0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D"
2972                        .parse()
2973                        .unwrap(),
2974                );
2975            } else if pos == 0x0c {
2976                n.md.family("$0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A".parse().unwrap());
2977            }
2978        })
2979        .unwrap()
2980        .unwrap_if_sufficient()
2981        .unwrap();
2982
2983        // In the testing netdir, adjacent members are in the same family by default...
2984        let r0 = netdir.by_id(&Ed25519Identity::from([0; 32])).unwrap();
2985        let family: Vec<_> = netdir.known_family_members(&r0).collect();
2986        assert_eq!(family.len(), 1);
2987        assert_eq!(family[0].id(), &Ed25519Identity::from([1; 32]));
2988
2989        // But we've made this relay claim membership with several others.
2990        let r10 = netdir.by_id(&Ed25519Identity::from([10; 32])).unwrap();
2991        let family: HashSet<_> = netdir.known_family_members(&r10).map(|r| *r.id()).collect();
2992        assert_eq!(family.len(), 2);
2993        assert!(family.contains(&Ed25519Identity::from([11; 32])));
2994        assert!(family.contains(&Ed25519Identity::from([12; 32])));
2995        // Note that 13 doesn't get put in, even though it's listed, since it doesn't claim
2996        //  membership with 10.
2997    }
2998    #[test]
2999    #[cfg(feature = "geoip")]
3000    fn relay_has_country_code() {
3001        let src_v6 = r#"
3002        fe80:dead:beef::,fe80:dead:ffff::,US
3003        fe80:feed:eeee::1,fe80:feed:eeee::1,AT
3004        fe80:feed:eeee::2,fe80:feed:ffff::,DE
3005        "#;
3006        let db = GeoipDb::new_from_legacy_format("", src_v6, true).unwrap();
3007
3008        let netdir = construct_custom_netdir_with_geoip(
3009            |pos, n, _| {
3010                if pos == 0x01 {
3011                    n.rs.add_or_port("[fe80:dead:beef::1]:42".parse().unwrap());
3012                }
3013                if pos == 0x02 {
3014                    n.rs.add_or_port("[fe80:feed:eeee::1]:42".parse().unwrap());
3015                    n.rs.add_or_port("[fe80:feed:eeee::2]:42".parse().unwrap());
3016                }
3017                if pos == 0x03 {
3018                    n.rs.add_or_port("[fe80:dead:beef::1]:42".parse().unwrap());
3019                    n.rs.add_or_port("[fe80:dead:beef::2]:42".parse().unwrap());
3020                }
3021            },
3022            &db,
3023        )
3024        .unwrap()
3025        .unwrap_if_sufficient()
3026        .unwrap();
3027
3028        // No GeoIP data available -> None
3029        let r0 = netdir.by_id(&Ed25519Identity::from([0; 32])).unwrap();
3030        assert_eq!(r0.cc, None);
3031
3032        // Exactly one match -> Some
3033        let r1 = netdir.by_id(&Ed25519Identity::from([1; 32])).unwrap();
3034        assert_eq!(r1.cc.as_ref().map(|x| x.as_ref()), Some("US"));
3035
3036        // Conflicting matches -> None
3037        let r2 = netdir.by_id(&Ed25519Identity::from([2; 32])).unwrap();
3038        assert_eq!(r2.cc, None);
3039
3040        // Multiple agreeing matches -> Some
3041        let r3 = netdir.by_id(&Ed25519Identity::from([3; 32])).unwrap();
3042        assert_eq!(r3.cc.as_ref().map(|x| x.as_ref()), Some("US"));
3043    }
3044
3045    #[test]
3046    #[cfg(feature = "hs-common")]
3047    #[allow(deprecated)]
3048    fn hs_dirs_selection() {
3049        use tor_basic_utils::test_rng::testing_rng;
3050
3051        const HSDIR_SPREAD_STORE: i32 = 6;
3052        const HSDIR_SPREAD_FETCH: i32 = 2;
3053        const PARAMS: [(&str, i32); 2] = [
3054            ("hsdir_spread_store", HSDIR_SPREAD_STORE),
3055            ("hsdir_spread_fetch", HSDIR_SPREAD_FETCH),
3056        ];
3057
3058        let netdir: Arc<NetDir> =
3059            crate::testnet::construct_custom_netdir_with_params(|_, _, _| {}, PARAMS, None)
3060                .unwrap()
3061                .unwrap_if_sufficient()
3062                .unwrap()
3063                .into();
3064        let hsid = dummy_hs_blind_id();
3065
3066        const OP_RELAY_COUNT: &[(HsDirOp, usize)] = &[
3067            // We can't upload to (hsdir_n_replicas * hsdir_spread_store) = 12, relays because there
3068            // are only 10 relays with the HsDir flag in the consensus.
3069            #[cfg(feature = "hs-service")]
3070            (HsDirOp::Upload, 10),
3071            (HsDirOp::Download, 4),
3072        ];
3073
3074        for (op, relay_count) in OP_RELAY_COUNT {
3075            let relays = netdir.hs_dirs(&hsid, *op, &mut testing_rng());
3076
3077            assert_eq!(relays.len(), *relay_count);
3078
3079            // There should be no duplicates (the filtering function passed to
3080            // HsDirRing::ring_items_at() ensures the relays that are already in use for
3081            // lower-numbered replicas aren't considered a second time for a higher-numbered
3082            // replica).
3083            let unique = relays
3084                .iter()
3085                .map(|relay| relay.ed_identity())
3086                .collect::<HashSet<_>>();
3087            assert_eq!(unique.len(), relays.len());
3088        }
3089
3090        // TODO: come up with a test that checks that HsDirRing::ring_items_at() skips over the
3091        // expected relays.
3092        //
3093        // For example, let's say we have the following hsdir ring:
3094        //
3095        //         A  -  B
3096        //        /       \
3097        //       F         C
3098        //        \       /
3099        //         E  -  D
3100        //
3101        // Let's also assume that:
3102        //
3103        //   * hsdir_spread_store = 3
3104        //   * the ordering of the relays on the ring is [A, B, C, D, E, F]
3105        //
3106        // If we use relays [A, B, C] for replica 1, and hs_index(2) = E, then replica 2 _must_ get
3107        // relays [E, F, D]. We should have a test that checks this.
3108    }
3109
3110    #[test]
3111    fn zero_weights() {
3112        // Here we check the behavior of IndexedRandom::choose_weighted
3113        // in the presence of items whose weight is 0.
3114        //
3115        // We think that the behavior is:
3116        //   - If all items have weight 0, choose_weighted returns an error.
3117        //   - If any items have non-zero weight, one of them will be returned.
3118        let items = vec![1, 2, 3];
3119        let mut rng = testing_rng();
3120
3121        let a = items.choose_weighted(&mut rng, |_| 0);
3122        assert!(matches!(a, Err(WeightError::InsufficientNonZero)));
3123
3124        let only_one = |n: &i32| if *n == 1 { 1 } else { 0 };
3125        for _ in 0..100 {
3126            let a = items.choose_weighted(&mut rng, only_one);
3127            assert_eq!(a.unwrap(), &1);
3128        }
3129    }
3130}