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