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
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
pub mod details;
52
mod err;
53
#[cfg(feature = "hs-common")]
54
mod hsdir_params;
55
#[cfg(feature = "hs-common")]
56
mod hsdir_ring;
57
pub mod params;
58
mod weight;
59

            
60
#[cfg(any(test, feature = "testing"))]
61
pub mod testnet;
62
#[cfg(feature = "testing")]
63
pub mod testprovider;
64

            
65
use async_trait::async_trait;
66
#[cfg(feature = "hs-service")]
67
use itertools::chain;
68
use tor_error::warn_report;
69
#[cfg(feature = "hs-common")]
70
use tor_linkspec::OwnedCircTarget;
71
use tor_linkspec::{
72
    ChanTarget, DirectChanMethodsHelper, HasAddrs, HasRelayIds, RelayIdRef, RelayIdType,
73
};
74
use tor_llcrypto as ll;
75
use tor_llcrypto::pk::{ed25519::Ed25519Identity, rsa::RsaIdentity};
76
use tor_netdoc::doc::microdesc::{MdDigest, MicrodescAndHash};
77
use tor_netdoc::doc::netstatus::{self, MdConsensus, MdRouterStatus};
78
#[cfg(feature = "hs-common")]
79
use {hsdir_ring::HsDirRing, std::iter};
80

            
81
use derive_more::{From, Into};
82
use futures::{StreamExt, stream::BoxStream};
83
use num_enum::{IntoPrimitive, TryFromPrimitive};
84
use rand::seq::{IndexedRandom as _, SliceRandom as _, WeightError};
85
use serde::Deserialize;
86
use std::collections::HashMap;
87
use std::net::IpAddr;
88
use std::ops::Deref;
89
use std::sync::Arc;
90
use std::time::SystemTime;
91
use strum::{EnumCount, EnumIter};
92
use tracing::warn;
93
use typed_index_collections::{TiSlice, TiVec};
94

            
95
#[cfg(feature = "hs-common")]
96
use {
97
    itertools::Itertools,
98
    std::collections::HashSet,
99
    std::result::Result as StdResult,
100
    tor_error::{Bug, internal},
101
    tor_hscrypto::{pk::HsBlindId, time::TimePeriod},
102
    tor_linkspec::{OwnedChanTargetBuilder, verbatim::VerbatimLinkSpecCircTarget},
103
    tor_llcrypto::pk::curve25519,
104
};
105

            
106
pub use err::Error;
107
pub use weight::WeightRole;
108
/// A Result using the Error type from the tor-netdir crate
109
pub type Result<T> = std::result::Result<T, Error>;
110

            
111
#[cfg(feature = "hs-common")]
112
pub use err::{OnionDirLookupError, VerbatimCircTargetDecodeError};
113

            
114
use params::NetParameters;
115
#[cfg(feature = "geoip")]
116
use tor_geoip::{CountryCode, GeoipDb, HasCountryCode};
117

            
118
#[cfg(feature = "hs-common")]
119
pub use hsdir_params::HsDirParams;
120

            
121
/// Index into the consensus relays
122
///
123
/// This is an index into the list of relays returned by
124
/// [`.c_relays()`](ConsensusRelays::c_relays)
125
/// (on the corresponding consensus or netdir).
126
///
127
/// This is just a `usize` inside, but using a newtype prevents getting a relay index
128
/// confused with other kinds of slice indices or counts.
129
///
130
/// If you are in a part of the code which needs to work with multiple consensuses,
131
/// the typechecking cannot tell if you try to index into the wrong consensus.
132
#[derive(Debug, From, Into, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
133
pub(crate) struct RouterStatusIdx(usize);
134

            
135
/// Extension trait to provide index-type-safe `.c_relays()` method
136
//
137
// TODO: Really it would be better to have MdConsensns::relays() return TiSlice,
138
// but that would be an API break there.
139
pub(crate) trait ConsensusRelays {
140
    /// Obtain the list of relays in the consensus
141
    //
142
    fn c_relays(&self) -> &TiSlice<RouterStatusIdx, MdRouterStatus>;
143
}
144
impl ConsensusRelays for MdConsensus {
145
54645726
    fn c_relays(&self) -> &TiSlice<RouterStatusIdx, MdRouterStatus> {
146
54645726
        TiSlice::from_ref(MdConsensus::relays(self))
147
54645726
    }
148
}
149
impl ConsensusRelays for NetDir {
150
54545346
    fn c_relays(&self) -> &TiSlice<RouterStatusIdx, MdRouterStatus> {
151
54545346
        self.consensus.c_relays()
152
54545346
    }
153
}
154

            
155
/// Configuration for determining when two relays have addresses "too close" in
156
/// the network.
157
///
158
/// Used by `Relay::low_level_details().in_same_subnet()`.
159
#[derive(Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
160
#[serde(deny_unknown_fields)]
161
pub struct SubnetConfig {
162
    /// Consider IPv4 nodes in the same /x to be the same family.
163
    ///
164
    /// If this value is 0, all nodes with IPv4 addresses will be in the
165
    /// same family.  If this value is above 32, then no nodes will be
166
    /// placed im the same family based on their IPv4 addresses.
167
    subnets_family_v4: u8,
168
    /// Consider IPv6 nodes in the same /x to be the same family.
169
    ///
170
    /// If this value is 0, all nodes with IPv6 addresses will be in the
171
    /// same family.  If this value is above 128, then no nodes will be
172
    /// placed im the same family based on their IPv6 addresses.
173
    subnets_family_v6: u8,
174
}
175

            
176
impl Default for SubnetConfig {
177
582292
    fn default() -> Self {
178
582292
        Self::new(16, 32)
179
582292
    }
180
}
181

            
182
impl SubnetConfig {
183
    /// Construct a new SubnetConfig from a pair of bit prefix lengths.
184
    ///
185
    /// The values are clamped to the appropriate ranges if they are
186
    /// out-of-bounds.
187
1768804
    pub fn new(subnets_family_v4: u8, subnets_family_v6: u8) -> Self {
188
1768804
        Self {
189
1768804
            subnets_family_v4,
190
1768804
            subnets_family_v6,
191
1768804
        }
192
1768804
    }
193

            
194
    /// Construct a new SubnetConfig such that addresses are not in the same
195
    /// family with anything--not even with themselves.
196
3562946
    pub fn no_addresses_match() -> SubnetConfig {
197
3562946
        SubnetConfig {
198
3562946
            subnets_family_v4: 33,
199
3562946
            subnets_family_v6: 129,
200
3562946
        }
201
3562946
    }
202

            
203
    /// Return true if the two addresses in the same subnet, according to this
204
    /// configuration.
205
49824308
    pub fn addrs_in_same_subnet(&self, a: &IpAddr, b: &IpAddr) -> bool {
206
49824308
        match (a, b) {
207
49824276
            (IpAddr::V4(a), IpAddr::V4(b)) => {
208
49824276
                let bits = self.subnets_family_v4;
209
49824276
                if bits > 32 {
210
7112
                    return false;
211
49817164
                }
212
49817164
                let a = u32::from_be_bytes(a.octets());
213
49817164
                let b = u32::from_be_bytes(b.octets());
214
49817164
                (a >> (32 - bits)) == (b >> (32 - bits))
215
            }
216
20
            (IpAddr::V6(a), IpAddr::V6(b)) => {
217
20
                let bits = self.subnets_family_v6;
218
20
                if bits > 128 {
219
4
                    return false;
220
16
                }
221
16
                let a = u128::from_be_bytes(a.octets());
222
16
                let b = u128::from_be_bytes(b.octets());
223
16
                (a >> (128 - bits)) == (b >> (128 - bits))
224
            }
225
12
            _ => false,
226
        }
227
49824308
    }
228

            
229
    /// Return true if any of the addresses in `a` shares a subnet with any of
230
    /// the addresses in `b`, according to this configuration.
231
49824258
    pub fn any_addrs_in_same_subnet<T, U>(&self, a: &T, b: &U) -> bool
232
49824258
    where
233
49824258
        T: tor_linkspec::HasAddrs,
234
49824258
        U: tor_linkspec::HasAddrs,
235
    {
236
49824264
        a.addrs().any(|aa| {
237
49824264
            b.addrs()
238
49824272
                .any(|bb| self.addrs_in_same_subnet(&aa.ip(), &bb.ip()))
239
49824264
        })
240
49824258
    }
241

            
242
    /// Return a new subnet configuration that is the union of `self` and
243
    /// `other`.
244
    ///
245
    /// That is, return a subnet configuration that puts all addresses in the
246
    /// same subnet if and only if at least one of `self` and `other` would put
247
    /// them in the same subnet.
248
1778310
    pub fn union(&self, other: &Self) -> Self {
249
        use std::cmp::min;
250
1778310
        Self {
251
1778310
            subnets_family_v4: min(self.subnets_family_v4, other.subnets_family_v4),
252
1778310
            subnets_family_v6: min(self.subnets_family_v6, other.subnets_family_v6),
253
1778310
        }
254
1778310
    }
255
}
256

            
257
/// Configuration for which listed family information to use when deciding
258
/// whether relays belong to the same family.
259
///
260
/// Derived from network parameters.
261
#[derive(Clone, Copy, Debug)]
262
pub struct FamilyRules {
263
    /// If true, we use family information from lists of family members.
264
    use_family_lists: bool,
265
    /// If true, we use family information from lists of family IDs and from family certs.
266
    use_family_ids: bool,
267
}
268

            
269
impl<'a> From<&'a NetParameters> for FamilyRules {
270
593184
    fn from(params: &'a NetParameters) -> Self {
271
593184
        FamilyRules {
272
593184
            use_family_lists: bool::from(params.use_family_lists),
273
593184
            use_family_ids: bool::from(params.use_family_ids),
274
593184
        }
275
593184
    }
276
}
277

            
278
impl FamilyRules {
279
    /// Return a `FamilyRules` that will use all recognized kinds of family information.
280
914
    pub fn all_family_info() -> Self {
281
914
        Self {
282
914
            use_family_lists: true,
283
914
            use_family_ids: true,
284
914
        }
285
914
    }
286

            
287
    /// Return a `FamilyRules` that will ignore all family information declared by relays.
288
3563040
    pub fn ignore_declared_families() -> Self {
289
3563040
        Self {
290
3563040
            use_family_lists: false,
291
3563040
            use_family_ids: false,
292
3563040
        }
293
3563040
    }
294

            
295
    /// Configure this `FamilyRules` to use (or not use) family information from
296
    /// lists of family members.
297
48
    pub fn use_family_lists(&mut self, val: bool) -> &mut Self {
298
48
        self.use_family_lists = val;
299
48
        self
300
48
    }
301

            
302
    /// Configure this `FamilyRules` to use (or not use) family information from
303
    /// family IDs and family certs.
304
48
    pub fn use_family_ids(&mut self, val: bool) -> &mut Self {
305
48
        self.use_family_ids = val;
306
48
        self
307
48
    }
308

            
309
    /// Return a `FamilyRules` that will look at every source of information
310
    /// requested by `self` or by `other`.
311
1778304
    pub fn union(&self, other: &Self) -> Self {
312
        Self {
313
1778304
            use_family_lists: self.use_family_lists || other.use_family_lists,
314
1778304
            use_family_ids: self.use_family_ids || other.use_family_ids,
315
        }
316
1778304
    }
317
}
318

            
319
/// An opaque type representing the weight with which a relay or set of
320
/// relays will be selected for a given role.
321
///
322
/// Most users should ignore this type, and just use pick_relay instead.
323
#[derive(
324
    Copy,
325
    Clone,
326
    Debug,
327
    derive_more::Add,
328
    derive_more::Sum,
329
    derive_more::AddAssign,
330
    Eq,
331
    PartialEq,
332
    Ord,
333
    PartialOrd,
334
)]
335
pub struct RelayWeight(u64);
336

            
337
impl RelayWeight {
338
    /// Try to divide this weight by `rhs`.
339
    ///
340
    /// Return a ratio on success, or None on division-by-zero.
341
3604
    pub fn checked_div(&self, rhs: RelayWeight) -> Option<f64> {
342
3604
        if rhs.0 == 0 {
343
2
            None
344
        } else {
345
3602
            Some((self.0 as f64) / (rhs.0 as f64))
346
        }
347
3604
    }
348

            
349
    /// Compute a ratio `frac` of this weight.
350
    ///
351
    /// Return None if frac is less than zero, since negative weights
352
    /// are impossible.
353
27796
    pub fn ratio(&self, frac: f64) -> Option<RelayWeight> {
354
27796
        let product = (self.0 as f64) * frac;
355
27796
        if product >= 0.0 && product.is_finite() {
356
27794
            Some(RelayWeight(product as u64))
357
        } else {
358
2
            None
359
        }
360
27796
    }
361
}
362

            
363
impl From<u64> for RelayWeight {
364
7200
    fn from(val: u64) -> Self {
365
7200
        RelayWeight(val)
366
7200
    }
367
}
368

            
369
/// An operation for which we might be requesting a hidden service directory.
370
#[derive(Copy, Clone, Debug, PartialEq)]
371
// TODO: make this pub(crate) once NetDir::hs_dirs is removed
372
#[non_exhaustive]
373
pub enum HsDirOp {
374
    /// Uploading an onion service descriptor.
375
    #[cfg(feature = "hs-service")]
376
    Upload,
377
    /// Downloading an onion service descriptor.
378
    Download,
379
}
380

            
381
/// A view of the Tor directory, suitable for use in building circuits.
382
///
383
/// Abstractly, a [`NetDir`] is a set of usable public [`Relay`]s, each of which
384
/// has its own properties, identity, and correct weighted probability for use
385
/// under different circumstances.
386
///
387
/// A [`NetDir`] is constructed by making a [`PartialNetDir`] from a consensus
388
/// document, and then adding enough microdescriptors to that `PartialNetDir` so
389
/// that it can be used to build paths. (Thus, if you have a NetDir, it is
390
/// definitely adequate to build paths.)
391
///
392
/// # "Usable" relays
393
///
394
/// Many methods on NetDir are defined in terms of <a name="usable">"Usable"</a> relays.  Unless
395
/// otherwise stated, a relay is "usable" if it is listed in the consensus,
396
/// if we have full directory information for that relay (including a
397
/// microdescriptor), and if that relay does not have any flags indicating that
398
/// we should never use it. (Currently, `NoEdConsensus` is the only such flag.)
399
///
400
/// # Limitations
401
///
402
/// The current NetDir implementation assumes fairly strongly that every relay
403
/// has an Ed25519 identity and an RSA identity, that the consensus is indexed
404
/// by RSA identities, and that the Ed25519 identities are stored in
405
/// microdescriptors.
406
///
407
/// If these assumptions someday change, then we'll have to revise the
408
/// implementation.
409
#[derive(Debug, Clone)]
410
pub struct NetDir {
411
    /// A microdescriptor consensus that lists the members of the network,
412
    /// and maps each one to a 'microdescriptor' that has more information
413
    /// about it
414
    consensus: Arc<MdConsensus>,
415
    /// A map from keys to integer values, distributed in the consensus,
416
    /// and clamped to certain defaults.
417
    params: NetParameters,
418
    /// Map from routerstatus index, to that routerstatus's microdescriptor (if we have one.)
419
    mds: TiVec<RouterStatusIdx, Option<Arc<MicrodescAndHash>>>,
420
    /// Map from SHA256 of _missing_ microdescriptors to the index of their
421
    /// corresponding routerstatus.
422
    rsidx_by_missing: HashMap<MdDigest, RouterStatusIdx>,
423
    /// Map from ed25519 identity to index of the routerstatus.
424
    ///
425
    /// Note that we don't know the ed25519 identity of a relay until
426
    /// we get the microdescriptor for it, so this won't be filled in
427
    /// until we get the microdescriptors.
428
    ///
429
    /// # Implementation note
430
    ///
431
    /// For this field, and for `rsidx_by_rsa`,
432
    /// it might be cool to have references instead.
433
    /// But that would make this into a self-referential structure,
434
    /// which isn't possible in safe rust.
435
    rsidx_by_ed: HashMap<Ed25519Identity, RouterStatusIdx>,
436
    /// Map from RSA identity to index of the routerstatus.
437
    ///
438
    /// This is constructed at the same time as the NetDir object, so it
439
    /// can be immutable.
440
    rsidx_by_rsa: Arc<HashMap<RsaIdentity, RouterStatusIdx>>,
441

            
442
    /// Hash ring(s) describing the onion service directory.
443
    ///
444
    /// This is empty in a PartialNetDir, and is filled in before the NetDir is
445
    /// built.
446
    //
447
    // TODO hs: It is ugly to have this exist in a partially constructed state
448
    // in a PartialNetDir.
449
    // Ideally, a PartialNetDir would contain only an HsDirs<HsDirParams>,
450
    // or perhaps nothing at all, here.
451
    #[cfg(feature = "hs-common")]
452
    hsdir_rings: Arc<HsDirs<HsDirRing>>,
453

            
454
    /// Weight values to apply to a given relay when deciding how frequently
455
    /// to choose it for a given role.
456
    weights: weight::WeightSet,
457

            
458
    #[cfg(feature = "geoip")]
459
    /// Country codes for each router in our consensus.
460
    ///
461
    /// This is indexed by the `RouterStatusIdx` (i.e. a router idx of zero has
462
    /// the country code at position zero in this array).
463
    country_codes: Vec<Option<CountryCode>>,
464
}
465

            
466
/// Collection of hidden service directories (or parameters for them)
467
///
468
/// In [`NetDir`] this is used to store the actual hash rings.
469
/// (But, in a NetDir in a [`PartialNetDir`], it contains [`HsDirRing`]s
470
/// where only the `params` are populated, and the `ring` is empty.)
471
///
472
/// This same generic type is used as the return type from
473
/// [`HsDirParams::compute`](HsDirParams::compute),
474
/// where it contains the *parameters* for the primary and secondary rings.
475
#[derive(Debug, Clone)]
476
#[cfg(feature = "hs-common")]
477
pub(crate) struct HsDirs<D> {
478
    /// The current ring
479
    ///
480
    /// It corresponds to the time period containing the `valid-after` time in
481
    /// the consensus. Its SRV is whatever SRV was most current at the time when
482
    /// that time period began.
483
    ///
484
    /// This is the hash ring that we should use whenever we are fetching an
485
    /// onion service descriptor.
486
    current: D,
487

            
488
    /// Secondary rings (based on the parameters for the previous and next time periods)
489
    ///
490
    /// Onion services upload to positions on these ring as well, based on how
491
    /// far into the current time period this directory is, so that
492
    /// not-synchronized clients can still find their descriptor.
493
    ///
494
    /// Note that with the current (2023) network parameters, with
495
    /// `hsdir_interval = SRV lifetime = 24 hours` at most one of these
496
    /// secondary rings will be active at a time.  We have two here in order
497
    /// to conform with a more flexible regime in proposal 342.
498
    //
499
    // TODO: hs clients never need this; so I've made it not-present for them.
500
    // But does that risk too much with respect to side channels?
501
    //
502
    // TODO: Perhaps we should refactor this so that it is clear that these
503
    // are immutable?  On the other hand, the documentation for this type
504
    // declares that it is immutable, so we are likely okay.
505
    //
506
    // TODO: this `Vec` is only ever 0,1,2 elements.
507
    // Maybe it should be an ArrayVec or something.
508
    #[cfg(feature = "hs-service")]
509
    secondary: Vec<D>,
510
}
511

            
512
#[cfg(feature = "hs-common")]
513
impl<D> HsDirs<D> {
514
    /// Convert an `HsDirs<D>` to `HsDirs<D2>` by mapping each contained `D`
515
19938
    pub(crate) fn map<D2>(self, mut f: impl FnMut(D) -> D2) -> HsDirs<D2> {
516
19938
        HsDirs {
517
19938
            current: f(self.current),
518
19938
            #[cfg(feature = "hs-service")]
519
19938
            secondary: self.secondary.into_iter().map(f).collect(),
520
19938
        }
521
19938
    }
522

            
523
    /// Iterate over some of the contained hsdirs, according to `secondary`
524
    ///
525
    /// The current ring is always included.
526
    /// Secondary rings are included iff `secondary` and the `hs-service` feature is enabled.
527
772
    fn iter_filter_secondary(&self, secondary: bool) -> impl Iterator<Item = &D> {
528
772
        let i = iter::once(&self.current);
529

            
530
        // With "hs-service" disabled, there are no secondary rings,
531
        // so we don't care.
532
772
        let _ = secondary;
533

            
534
        #[cfg(feature = "hs-service")]
535
772
        let i = chain!(i, self.secondary.iter().filter(move |_| secondary));
536

            
537
772
        i
538
772
    }
539

            
540
    /// Iterate over all the contained hsdirs
541
768
    pub(crate) fn iter(&self) -> impl Iterator<Item = &D> {
542
768
        self.iter_filter_secondary(true)
543
768
    }
544

            
545
    /// Iterate over the hsdirs relevant for `op`
546
4
    pub(crate) fn iter_for_op(&self, op: HsDirOp) -> impl Iterator<Item = &D> {
547
4
        self.iter_filter_secondary(match op {
548
            #[cfg(feature = "hs-service")]
549
2
            HsDirOp::Upload => true,
550
2
            HsDirOp::Download => false,
551
        })
552
4
    }
553
}
554

            
555
/// An event that a [`NetDirProvider`] can broadcast to indicate that a change in
556
/// the status of its directory.
557
#[derive(
558
    Debug, Clone, Copy, PartialEq, Eq, EnumIter, EnumCount, IntoPrimitive, TryFromPrimitive,
559
)]
560
#[non_exhaustive]
561
#[repr(u16)]
562
pub enum DirEvent {
563
    /// A new consensus has been received, and has enough information to be
564
    /// used.
565
    ///
566
    /// This event is also broadcast when a new set of consensus parameters is
567
    /// available, even if that set of parameters comes from a configuration
568
    /// change rather than from the latest consensus.
569
    NewConsensus,
570

            
571
    /// New descriptors have been received for the current consensus.
572
    ///
573
    /// (This event is _not_ broadcast when receiving new descriptors for a
574
    /// consensus which is not yet ready to replace the current consensus.)
575
    NewDescriptors,
576

            
577
    /// We have received updated recommendations and requirements
578
    /// for which subprotocols we should have to use the network.
579
    NewProtocolRecommendation,
580
}
581

            
582
/// The network directory provider is shutting down without giving us the
583
/// netdir we asked for.
584
#[derive(Clone, Copy, Debug, thiserror::Error)]
585
#[error("Network directory provider is shutting down")]
586
#[non_exhaustive]
587
pub struct NetdirProviderShutdown;
588

            
589
impl tor_error::HasKind for NetdirProviderShutdown {
590
    fn kind(&self) -> tor_error::ErrorKind {
591
        tor_error::ErrorKind::ArtiShuttingDown
592
    }
593
}
594

            
595
/// How "timely" must a network directory be?
596
///
597
/// This enum is used as an argument when requesting a [`NetDir`] object from
598
/// [`NetDirProvider`] and other APIs, to specify how recent the information
599
/// must be in order to be useful.
600
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
601
#[allow(clippy::exhaustive_enums)]
602
pub enum Timeliness {
603
    /// The network directory must be strictly timely.
604
    ///
605
    /// That is, it must be based on a consensus that valid right now, with no
606
    /// tolerance for skew or consensus problems.
607
    ///
608
    /// Avoid using this option if you could use [`Timeliness::Timely`] instead.
609
    Strict,
610
    /// The network directory must be roughly timely.
611
    ///
612
    /// This is, it must be based on a consensus that is not _too_ far in the
613
    /// future, and not _too_ far in the past.
614
    ///
615
    /// (The tolerances for "too far" will depend on configuration.)
616
    ///
617
    /// This is almost always the option that you want to use.
618
    Timely,
619
    /// Any network directory is permissible, regardless of how untimely.
620
    ///
621
    /// Avoid using this option if you could use [`Timeliness::Timely`] instead.
622
    Unchecked,
623
}
624

            
625
/// An object that can provide [`NetDir`]s, as well as inform consumers when
626
/// they might have changed.
627
///
628
/// It is the responsibility of the implementor of `NetDirProvider`
629
/// to try to obtain an up-to-date `NetDir`,
630
/// and continuously to maintain and update it.
631
///
632
/// In usual configurations, Arti uses `tor_dirmgr::DirMgr`
633
/// as its `NetDirProvider`.
634
#[async_trait]
635
pub trait NetDirProvider: UpcastArcNetDirProvider + Send + Sync {
636
    /// Return a network directory that's live according to the provided
637
    /// `timeliness`.
638
    fn netdir(&self, timeliness: Timeliness) -> Result<Arc<NetDir>>;
639

            
640
    /// Return a reasonable netdir for general usage.
641
    ///
642
    /// This is an alias for
643
    /// [`NetDirProvider::netdir`]`(`[`Timeliness::Timely`]`)`.
644
776
    fn timely_netdir(&self) -> Result<Arc<NetDir>> {
645
776
        self.netdir(Timeliness::Timely)
646
776
    }
647

            
648
    /// Return a new asynchronous stream that will receive notification
649
    /// whenever the consensus has changed.
650
    ///
651
    /// Multiple events may be batched up into a single item: each time
652
    /// this stream yields an event, all you can assume is that the event has
653
    /// occurred at least once.
654
    fn events(&self) -> BoxStream<'static, DirEvent>;
655

            
656
    /// Return the latest network parameters.
657
    ///
658
    /// If we have no directory, return a reasonable set of defaults.
659
    fn params(&self) -> Arc<dyn AsRef<NetParameters>>;
660

            
661
    /// Get a NetDir from `provider`, waiting until one exists.
662
    async fn wait_for_netdir(
663
        &self,
664
        timeliness: Timeliness,
665
64
    ) -> std::result::Result<Arc<NetDir>, NetdirProviderShutdown> {
666
        if let Ok(nd) = self.netdir(timeliness) {
667
            return Ok(nd);
668
        }
669

            
670
        let mut stream = self.events();
671
        loop {
672
            // We need to retry `self.netdir()` before waiting for any stream events, to
673
            // avoid deadlock.
674
            //
675
            // We ignore all errors here: they can all potentially be fixed by
676
            // getting a fresh consensus, and they will all get warned about
677
            // by the NetDirProvider itself.
678
            if let Ok(nd) = self.netdir(timeliness) {
679
                return Ok(nd);
680
            }
681
            match stream.next().await {
682
                Some(_) => {}
683
                None => {
684
                    return Err(NetdirProviderShutdown);
685
                }
686
            }
687
        }
688
64
    }
689

            
690
    /// Wait until `provider` lists `target`.
691
    ///
692
    /// NOTE: This might potentially wait indefinitely, if `target` is never actually
693
    /// becomes listed in the directory.  It will exit if the `NetDirProvider` shuts down.
694
    async fn wait_for_netdir_to_list(
695
        &self,
696
        target: &tor_linkspec::RelayIds,
697
        timeliness: Timeliness,
698
    ) -> std::result::Result<(), NetdirProviderShutdown> {
699
        let mut events = self.events();
700
        loop {
701
            // See if the desired relay is in the netdir.
702
            //
703
            // We do this before waiting for any events, to avoid race conditions.
704
            {
705
                let netdir = self.wait_for_netdir(timeliness).await?;
706
                if netdir.ids_listed(target) == Some(true) {
707
                    return Ok(());
708
                }
709
                // If we reach this point, then ids_listed returned `Some(false)`,
710
                // meaning "This relay is definitely not in the current directory";
711
                // or it returned `None`, meaning "waiting for more information
712
                // about this network directory.
713
                // In both cases, it's reasonable to just wait for another netdir
714
                // event and try again.
715
            }
716
            // We didn't find the relay; wait for the provider to have a new netdir
717
            // or more netdir information.
718
            if events.next().await.is_none() {
719
                // The event stream is closed; the provider has shut down.
720
                return Err(NetdirProviderShutdown);
721
            }
722
        }
723
    }
724

            
725
    /// Return the latest set of recommended and required protocols, if there is one.
726
    ///
727
    /// This may be more recent (or more available) than this provider's associated NetDir.
728
    fn protocol_statuses(&self) -> Option<(SystemTime, Arc<netstatus::ProtoStatuses>)>;
729
}
730

            
731
impl<T> NetDirProvider for Arc<T>
732
where
733
    T: NetDirProvider,
734
{
735
    fn netdir(&self, timeliness: Timeliness) -> Result<Arc<NetDir>> {
736
        self.deref().netdir(timeliness)
737
    }
738

            
739
    fn timely_netdir(&self) -> Result<Arc<NetDir>> {
740
        self.deref().timely_netdir()
741
    }
742

            
743
    fn events(&self) -> BoxStream<'static, DirEvent> {
744
        self.deref().events()
745
    }
746

            
747
    fn params(&self) -> Arc<dyn AsRef<NetParameters>> {
748
        self.deref().params()
749
    }
750

            
751
    fn protocol_statuses(&self) -> Option<(SystemTime, Arc<netstatus::ProtoStatuses>)> {
752
        self.deref().protocol_statuses()
753
    }
754
}
755

            
756
/// Helper trait: allows any `Arc<X>` to be upcast to a `Arc<dyn
757
/// NetDirProvider>` if X is an implementation or supertrait of NetDirProvider.
758
///
759
/// This trait exists to work around a limitation in rust: when trait upcasting
760
/// coercion is stable, this will be unnecessary.
761
///
762
/// The Rust tracking issue is <https://github.com/rust-lang/rust/issues/65991>.
763
pub trait UpcastArcNetDirProvider {
764
    /// Return a view of this object as an `Arc<dyn NetDirProvider>`
765
    fn upcast_arc<'a>(self: Arc<Self>) -> Arc<dyn NetDirProvider + 'a>
766
    where
767
        Self: 'a;
768
}
769

            
770
impl<T> UpcastArcNetDirProvider for T
771
where
772
    T: NetDirProvider + Sized,
773
{
774
8
    fn upcast_arc<'a>(self: Arc<Self>) -> Arc<dyn NetDirProvider + 'a>
775
8
    where
776
8
        Self: 'a,
777
    {
778
8
        self
779
8
    }
780
}
781

            
782
impl AsRef<NetParameters> for NetDir {
783
1632
    fn as_ref(&self) -> &NetParameters {
784
1632
        self.params()
785
1632
    }
786
}
787

            
788
/// A partially build NetDir -- it can't be unwrapped until it has
789
/// enough information to build safe paths.
790
#[derive(Debug, Clone)]
791
pub struct PartialNetDir {
792
    /// The netdir that's under construction.
793
    netdir: NetDir,
794

            
795
    /// The previous netdir, if we had one
796
    ///
797
    /// Used as a cache, so we can reuse information
798
    #[cfg(feature = "hs-common")]
799
    prev_netdir: Option<Arc<NetDir>>,
800
}
801

            
802
/// A view of a relay on the Tor network, suitable for building circuits.
803
// TODO: This should probably be a more specific struct, with a trait
804
// that implements it.
805
#[derive(Clone)]
806
pub struct Relay<'a> {
807
    /// A router descriptor for this relay.
808
    rs: &'a netstatus::MdRouterStatus,
809
    /// A microdescriptor for this relay.
810
    md: &'a MicrodescAndHash,
811
    /// The country code this relay is in, if we know one.
812
    #[cfg(feature = "geoip")]
813
    cc: Option<CountryCode>,
814
}
815

            
816
/// A relay that we haven't checked for validity or usability in
817
/// routing.
818
#[derive(Debug)]
819
pub struct UncheckedRelay<'a> {
820
    /// A router descriptor for this relay.
821
    rs: &'a netstatus::MdRouterStatus,
822
    /// A microdescriptor for this relay, if there is one.
823
    md: Option<&'a MicrodescAndHash>,
824
    /// The country code this relay is in, if we know one.
825
    #[cfg(feature = "geoip")]
826
    cc: Option<CountryCode>,
827
}
828

            
829
/// A partial or full network directory that we can download
830
/// microdescriptors for.
831
pub trait MdReceiver {
832
    /// Return an iterator over the digests for all of the microdescriptors
833
    /// that this netdir is missing.
834
    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_>;
835
    /// Add a microdescriptor to this netdir, if it was wanted.
836
    ///
837
    /// Return true if it was indeed wanted.
838
    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool;
839
    /// Return the number of missing microdescriptors.
840
    fn n_missing(&self) -> usize;
841
}
842

            
843
impl PartialNetDir {
844
    /// Create a new PartialNetDir with a given consensus, and no
845
    /// microdescriptors loaded.
846
    ///
847
    /// If `replacement_params` is provided, override network parameters from
848
    /// the consensus with those from `replacement_params`.
849
9876
    pub fn new(
850
9876
        consensus: MdConsensus,
851
9876
        replacement_params: Option<&netstatus::NetParams<i32>>,
852
9876
    ) -> Self {
853
9876
        Self::new_inner(
854
9876
            consensus,
855
9876
            replacement_params,
856
            #[cfg(feature = "geoip")]
857
9876
            None,
858
        )
859
9876
    }
860

            
861
    /// Create a new PartialNetDir with GeoIP support.
862
    ///
863
    /// This does the same thing as `new()`, except the provided GeoIP database is used to add
864
    /// country codes to relays.
865
    #[cfg(feature = "geoip")]
866
146
    pub fn new_with_geoip(
867
146
        consensus: MdConsensus,
868
146
        replacement_params: Option<&netstatus::NetParams<i32>>,
869
146
        geoip_db: &GeoipDb,
870
146
    ) -> Self {
871
146
        Self::new_inner(consensus, replacement_params, Some(geoip_db))
872
146
    }
873

            
874
    /// Implementation of the `new()` functions.
875
10022
    fn new_inner(
876
10022
        consensus: MdConsensus,
877
10022
        replacement_params: Option<&netstatus::NetParams<i32>>,
878
10022
        #[cfg(feature = "geoip")] geoip_db: Option<&GeoipDb>,
879
10022
    ) -> Self {
880
10022
        let mut params = NetParameters::default();
881

            
882
        // (We ignore unrecognized options here, since they come from
883
        // the consensus, and we don't expect to recognize everything
884
        // there.)
885
10022
        let _ = params.saturating_update(consensus.params().iter());
886

            
887
        // Now see if the user has any parameters to override.
888
        // (We have to do this now, or else changes won't be reflected in our
889
        // weights.)
890
10022
        if let Some(replacement) = replacement_params {
891
10010
            for u in params.saturating_update(replacement.iter()) {
892
2
                warn!("Unrecognized option: override_net_params.{}", u);
893
            }
894
12
        }
895

            
896
        // Compute the weights we'll want to use for these relays.
897
10022
        let weights = weight::WeightSet::from_consensus(&consensus, &params);
898

            
899
10022
        let n_relays = consensus.c_relays().len();
900

            
901
10022
        let rsidx_by_missing = consensus
902
10022
            .c_relays()
903
10022
            .iter_enumerated()
904
379267
            .map(|(rsidx, rs)| (*rs.md_digest(), rsidx))
905
10022
            .collect();
906

            
907
10022
        let rsidx_by_rsa = consensus
908
10022
            .c_relays()
909
10022
            .iter_enumerated()
910
379267
            .map(|(rsidx, rs)| (*rs.rsa_identity(), rsidx))
911
10022
            .collect();
912

            
913
        #[cfg(feature = "geoip")]
914
10022
        let country_codes = if let Some(db) = geoip_db {
915
146
            consensus
916
146
                .c_relays()
917
146
                .iter()
918
756
                .map(|rs| {
919
1050
                    db.lookup_country_code_multi(rs.addrs().map(|x| x.ip()))
920
752
                        .cloned()
921
752
                })
922
146
                .collect()
923
        } else {
924
9876
            Default::default()
925
        };
926

            
927
        #[cfg(feature = "hs-common")]
928
10022
        let hsdir_rings = Arc::new({
929
10022
            let params = HsDirParams::compute(&consensus, &params).expect("Invalid consensus!");
930
            // TODO: It's a bit ugly to use expect above, but this function does
931
            // not return a Result. On the other hand, the error conditions under which
932
            // HsDirParams::compute can return Err are _very_ narrow and hard to
933
            // hit; see documentation in that function.  As such, we probably
934
            // don't need to have this return a Result.
935

            
936
10022
            params.map(HsDirRing::empty_from_params)
937
        });
938

            
939
10022
        let netdir = NetDir {
940
10022
            consensus: Arc::new(consensus),
941
10022
            params,
942
10022
            mds: vec![None; n_relays].into(),
943
10022
            rsidx_by_missing,
944
10022
            rsidx_by_rsa: Arc::new(rsidx_by_rsa),
945
10022
            rsidx_by_ed: HashMap::with_capacity(n_relays),
946
10022
            #[cfg(feature = "hs-common")]
947
10022
            hsdir_rings,
948
10022
            weights,
949
10022
            #[cfg(feature = "geoip")]
950
10022
            country_codes,
951
10022
        };
952

            
953
10022
        PartialNetDir {
954
10022
            netdir,
955
10022
            #[cfg(feature = "hs-common")]
956
10022
            prev_netdir: None,
957
10022
        }
958
10022
    }
959

            
960
    /// Return the declared lifetime of this PartialNetDir.
961
2
    pub fn lifetime(&self) -> &netstatus::Lifetime {
962
2
        self.netdir.lifetime()
963
2
    }
964

            
965
    /// Record a previous netdir, which can be used for reusing cached information
966
    //
967
    // Fills in as many missing microdescriptors as possible in this
968
    // netdir, using the microdescriptors from the previous netdir.
969
    //
970
    // With HS enabled, stores the netdir for reuse of relay hash ring index values.
971
    #[allow(clippy::needless_pass_by_value)] // prev might, or might not, be stored
972
2
    pub fn fill_from_previous_netdir(&mut self, prev: Arc<NetDir>) {
973
76
        for md in prev.mds.iter().flatten() {
974
76
            self.netdir.add_arc_microdesc(md.clone());
975
76
        }
976

            
977
        #[cfg(feature = "hs-common")]
978
2
        {
979
2
            self.prev_netdir = Some(prev);
980
2
        }
981
2
    }
982

            
983
    /// Compute the hash ring(s) for this NetDir
984
    #[cfg(feature = "hs-common")]
985
9916
    fn compute_rings(&mut self) {
986
9916
        let params = HsDirParams::compute(&self.netdir.consensus, &self.netdir.params)
987
9916
            .expect("Invalid consensus");
988
        // TODO: see TODO by similar expect in new()
989

            
990
9916
        self.netdir.hsdir_rings =
991
10520
            Arc::new(params.map(|params| {
992
10300
                HsDirRing::compute(params, &self.netdir, self.prev_netdir.as_deref())
993
10300
            }));
994
9916
    }
995

            
996
    /// Return true if this are enough information in this directory
997
    /// to build multihop paths.
998
4
    pub fn have_enough_paths(&self) -> bool {
999
4
        self.netdir.have_enough_paths()
4
    }
    /// If this directory has enough information to build multihop
    /// circuits, return it.
10112
    pub fn unwrap_if_sufficient(
10112
        #[allow(unused_mut)] mut self,
10112
    ) -> std::result::Result<NetDir, PartialNetDir> {
10112
        if self.netdir.have_enough_paths() {
            #[cfg(feature = "hs-common")]
9916
            self.compute_rings();
9916
            Ok(self.netdir)
        } else {
196
            Err(self)
        }
10112
    }
}
impl MdReceiver for PartialNetDir {
104
    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_> {
104
        self.netdir.missing_microdescs()
104
    }
394944
    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool {
394944
        self.netdir.add_microdesc(md)
394944
    }
288
    fn n_missing(&self) -> usize {
288
        self.netdir.n_missing()
288
    }
}
impl NetDir {
    /// Return the declared lifetime of this NetDir.
338
    pub fn lifetime(&self) -> &netstatus::Lifetime {
338
        self.consensus.lifetime()
338
    }
    /// Add `md` to this NetDir.
    ///
    /// Return true if we wanted it, and false otherwise.
395020
    fn add_arc_microdesc(&mut self, md: Arc<MicrodescAndHash>) -> bool {
395020
        if let Some(rsidx) = self.rsidx_by_missing.remove(md.digest()) {
378268
            assert_eq!(self.c_relays()[rsidx].md_digest(), md.digest());
            // There should never be two approved MDs in the same
            // consensus listing the same ID... but if there is,
            // we'll let the most recent one win.
378268
            self.rsidx_by_ed.insert(*md.ed25519_id(), rsidx);
            // Happy path: we did indeed want this one.
378268
            self.mds[rsidx] = Some(md);
            // Save some space in the missing-descriptor list.
378268
            if self.rsidx_by_missing.len() < self.rsidx_by_missing.capacity() / 4 {
19024
                self.rsidx_by_missing.shrink_to_fit();
359244
            }
378268
            return true;
16752
        }
        // Either we already had it, or we never wanted it at all.
16752
        false
395020
    }
    /// Construct a (possibly invalid) Relay object from a routerstatus and its
    /// index within the consensus.
51943874
    fn relay_from_rs_and_rsidx<'a>(
51943874
        &'a self,
51943874
        rs: &'a netstatus::MdRouterStatus,
51943874
        rsidx: RouterStatusIdx,
51943874
    ) -> UncheckedRelay<'a> {
51943874
        debug_assert_eq!(self.c_relays()[rsidx].rsa_identity(), rs.rsa_identity());
51943874
        let md = self.mds[rsidx].as_deref();
51943874
        if let Some(md) = md {
51939992
            debug_assert_eq!(rs.md_digest(), md.digest());
3882
        }
51943874
        UncheckedRelay {
51943874
            rs,
51943874
            md,
51943874
            #[cfg(feature = "geoip")]
51943874
            cc: self.country_codes.get(rsidx.0).copied().flatten(),
51943874
        }
51943874
    }
    /// Return the value of the hsdir_n_replicas param.
    #[cfg(feature = "hs-common")]
768
    fn n_replicas(&self) -> u8 {
768
        self.params
768
            .hsdir_n_replicas
768
            .get()
768
            .try_into()
768
            .expect("BoundedInt did not enforce bounds")
768
    }
    /// Return the spread parameter for the specified `op`.
    #[cfg(feature = "hs-common")]
768
    fn spread(&self, op: HsDirOp) -> usize {
768
        let spread = match op {
384
            HsDirOp::Download => self.params.hsdir_spread_fetch,
            #[cfg(feature = "hs-service")]
384
            HsDirOp::Upload => self.params.hsdir_spread_store,
        };
768
        spread
768
            .get()
768
            .try_into()
768
            .expect("BoundedInt did not enforce bounds!")
768
    }
    /// Select `spread` hsdir relays for the specified `hsid` from a given `ring`.
    ///
    /// Algorithm:
    ///
    /// for idx in 1..=n_replicas:
    ///       - let H = hsdir_ring::onion_service_index(id, replica, rand,
    ///         period).
    ///       - Find the position of H within hsdir_ring.
    ///       - Take elements from hsdir_ring starting at that position,
    ///         adding them to Dirs until we have added `spread` new elements
    ///         that were not there before.
    #[cfg(feature = "hs-common")]
768
    fn select_hsdirs<'h, 'r: 'h>(
768
        &'r self,
768
        hsid: HsBlindId,
768
        ring: &'h HsDirRing,
768
        spread: usize,
768
    ) -> impl Iterator<Item = Relay<'r>> + 'h {
768
        let n_replicas = self.n_replicas();
768
        (1..=n_replicas) // 1-indexed !
768
            .flat_map({
768
                let mut selected_nodes = HashSet::new();
64
                move |replica: u8| {
64
                    let hsdir_idx = hsdir_ring::service_hsdir_index(&hsid, replica, ring.params());
324
                    ring.ring_items_at(hsdir_idx, spread, |(hsdir_idx, _)| {
                        // According to rend-spec 2.2.3:
                        //                                                  ... If any of those
                        // nodes have already been selected for a lower-numbered replica of the
                        // service, any nodes already chosen are disregarded (i.e. skipped over)
                        // when choosing a replica's hsdir_spread_store nodes.
324
                        selected_nodes.insert(*hsdir_idx)
324
                    })
64
                    .collect::<Vec<_>>()
64
                }
            })
960
            .filter_map(move |(_hsdir_idx, rs_idx)| {
                // This ought not to be None but let's not panic or bail if it is
224
                self.relay_by_rs_idx(*rs_idx)
224
            })
768
    }
    /// Replace the overridden parameters in this netdir with `new_replacement`.
    ///
    /// After this function is done, the netdir's parameters will be those in
    /// the consensus, overridden by settings from `new_replacement`.  Any
    /// settings in the old replacement parameters will be discarded.
    pub fn replace_overridden_parameters(&mut self, new_replacement: &netstatus::NetParams<i32>) {
        // TODO(nickm): This is largely duplicate code from PartialNetDir::new().
        let mut new_params = NetParameters::default();
        let _ = new_params.saturating_update(self.consensus.params().iter());
        for u in new_params.saturating_update(new_replacement.iter()) {
            warn!("Unrecognized option: override_net_params.{}", u);
        }
        self.params = new_params;
    }
    /// Return an iterator over all Relay objects, including invalid ones
    /// that we can't use.
1310634
    pub fn all_relays(&self) -> impl Iterator<Item = UncheckedRelay<'_>> {
        // TODO: I'd like if we could memoize this so we don't have to
        // do so many hashtable lookups.
1310634
        self.c_relays()
1310634
            .iter_enumerated()
50686864
            .map(move |(rsidx, rs)| self.relay_from_rs_and_rsidx(rs, rsidx))
1310634
    }
    /// Return an iterator over all [usable](NetDir#usable) Relays.
1242358
    pub fn relays(&self) -> impl Iterator<Item = Relay<'_>> {
1242358
        self.all_relays().filter_map(UncheckedRelay::into_relay)
1242358
    }
    /// Look up a relay's [`MicrodescAndHash`] by its [`RouterStatusIdx`]
    #[cfg_attr(not(feature = "hs-common"), allow(dead_code))]
    pub(crate) fn md_by_rsidx(&self, rsidx: RouterStatusIdx) -> Option<&MicrodescAndHash> {
        self.mds.get(rsidx)?.as_deref()
    }
    /// Return a relay matching a given identity, if we have a
    /// _usable_ relay with that key.
    ///
    /// (Does not return [unusable](NetDir#usable) relays.)
    ///
    ///
    /// Note that a `None` answer is not always permanent: if a microdescriptor
    /// is subsequently added for a relay with this ID, the ID may become usable
    /// even if it was not usable before.
620574
    pub fn by_id<'a, T>(&self, id: T) -> Option<Relay<'_>>
620574
    where
620574
        T: Into<RelayIdRef<'a>>,
    {
620574
        let id = id.into();
620574
        let answer = match id {
618394
            RelayIdRef::Ed25519(ed25519) => {
618394
                let rsidx = *self.rsidx_by_ed.get(ed25519)?;
611184
                let rs = self.c_relays().get(rsidx).expect("Corrupt index");
611184
                self.relay_from_rs_and_rsidx(rs, rsidx).into_relay()?
            }
2180
            RelayIdRef::Rsa(rsa) => self
2180
                .by_rsa_id_unchecked(rsa)
2180
                .and_then(UncheckedRelay::into_relay)?,
            other_type => self.relays().find(|r| r.has_identity(other_type))?,
        };
611198
        assert!(answer.has_identity(id));
611198
        Some(answer)
620574
    }
    /// Obtain a `Relay` given a `RouterStatusIdx`
    ///
    /// Differs from `relay_from_rs_and_rsi` as follows:
    ///  * That function expects the caller to already have an `MdRouterStatus`;
    ///    it checks with `debug_assert` that the relay in the netdir matches.
    ///  * That function panics if the `RouterStatusIdx` is invalid; this one returns `None`.
    ///  * That function returns an `UncheckedRelay`; this one a `Relay`.
    ///
    /// `None` could be returned here, even with a valid `rsi`,
    /// if `rsi` refers to an [unusable](NetDir#usable) relay.
    #[cfg_attr(not(feature = "hs-common"), allow(dead_code))]
5404
    pub(crate) fn relay_by_rs_idx(&self, rs_idx: RouterStatusIdx) -> Option<Relay<'_>> {
5404
        let rs = self.c_relays().get(rs_idx)?;
5404
        let md = self.mds.get(rs_idx)?.as_deref();
5404
        UncheckedRelay {
5404
            rs,
5404
            md,
5404
            #[cfg(feature = "geoip")]
5404
            cc: self.country_codes.get(rs_idx.0).copied().flatten(),
5404
        }
5404
        .into_relay()
5404
    }
    /// Return a relay with the same identities as those in `target`, if one
    /// exists.
    ///
    /// Does not return [unusable](NetDir#usable) relays.
    ///
    /// Note that a negative result from this method is not necessarily permanent:
    /// it may be the case that a relay exists,
    /// but we don't yet have enough information about it to know all of its IDs.
    /// To test whether a relay is *definitely* absent,
    /// use [`by_ids_detailed`](Self::by_ids_detailed)
    /// or [`ids_listed`](Self::ids_listed).
    ///
    /// # Limitations
    ///
    /// This will be very slow if `target` does not have an Ed25519 or RSA
    /// identity.
558270
    pub fn by_ids<T>(&self, target: &T) -> Option<Relay<'_>>
558270
    where
558270
        T: HasRelayIds + ?Sized,
    {
558270
        let mut identities = target.identities();
        // Don't try if there are no identities.
558270
        let first_id = identities.next()?;
        // Since there is at most one relay with each given ID type,
        // we only need to check the first relay we find.
558270
        let candidate = self.by_id(first_id)?;
558058
        if identities.all(|wanted_id| candidate.has_identity(wanted_id)) {
558056
            Some(candidate)
        } else {
2
            None
        }
558270
    }
    /// Check whether there is a relay that has at least one identity from
    /// `target`, and which _could_ have every identity from `target`.
    /// If so, return such a relay.
    ///
    /// Return `Ok(None)` if we did not find a relay with any identity from `target`.
    ///
    /// Return `RelayLookupError::Impossible` if we found a relay with at least
    /// one identity from `target`, but that relay's other identities contradict
    /// what we learned from `target`.
    ///
    /// Does not return [unusable](NetDir#usable) relays.
    ///
    /// (This function is only useful if you need to distinguish the
    /// "impossible" case from the "no such relay known" case.)
    ///
    /// # Limitations
    ///
    /// This will be very slow if `target` does not have an Ed25519 or RSA
    /// identity.
    //
    // TODO HS: This function could use a better name.
    //
    // TODO: We could remove the feature restriction here once we think this API is
    // stable.
    #[cfg(feature = "hs-common")]
2174
    pub fn by_ids_detailed<T>(
2174
        &self,
2174
        target: &T,
2174
    ) -> std::result::Result<Option<Relay<'_>>, RelayLookupError>
2174
    where
2174
        T: HasRelayIds + ?Sized,
    {
2174
        let candidate = target
2174
            .identities()
            // Find all the relays that share any identity with this set of identities.
4344
            .filter_map(|id| self.by_id(id))
            // We might find the same relay more than once under a different
            // identity, so we remove the duplicates.
            //
            // Since there is at most one relay per rsa identity per consensus,
            // this is a true uniqueness check under current construction rules.
2174
            .unique_by(|r| r.rs.rsa_identity())
            // If we find two or more distinct relays, then have a contradiction.
2174
            .at_most_one()
2174
            .map_err(|_| RelayLookupError::Impossible)?;
        // If we have no candidate, return None early.
2174
        let candidate = match candidate {
10
            Some(relay) => relay,
2164
            None => return Ok(None),
        };
        // Now we know we have a single candidate.  Make sure that it does not have any
        // identity that does not match the target.
10
        if target
10
            .identities()
14
            .all(|wanted_id| match candidate.identity(wanted_id.id_type()) {
                None => true,
14
                Some(id) => id == wanted_id,
14
            })
        {
6
            Ok(Some(candidate))
        } else {
4
            Err(RelayLookupError::Impossible)
        }
2174
    }
    /// Return a boolean if this consensus definitely has (or does not have) a
    /// relay matching the listed identities.
    ///
    /// `Some(true)` indicates that the relay exists.
    /// `Some(false)` indicates that the relay definitely does not exist.
    /// `None` indicates that we can't yet tell whether such a relay exists,
    ///  due to missing information.
25254
    fn id_pair_listed(&self, ed_id: &Ed25519Identity, rsa_id: &RsaIdentity) -> Option<bool> {
25254
        let r = self.by_rsa_id_unchecked(rsa_id);
25254
        match r {
24964
            Some(unchecked) => {
24964
                if !unchecked.rs.ed25519_id_is_usable() {
                    return Some(false);
24964
                }
                // If md is present, then it's listed iff we have the right
                // ed id.  Otherwise we don't know if it's listed.
25482
                unchecked.md.map(|md| md.ed25519_id() == ed_id)
            }
            None => {
                // Definitely not listed.
290
                Some(false)
            }
        }
25254
    }
    /// Check whether a relay exists (or may exist)
    /// with the same identities as those in `target`.
    ///
    /// `Some(true)` indicates that the relay exists.
    /// `Some(false)` indicates that the relay definitely does not exist.
    /// `None` indicates that we can't yet tell whether such a relay exists,
    ///  due to missing information.
8620
    pub fn ids_listed<T>(&self, target: &T) -> Option<bool>
8620
    where
8620
        T: HasRelayIds + ?Sized,
    {
8620
        let rsa_id = target.rsa_identity();
8620
        let ed25519_id = target.ed_identity();
        // TODO: If we later support more identity key types, this will
        // become incorrect.  This assertion might help us recognize that case.
        const _: () = assert!(RelayIdType::COUNT == 2);
8620
        match (rsa_id, ed25519_id) {
8620
            (Some(r), Some(e)) => self.id_pair_listed(e, r),
            (Some(r), None) => Some(self.rsa_id_is_listed(r)),
            (None, Some(e)) => {
                if self.rsidx_by_ed.contains_key(e) {
                    Some(true)
                } else {
                    None
                }
            }
            (None, None) => None,
        }
8620
    }
    /// Return a (possibly [unusable](NetDir#usable)) relay with a given RSA identity.
    ///
    /// This API can be used to find information about a relay that is listed in
    /// the current consensus, even if we don't yet have enough information
    /// (like a microdescriptor) about the relay to use it.
283724
    #[cfg_attr(feature = "experimental-api", visibility::make(pub))]
283724
    #[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
283724
    fn by_rsa_id_unchecked(&self, rsa_id: &RsaIdentity) -> Option<UncheckedRelay<'_>> {
283724
        let rsidx = *self.rsidx_by_rsa.get(rsa_id)?;
281264
        let rs = self.c_relays().get(rsidx).expect("Corrupt index");
281264
        assert_eq!(rs.rsa_identity(), rsa_id);
281264
        Some(self.relay_from_rs_and_rsidx(rs, rsidx))
283724
    }
    /// Return the relay with a given RSA identity, if we have one
    /// and it is [usable](NetDir#usable).
12
    fn by_rsa_id(&self, rsa_id: &RsaIdentity) -> Option<Relay<'_>> {
12
        self.by_rsa_id_unchecked(rsa_id)?.into_relay()
12
    }
    /// Return true if `rsa_id` is listed in this directory, even if it isn't
    /// currently usable.
    ///
    /// (An "[unusable](NetDir#usable)" relay in this context is one for which we don't have full
    /// directory information.)
6
    #[cfg_attr(feature = "experimental-api", visibility::make(pub))]
6
    #[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
6
    fn rsa_id_is_listed(&self, rsa_id: &RsaIdentity) -> bool {
6
        self.by_rsa_id_unchecked(rsa_id).is_some()
6
    }
    /// List the hsdirs in this NetDir, that should be in the HSDir rings
    ///
    /// The results are not returned in any particular order.
    #[cfg(feature = "hs-common")]
10300
    fn all_hsdirs(&self) -> impl Iterator<Item = (RouterStatusIdx, Relay<'_>)> {
393748
        self.c_relays().iter_enumerated().filter_map(|(rsidx, rs)| {
393520
            let relay = self.relay_from_rs_and_rsidx(rs, rsidx);
393520
            relay.is_hsdir_for_ring().then_some(())?;
96376
            let relay = relay.into_relay()?;
96368
            Some((rsidx, relay))
393520
        })
10300
    }
    /// Return the parameters from the consensus, clamped to the
    /// correct ranges, with defaults filled in.
    ///
    /// NOTE: that unsupported parameters aren't returned here; only those
    /// values configured in the `params` module are available.
622644
    pub fn params(&self) -> &NetParameters {
622644
        &self.params
622644
    }
    /// Return a [`ProtoStatus`](netstatus::ProtoStatus) that lists the
    /// network's current requirements and recommendations for the list of
    /// protocols that every relay must implement.
    //
    // TODO HS: I am not sure this is the right API; other alternatives would be:
    //    * To expose the _required_ relay protocol list instead (since that's all that
    //      onion service implementations need).
    //    * To expose the client protocol list as well (for symmetry).
    //    * To expose the MdConsensus instead (since that's more general, although
    //      it restricts the future evolution of this API).
    //
    // I think that this is a reasonably good compromise for now, but I'm going
    // to put it behind the `hs-common` feature to give us time to consider more.
    #[cfg(feature = "hs-common")]
2160
    pub fn relay_protocol_status(&self) -> &netstatus::ProtoStatus {
2160
        self.consensus.relay_protocol_status()
2160
    }
    /// Return a [`ProtoStatus`](netstatus::ProtoStatus) that lists the
    /// network's current requirements and recommendations for the list of
    /// protocols that every relay must implement.
    //
    // TODO HS: See notes on relay_protocol_status above.
    #[cfg(feature = "hs-common")]
    pub fn client_protocol_status(&self) -> &netstatus::ProtoStatus {
        self.consensus.client_protocol_status()
    }
    /// Construct a `CircTarget` from an externally provided list of link specifiers,
    /// and an externally provided onion key.
    ///
    /// This method is used in the onion service protocol,
    /// where introduction points and rendezvous points are specified using these inputs.
    ///
    /// This function is a member of `NetDir` so that it can provide a reasonable list of
    /// [`Protocols`](tor_protover::Protocols) capabilities for the generated `CircTarget`.
    /// It does not (and should not!) look up anything else from the directory.
    #[cfg(feature = "hs-common")]
2160
    pub fn circ_target_from_verbatim_linkspecs(
2160
        &self,
2160
        linkspecs: &[tor_linkspec::EncodedLinkSpec],
2160
        ntor_onion_key: &curve25519::PublicKey,
2160
    ) -> StdResult<VerbatimLinkSpecCircTarget<OwnedCircTarget>, VerbatimCircTargetDecodeError> {
        use VerbatimCircTargetDecodeError as E;
        use tor_linkspec::CircTarget as _;
        use tor_linkspec::decode::Strictness;
2160
        let mut bld = OwnedCircTarget::builder();
        use tor_error::into_internal;
2160
        *bld.chan_target() =
2160
            OwnedChanTargetBuilder::from_encoded_linkspecs(Strictness::Standard, linkspecs)?;
2160
        let protocols = {
2160
            let chan_target = bld.chan_target().build().map_err(into_internal!(
                "from_encoded_linkspecs gave an invalid output"
            ))?;
2160
            match self
2160
                .by_ids_detailed(&chan_target)
2160
                .map_err(E::ImpossibleIds)?
            {
                Some(relay) => relay.protovers().clone(),
2160
                None => self.relay_protocol_status().required_protocols().clone(),
            }
        };
2160
        bld.protocols(protocols);
2160
        bld.ntor_onion_key(*ntor_onion_key);
2160
        Ok(VerbatimLinkSpecCircTarget::new(
2160
            bld.build()
2160
                .map_err(into_internal!("Failed to construct a valid circtarget"))?,
2160
            linkspecs.to_vec(),
        ))
2160
    }
    /// Return weighted the fraction of relays we can use.  We only
    /// consider relays that match the predicate `usable`.  We weight
    /// this bandwidth according to the provided `role`.
    ///
    /// If _no_ matching relays in the consensus have a nonzero
    /// weighted bandwidth value, we fall back to looking at the
    /// unweighted fraction of matching relays.
    ///
    /// If there are no matching relays in the consensus, we return 0.0.
29736
    fn frac_for_role<'a, F>(&'a self, role: WeightRole, usable: F) -> f64
29736
    where
29736
        F: Fn(&UncheckedRelay<'a>) -> bool,
    {
29736
        let mut total_weight = 0_u64;
29736
        let mut have_weight = 0_u64;
29736
        let mut have_count = 0_usize;
29736
        let mut total_count = 0_usize;
1130016
        for r in self.all_relays() {
1130016
            if !usable(&r) {
374560
                continue;
755456
            }
755456
            let w = self.weights.weight_rs_for_role(r.rs, role);
755456
            total_weight += w;
755456
            total_count += 1;
755456
            if r.is_usable() {
752532
                have_weight += w;
752532
                have_count += 1;
752532
            }
        }
29736
        if total_weight > 0 {
            // The consensus lists some weighted bandwidth so return the
            // fraction of the weighted bandwidth for which we have
            // descriptors.
29736
            (have_weight as f64) / (total_weight as f64)
        } else if total_count > 0 {
            // The consensus lists no weighted bandwidth for these relays,
            // but at least it does list relays. Return the fraction of
            // relays for which it we have descriptors.
            (have_count as f64) / (total_count as f64)
        } else {
            // There are no relays of this kind in the consensus.  Return
            // 0.0, to avoid dividing by zero and giving NaN.
            0.0
        }
29736
    }
    /// Return the estimated fraction of possible paths that we have
    /// enough microdescriptors to build.
10118
    fn frac_usable_paths(&self) -> f64 {
        // TODO #504, TODO SPEC: We may want to add a set of is_flagged_fast() and/or
        // is_flagged_stable() checks here.  This will require spec clarification.
379653
        let f_g = self.frac_for_role(WeightRole::Guard, |u| {
379424
            u.low_level_details().is_suitable_as_guard()
379424
        });
10118
        let f_m = self.frac_for_role(WeightRole::Middle, |_| true);
110663
        let f_e = if self.all_relays().any(|u| u.rs.is_flagged_exit()) {
371144
            self.frac_for_role(WeightRole::Exit, |u| u.rs.is_flagged_exit())
        } else {
            // If there are no exits at all, we use f_m here.
624
            f_m
        };
10118
        f_g * f_m * f_e
10118
    }
    /// Return true if there is enough information in this NetDir to build
    /// multihop circuits.
10116
    fn have_enough_paths(&self) -> bool {
        // TODO-A001: This should check for our guards as well, and
        // make sure that if they're listed in the consensus, we have
        // the descriptors for them.
        // If we can build a randomly chosen path with at least this
        // probability, we know enough information to participate
        // on the network.
10116
        let min_frac_paths: f64 = self.params().min_circuit_path_threshold.as_fraction();
        // What fraction of paths can we build?
10116
        let available = self.frac_usable_paths();
10116
        available >= min_frac_paths
10116
    }
    /// Choose a relay at random.
    ///
    /// Each relay is chosen with probability proportional to its weight
    /// in the role `role`, and is only selected if the predicate `usable`
    /// returns true for it.
    ///
    /// This function returns None if (and only if) there are no relays
    /// where `usable` returned true.
    ///
    /// A relay with zero weight will be chosen iff all `usable` relays have
    /// zero weight.
    //
    // TODO this API, with the `usable` closure, invites mistakes where we fail to
    // check conditions that are implied by the role we have selected for the relay:
    // call sites must include a call to `Relay::is_polarity_inverter()` or whatever.
    // IMO the `WeightRole` ought to imply a condition (and it should therefore probably
    // be renamed.)  -Diziet
59604
    pub fn pick_relay<'a, R, P>(
59604
        &'a self,
59604
        rng: &mut R,
59604
        role: WeightRole,
59604
        usable: P,
59604
    ) -> Option<Relay<'a>>
59604
    where
59604
        R: rand::Rng,
59604
        P: FnMut(&Relay<'a>) -> bool,
    {
59604
        let relays: Vec<_> = self.relays().filter(usable).collect();
59604
        tracing::trace!(?role, "picking from {} relays", relays.len());
        // Preemptively check for and handle an empty sequence ourselves, since it's
        // cheap to do so and the `choose_weighted` behavior for this edge-case
        // is a bit unpredictable.
        // See e.g. <https://github.com/rust-random/rand/issues/1783>
59604
        if relays.is_empty() {
66
            tracing::debug!(?role, "No eligible relays");
66
            return None;
59538
        }
        // This algorithm uses rand::distr::WeightedIndex, and uses
        // gives O(n) time and space  to build the index, plus O(log n)
        // sampling time.
        //
        // We might be better off building a WeightedIndex in advance
        // for each `role`, and then sampling it repeatedly until we
        // get a relay that satisfies `usable`.  Or we might not --
        // that depends heavily on the actual particulars of our
        // inputs.  We probably shouldn't make any changes there
        // unless profiling tells us that this function is in a hot
        // path.
        //
        // The C Tor sampling implementation goes through some trouble
        // here to try to make its path selection constant-time.  I
        // believe that there is no actual remotely exploitable
        // side-channel here however.  It could be worth analyzing in
        // the future.
        //
        // This code will give the wrong result if the total of all weights
        // can exceed u64::MAX.  We make sure that can't happen when we
        // set up `self.weights`.
1045812
        match relays[..].choose_weighted(rng, |r| {
1045812
            let weight = self.weights.weight_rs_for_role(r.rs, role);
1045812
            tracing::trace!("relay:{id:?} role:{role:?} weight:{weight}", id = r.id());
1045812
            weight
1045812
        }) {
59538
            Ok(relay) => Some(relay.clone()),
            Err(WeightError::InsufficientNonZero) => {
                warn!(?self.weights, ?role,
                        "After filtering, all {} relays had zero weight. Choosing one at random. See bug #1907.",
                        relays.len());
                relays.choose(rng).cloned()
            }
            Err(e) => {
                warn_report!(
                    e,
                    "Unexpected error while choosing from {} relays for role {:?}",
                    relays.len(),
                    role
                );
                None
            }
        }
59604
    }
    /// Choose `n` items (relays) at random, using the provided weights.
    ///
    /// This is intended as an internal, easier-to-test, implementation of
    /// `pick_n_relays`. `T` is generic for testing, but intended to be `Relay`.
    ///
    /// Items are chosen without replacement: no item will be returned twice.
    ///
    /// If *all* items have zero-weight, then up to `n` will be chosen randomly
    /// and returned. Otherwise, never returns items with zero-weight.
    ///
    /// May return fewer than `n` items if there are fewer than `n` with non-zero weight
    /// (or all have zero-weight but there are fewer than `n` total).
29707
    fn pick_n_weighted<R, T>(rng: &mut R, n: usize, weighted_items: &[(T, u64)]) -> Vec<T>
29707
    where
29707
        R: rand::Rng,
29707
        T: Clone,
    {
29707
        let mut sampled_items = match weighted_items[..]
209630
            .sample_weighted(rng, n, |(_r, w)| *w as f64)
        {
            Err(e) => {
                warn_report!(e, "Unexpected error while sampling a set of items");
                Vec::new()
            }
29707
            Ok(sampled_items) => {
29707
                if sampled_items.len() < n {
                    // Too few items had nonzero weights: return all of those that are okay.
25508
                    let nonzero_weight_items: Vec<_> = weighted_items
25508
                        .iter()
113748
                        .filter_map(|(i, w)| if *w > 0 { Some(i) } else { None })
25508
                        .cloned()
25508
                        .collect();
25508
                    if nonzero_weight_items.is_empty() {
12755
                        tracing::debug!(
                            "All {} items had zero weight! Picking some at random. See bug #1907.",
                            weighted_items.len()
                        );
12755
                        let items: Vec<_> =
12767
                            weighted_items.iter().map(|(i, _w)| i.clone()).collect();
12755
                        if items.len() >= n {
4
                            items.sample(rng, n).cloned().collect()
                        } else {
12751
                            items
                        }
                    } else {
12753
                        tracing::debug!(
                            "After filtering, only had {}/{} items with nonzero weight. Returning them all. See bug #1907.",
                            nonzero_weight_items.len(),
                            weighted_items.len()
                        );
12753
                        nonzero_weight_items
                    }
                } else {
26382
                    sampled_items.map(|(i, _w)| i.clone()).collect()
                }
            }
        };
29707
        sampled_items.shuffle(rng);
29707
        sampled_items
29707
    }
    /// Choose `n` relay at random.
    ///
    /// Each relay is chosen with probability proportional to its weight
    /// in the role `role`, and is only selected if the predicate `usable`
    /// returns true for it.
    ///
    /// Relays are chosen without replacement: no relay will be
    /// returned twice. Therefore, the resulting vector may be smaller
    /// than `n` if we happen to have fewer than `n` appropriate relays.
    ///
    /// Relays with zero-weight will be chosen only if there are *no* usable
    /// relays with nonzero-weight.
    ///
    /// This function returns an empty vector if (and only if) there are no
    /// relays where `usable` returned true.
29695
    pub fn pick_n_relays<'a, R, P>(
29695
        &'a self,
29695
        rng: &mut R,
29695
        n: usize,
29695
        role: WeightRole,
29695
        usable: P,
29695
    ) -> Vec<Relay<'a>>
29695
    where
29695
        R: rand::Rng,
29695
        P: FnMut(&Relay<'a>) -> bool,
    {
29695
        let filtered_weighted_relays: Vec<(Relay<'a>, u64)> = self
29695
            .relays()
29695
            .filter(usable)
209588
            .map(|r| (r.clone(), self.weights.weight_rs_for_role(r.rs, role)))
29695
            .collect();
29695
        let res = NetDir::pick_n_weighted(rng, n, filtered_weighted_relays.as_slice());
29695
        let n_found = res.len();
29695
        if n_found < n {
25498
            warn!(?self.weights, ?role,
                "Requested {n} relays, but only {n_usable} were usable, and only {n_found} were chosen after weighting {role:?}.",
                n_usable=filtered_weighted_relays.len(),
            );
4197
        }
29695
        res
29695
    }
    /// Compute the weight with which `relay` will be selected for a given
    /// `role`.
36002
    pub fn relay_weight<'a>(&'a self, relay: &Relay<'a>, role: WeightRole) -> RelayWeight {
36002
        RelayWeight(self.weights.weight_rs_for_role(relay.rs, role))
36002
    }
    /// Compute the total weight with which any relay matching `usable`
    /// will be selected for a given `role`.
    ///
    /// Note: because this function is used to assess the total
    /// properties of the consensus, the `usable` predicate takes a
    /// [`MdRouterStatus`] rather than a [`Relay`].
24167
    pub fn total_weight<P>(&self, role: WeightRole, usable: P) -> RelayWeight
24167
    where
24167
        P: Fn(&UncheckedRelay<'_>) -> bool,
    {
24167
        self.all_relays()
541070
            .filter_map(|unchecked| {
541070
                if usable(&unchecked) {
232100
                    Some(RelayWeight(
232100
                        self.weights.weight_rs_for_role(unchecked.rs, role),
232100
                    ))
                } else {
308970
                    None
                }
541070
            })
24167
            .sum()
24167
    }
    /// Compute the weight with which a relay with ID `rsa_id` would be
    /// selected for a given `role`.
    ///
    /// Note that weight returned by this function assumes that the
    /// relay with that ID is actually [usable](NetDir#usable); if it isn't usable,
    /// then other weight-related functions will call its weight zero.
256084
    pub fn weight_by_rsa_id(&self, rsa_id: &RsaIdentity, role: WeightRole) -> Option<RelayWeight> {
256084
        self.by_rsa_id_unchecked(rsa_id)
261420
            .map(|unchecked| RelayWeight(self.weights.weight_rs_for_role(unchecked.rs, role)))
256084
    }
    /// Return all relays in this NetDir known to be in the same family as
    /// `relay`.
    ///
    /// This list of members will **not** necessarily include `relay` itself.
    ///
    /// # Limitations
    ///
    /// Two relays only belong to the same family if _each_ relay
    /// claims to share a family with the other.  But if we are
    /// missing a microdescriptor for one of the relays listed by this
    /// relay, we cannot know whether it acknowledges family
    /// membership with this relay or not.  Therefore, this function
    /// can omit family members for which there is not (as yet) any
    /// Relay object.
4
    pub fn known_family_members<'a>(
4
        &'a self,
4
        relay: &'a Relay<'a>,
4
    ) -> impl Iterator<Item = Relay<'a>> {
4
        let relay_rsa_id = relay.rsa_id();
10
        relay.md.family().members().filter_map(move |other_rsa_id| {
8
            self.by_rsa_id(other_rsa_id)
8
                .filter(|other_relay| other_relay.md.family().contains(relay_rsa_id))
8
        })
4
    }
    /// Return the current hidden service directory "time period".
    ///
    /// Specifically, this returns the time period that contains the beginning
    /// of the validity period of this `NetDir`'s consensus.  That time period
    /// is the one we use when acting as an hidden service client.
    #[cfg(feature = "hs-common")]
1728
    pub fn hs_time_period(&self) -> TimePeriod {
1728
        self.hsdir_rings.current.time_period()
1728
    }
    /// Return the [`HsDirParams`] of all the relevant hidden service directory "time periods"
    ///
    /// This includes the current time period (as from
    /// [`.hs_time_period`](NetDir::hs_time_period))
    /// plus additional time periods that we publish descriptors for when we are
    /// acting as a hidden service.
    #[cfg(feature = "hs-service")]
384
    pub fn hs_all_time_periods(&self) -> Vec<HsDirParams> {
384
        self.hsdir_rings
384
            .iter()
776
            .map(|r| r.params().clone())
384
            .collect()
384
    }
    /// Return the relays in this network directory that will be used as hidden service directories
    ///
    /// These are suitable to retrieve a given onion service's descriptor at a given time period.
    #[cfg(feature = "hs-common")]
16
    pub fn hs_dirs_download<'r, R>(
16
        &'r self,
16
        hsid: HsBlindId,
16
        period: TimePeriod,
16
        rng: &mut R,
16
    ) -> std::result::Result<Vec<Relay<'r>>, Bug>
16
    where
16
        R: rand::Rng,
    {
        // Algorithm:
        //
        // 1. Determine which HsDirRing to use, based on the time period.
        // 2. Find the shared random value that's associated with that HsDirRing.
        // 3. Choose spread = the parameter `hsdir_spread_fetch`
        // 4. Let n_replicas = the parameter `hsdir_n_replicas`.
        // 5. Initialize Dirs = []
        // 6. for idx in 1..=n_replicas:
        //       - let H = hsdir_ring::onion_service_index(id, replica, rand,
        //         period).
        //       - Find the position of H within hsdir_ring.
        //       - Take elements from hsdir_ring starting at that position,
        //         adding them to Dirs until we have added `spread` new elements
        //         that were not there before.
        // 7. Shuffle Dirs
        // 8. return Dirs.
16
        let spread = self.spread(HsDirOp::Download);
        // When downloading, only look at relays on current ring.
16
        let ring = &self.hsdir_rings.current;
16
        if ring.params().time_period != period {
            return Err(internal!(
                "our current ring is not associated with the requested time period!"
            ));
16
        }
16
        let mut hs_dirs = self.select_hsdirs(hsid, ring, spread).collect_vec();
        // When downloading, the order of the returned relays is random.
16
        hs_dirs.shuffle(rng);
16
        Ok(hs_dirs)
16
    }
    /// Return the relays in this network directory that will be used as hidden service directories
    ///
    /// Returns the relays that are suitable for storing a given onion service's descriptors at the
    /// given time period.
    #[cfg(feature = "hs-service")]
384
    pub fn hs_dirs_upload(
384
        &self,
384
        hsid: HsBlindId,
384
        period: TimePeriod,
384
    ) -> std::result::Result<impl Iterator<Item = Relay<'_>>, Bug> {
        // Algorithm:
        //
        // 1. Choose spread = the parameter `hsdir_spread_store`
        // 2. Determine which HsDirRing to use, based on the time period.
        // 3. Find the shared random value that's associated with that HsDirRing.
        // 4. Let n_replicas = the parameter `hsdir_n_replicas`.
        // 5. Initialize Dirs = []
        // 6. for idx in 1..=n_replicas:
        //       - let H = hsdir_ring::onion_service_index(id, replica, rand,
        //         period).
        //       - Find the position of H within hsdir_ring.
        //       - Take elements from hsdir_ring starting at that position,
        //         adding them to Dirs until we have added `spread` new elements
        //         that were not there before.
        // 3. return Dirs.
384
        let spread = self.spread(HsDirOp::Upload);
        // For each HsBlindId, determine which HsDirRing to use.
384
        let rings = self
384
            .hsdir_rings
384
            .iter()
392
            .filter_map(move |ring| {
                // Make sure the ring matches the TP of the hsid it's matched with.
384
                (ring.params().time_period == period).then_some((ring, hsid, period))
384
            })
384
            .collect::<Vec<_>>();
        // The specified period should have an associated ring.
392
        if !rings.iter().any(|(_, _, tp)| *tp == period) {
            return Err(internal!(
                "the specified time period does not have an associated ring"
            ));
384
        };
        // Now that we've matched each `hsid` with the ring associated with its TP, we can start
        // selecting replicas from each ring.
392
        Ok(rings.into_iter().flat_map(move |(ring, hsid, period)| {
16
            assert_eq!(period, ring.params().time_period());
16
            self.select_hsdirs(hsid, ring, spread)
16
        }))
384
    }
    /// Return the relays in this network directory that will be used as hidden service directories
    ///
    /// Depending on `op`,
    /// these are suitable to either store, or retrieve, a
    /// given onion service's descriptor at a given time period.
    ///
    /// When `op` is `Download`, the order is random.
    /// When `op` is `Upload`, the order is not specified.
    ///
    /// Return an error if the time period is not one returned by
    /// `onion_service_time_period` or `onion_service_secondary_time_periods`.
    //
    // TODO: make HsDirOp pub(crate) once this is removed
    #[cfg(feature = "hs-common")]
    #[deprecated(note = "Use hs_dirs_upload or hs_dirs_download instead")]
4
    pub fn hs_dirs<'r, R>(&'r self, hsid: &HsBlindId, op: HsDirOp, rng: &mut R) -> Vec<Relay<'r>>
4
    where
4
        R: rand::Rng,
    {
        // Algorithm:
        //
        // 1. Determine which HsDirRing to use, based on the time period.
        // 2. Find the shared random value that's associated with that HsDirRing.
        // 3. Choose spread = the parameter `hsdir_spread_store` or
        //    `hsdir_spread_fetch` based on `op`.
        // 4. Let n_replicas = the parameter `hsdir_n_replicas`.
        // 5. Initialize Dirs = []
        // 6. for idx in 1..=n_replicas:
        //       - let H = hsdir_ring::onion_service_index(id, replica, rand,
        //         period).
        //       - Find the position of H within hsdir_ring.
        //       - Take elements from hsdir_ring starting at that position,
        //         adding them to Dirs until we have added `spread` new elements
        //         that were not there before.
        // 7. return Dirs.
4
        let n_replicas = self
4
            .params
4
            .hsdir_n_replicas
4
            .get()
4
            .try_into()
4
            .expect("BoundedInt did not enforce bounds");
4
        let spread = match op {
2
            HsDirOp::Download => self.params.hsdir_spread_fetch,
            #[cfg(feature = "hs-service")]
2
            HsDirOp::Upload => self.params.hsdir_spread_store,
        };
4
        let spread = spread
4
            .get()
4
            .try_into()
4
            .expect("BoundedInt did not enforce bounds!");
        // TODO: I may be wrong here but I suspect that this function may
        // need refactoring so that it does not look at _all_ of the HsDirRings,
        // but only at the ones that corresponds to time periods for which
        // HsBlindId is valid.  Or I could be mistaken, in which case we should
        // have a comment to explain why I am, since the logic is subtle.
        // (For clients, there is only one ring.) -nickm
        //
        // (Actually, there is no need to follow through with the above TODO,
        // since this function is deprecated, and not used anywhere but the
        // tests.)
4
        let mut hs_dirs = self
4
            .hsdir_rings
4
            .iter_for_op(op)
4
            .cartesian_product(1..=n_replicas) // 1-indexed !
4
            .flat_map({
4
                let mut selected_nodes = HashSet::new();
8
                move |(ring, replica): (&HsDirRing, u8)| {
8
                    let hsdir_idx = hsdir_ring::service_hsdir_index(hsid, replica, ring.params());
44
                    ring.ring_items_at(hsdir_idx, spread, |(hsdir_idx, _)| {
                        // According to rend-spec 2.2.3:
                        //                                                  ... If any of those
                        // nodes have already been selected for a lower-numbered replica of the
                        // service, any nodes already chosen are disregarded (i.e. skipped over)
                        // when choosing a replica's hsdir_spread_store nodes.
44
                        selected_nodes.insert(*hsdir_idx)
44
                    })
8
                    .collect::<Vec<_>>()
8
                }
            })
28
            .filter_map(|(_hsdir_idx, rs_idx)| {
                // This ought not to be None but let's not panic or bail if it is
28
                self.relay_by_rs_idx(*rs_idx)
28
            })
4
            .collect_vec();
4
        match op {
2
            HsDirOp::Download => {
2
                // When `op` is `Download`, the order is random.
2
                hs_dirs.shuffle(rng);
2
            }
            #[cfg(feature = "hs-service")]
2
            HsDirOp::Upload => {
2
                // When `op` is `Upload`, the order is not specified.
2
            }
        }
4
        hs_dirs
4
    }
}
impl MdReceiver for NetDir {
154
    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_> {
154
        Box::new(self.rsidx_by_missing.keys())
154
    }
394944
    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool {
394944
        self.add_arc_microdesc(Arc::new(md))
394944
    }
288
    fn n_missing(&self) -> usize {
288
        self.rsidx_by_missing.len()
288
    }
}
impl<'a> UncheckedRelay<'a> {
    /// Return an [`UncheckedRelayDetails`](details::UncheckedRelayDetails) for this relay.
    ///
    /// Callers should generally avoid using this information directly if they can;
    /// it's better to use a higher-level function that exposes semantic information
    /// rather than these properties.
1037120
    pub fn low_level_details(&self) -> details::UncheckedRelayDetails<'_> {
1037120
        details::UncheckedRelayDetails(self)
1037120
    }
    /// Return true if this relay is valid and [usable](NetDir#usable).
    ///
    /// This function should return `true` for every Relay we expose
    /// to the user.
50219656
    pub fn is_usable(&self) -> bool {
        // No need to check for 'valid' or 'running': they are implicit.
50219656
        self.md.is_some() && self.rs.ed25519_id_is_usable()
50219656
    }
    /// If this is [usable](NetDir#usable), return a corresponding Relay object.
49464200
    pub fn into_relay(self) -> Option<Relay<'a>> {
49464200
        if self.is_usable() {
            Some(Relay {
49464176
                rs: self.rs,
49464176
                md: self.md?,
                #[cfg(feature = "geoip")]
49464176
                cc: self.cc,
            })
        } else {
24
            None
        }
49464200
    }
    /// Return true if this relay is a hidden service directory
    ///
    /// Ie, if it is to be included in the hsdir ring.
    #[cfg(feature = "hs-common")]
393520
    pub(crate) fn is_hsdir_for_ring(&self) -> bool {
        // TODO are there any other flags should we check?
        // rend-spec-v3 2.2.3 says just
        //   "each node listed in the current consensus with the HSDir flag"
        // Do we need to check ed25519_id_is_usable ?
        // See also https://gitlab.torproject.org/tpo/core/arti/-/issues/504
393520
        self.rs.is_flagged_hsdir()
393520
    }
}
impl<'a> Relay<'a> {
    /// Return a [`RelayDetails`](details::RelayDetails) for this relay.
    ///
    /// Callers should generally avoid using this information directly if they can;
    /// it's better to use a higher-level function that exposes semantic information
    /// rather than these properties.
102387574
    pub fn low_level_details(&self) -> details::RelayDetails<'_> {
102387574
        details::RelayDetails(self)
102387574
    }
    /// Return the Ed25519 ID for this relay.
151177630
    pub fn id(&self) -> &Ed25519Identity {
151177630
        self.md.ed25519_id()
151177630
    }
    /// Return the RsaIdentity for this relay.
97968048
    pub fn rsa_id(&self) -> &RsaIdentity {
97968048
        self.rs.rsa_identity()
97968048
    }
    /// Return a reference to this relay's "router status" entry in
    /// the consensus.
    ///
    /// The router status entry contains information about the relay
    /// that the authorities voted on directly.  For most use cases,
    /// you shouldn't need them.
    ///
    /// This function is only available if the crate was built with
    /// its `experimental-api` feature.
    #[cfg(feature = "experimental-api")]
4
    pub fn rs(&self) -> &netstatus::MdRouterStatus {
4
        self.rs
4
    }
    /// Return a reference to this relay's "microdescriptor" entry in
    /// the consensus.
    ///
    /// A "microdescriptor" is a synopsis of the information about a relay,
    /// used to determine its capabilities and route traffic through it.
    /// For most use cases, you shouldn't need it.
    ///
    /// This function is only available if the crate was built with
    /// its `experimental-api` feature.
    #[cfg(feature = "experimental-api")]
4
    pub fn md(&self) -> &MicrodescAndHash {
4
        self.md
4
    }
}
/// An error value returned from [`NetDir::by_ids_detailed`].
#[cfg(feature = "hs-common")]
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RelayLookupError {
    /// We found a relay whose presence indicates that the provided set of
    /// identities is impossible to resolve.
    #[error("Provided set of identities is impossible according to consensus.")]
    Impossible,
}
impl<'a> HasAddrs for Relay<'a> {
138212922
    fn addrs(&self) -> impl Iterator<Item = std::net::SocketAddr> {
138212922
        self.rs.addrs()
138212922
    }
}
#[cfg(feature = "geoip")]
impl<'a> HasCountryCode for Relay<'a> {
864
    fn country_code(&self) -> Option<CountryCode> {
864
        self.cc
864
    }
}
impl<'a> tor_linkspec::HasRelayIdsLegacy for Relay<'a> {
151165426
    fn ed_identity(&self) -> &Ed25519Identity {
151165426
        self.id()
151165426
    }
45754102
    fn rsa_identity(&self) -> &RsaIdentity {
45754102
        self.rsa_id()
45754102
    }
}
impl<'a> HasRelayIds for UncheckedRelay<'a> {
    fn identity(&self, key_type: RelayIdType) -> Option<RelayIdRef<'_>> {
        match key_type {
            RelayIdType::Ed25519 if self.rs.ed25519_id_is_usable() => {
                self.md.map(|m| m.ed25519_id().into())
            }
            RelayIdType::Rsa => Some(self.rs.rsa_identity().into()),
            _ => None,
        }
    }
}
#[cfg(feature = "geoip")]
impl<'a> HasCountryCode for UncheckedRelay<'a> {
    fn country_code(&self) -> Option<CountryCode> {
        self.cc
    }
}
impl<'a> DirectChanMethodsHelper for Relay<'a> {}
impl<'a> ChanTarget for Relay<'a> {}
impl<'a> tor_linkspec::CircTarget for Relay<'a> {
1801440
    fn ntor_onion_key(&self) -> &ll::pk::curve25519::PublicKey {
1801440
        self.md.ntor_key()
1801440
    }
1797360
    fn protovers(&self) -> &tor_protover::Protocols {
1797360
        self.rs.protovers()
1797360
    }
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;
    use crate::testnet::*;
    use float_eq::assert_float_eq;
    use std::collections::HashSet;
    use std::time::Duration;
    use tor_basic_utils::test_rng::{self, testing_rng};
    use tor_linkspec::{RelayIdType, RelayIds};
    #[cfg(feature = "hs-common")]
    fn dummy_hs_blind_id() -> HsBlindId {
        let hsid = [2, 1, 1, 1].iter().cycle().take(32).cloned().collect_vec();
        let hsid = Ed25519Identity::new(hsid[..].try_into().unwrap());
        HsBlindId::from(hsid)
    }
    // Basic functionality for a partial netdir: Add microdescriptors,
    // then you have a netdir.
    #[test]
    fn partial_netdir() {
        let (consensus, microdescs) = construct_network().unwrap();
        let dir = PartialNetDir::new(consensus, None);
        // Check the lifetime
        let lifetime = dir.lifetime();
        assert_eq!(
            lifetime
                .valid_until()
                .duration_since(lifetime.valid_after())
                .unwrap(),
            Duration::new(86400, 0)
        );
        // No microdescriptors, so we don't have enough paths, and can't
        // advance.
        assert!(!dir.have_enough_paths());
        let mut dir = match dir.unwrap_if_sufficient() {
            Ok(_) => panic!(),
            Err(d) => d,
        };
        let missing: HashSet<_> = dir.missing_microdescs().collect();
        assert_eq!(missing.len(), 40);
        assert_eq!(missing.len(), dir.netdir.c_relays().len());
        for md in &microdescs {
            assert!(missing.contains(md.digest()));
        }
        // Now add all the mds and try again.
        for md in microdescs {
            let wanted = dir.add_microdesc(md);
            assert!(wanted);
        }
        let missing: HashSet<_> = dir.missing_microdescs().collect();
        assert!(missing.is_empty());
        assert!(dir.have_enough_paths());
        let _complete = match dir.unwrap_if_sufficient() {
            Ok(d) => d,
            Err(_) => panic!(),
        };
    }
    #[test]
    fn override_params() {
        let (consensus, _microdescs) = construct_network().unwrap();
        let override_p = "bwweightscale=2 doesnotexist=77 circwindow=500"
            .parse()
            .unwrap();
        let dir = PartialNetDir::new(consensus.clone(), Some(&override_p));
        let params = &dir.netdir.params;
        assert_eq!(params.bw_weight_scale.get(), 2);
        assert_eq!(params.circuit_window.get(), 500_i32);
        // try again without the override.
        let dir = PartialNetDir::new(consensus, None);
        let params = &dir.netdir.params;
        assert_eq!(params.bw_weight_scale.get(), 1_i32);
        assert_eq!(params.circuit_window.get(), 1000_i32);
    }
    #[test]
    fn fill_from_previous() {
        let (consensus, microdescs) = construct_network().unwrap();
        let mut dir = PartialNetDir::new(consensus.clone(), None);
        for md in microdescs.iter().skip(2) {
            let wanted = dir.add_microdesc(md.clone());
            assert!(wanted);
        }
        let dir1 = dir.unwrap_if_sufficient().unwrap();
        assert_eq!(dir1.missing_microdescs().count(), 2);
        let mut dir = PartialNetDir::new(consensus, None);
        assert_eq!(dir.missing_microdescs().count(), 40);
        dir.fill_from_previous_netdir(Arc::new(dir1));
        assert_eq!(dir.missing_microdescs().count(), 2);
    }
    #[test]
    fn path_count() {
        let low_threshold = "min_paths_for_circs_pct=64".parse().unwrap();
        let high_threshold = "min_paths_for_circs_pct=65".parse().unwrap();
        let (consensus, microdescs) = construct_network().unwrap();
        let mut dir = PartialNetDir::new(consensus.clone(), Some(&low_threshold));
        for (pos, md) in microdescs.iter().enumerate() {
            if pos % 7 == 2 {
                continue; // skip a few relays.
            }
            dir.add_microdesc(md.clone());
        }
        let dir = dir.unwrap_if_sufficient().unwrap();
        // We  have 40 relays that we know about from the consensus.
        assert_eq!(dir.all_relays().count(), 40);
        // But only 34 are usable.
        assert_eq!(dir.relays().count(), 34);
        // For guards: mds 20..=39 correspond to Guard relays.
        // Their bandwidth is 2*(1000+2000+...10000) = 110_000.
        // We skipped 23, 30, and 37.  They have bandwidth
        // 4000 + 1000 + 8000 = 13_000.  So our fractional bandwidth
        // should be (110-13)/110.
        let f = dir.frac_for_role(WeightRole::Guard, |u| u.rs.is_flagged_guard());
        assert!(((97.0 / 110.0) - f).abs() < 0.000001);
        // For exits: mds 10..=19 and 30..=39 correspond to Exit relays.
        // We skipped 16, 30,  and 37. Per above our fractional bandwidth is
        // (110-16)/110.
        let f = dir.frac_for_role(WeightRole::Exit, |u| u.rs.is_flagged_exit());
        assert!(((94.0 / 110.0) - f).abs() < 0.000001);
        // For middles: all relays are middles. We skipped 2, 9, 16,
        // 23, 30, and 37. Per above our fractional bandwidth is
        // (220-33)/220
        let f = dir.frac_for_role(WeightRole::Middle, |_| true);
        assert!(((187.0 / 220.0) - f).abs() < 0.000001);
        // Multiplying those together, we get the fraction of paths we can
        // build at ~0.64052066, which is above the threshold we set above for
        // MinPathsForCircsPct.
        let f = dir.frac_usable_paths();
        assert!((f - 0.64052066).abs() < 0.000001);
        // But if we try again with a slightly higher threshold...
        let mut dir = PartialNetDir::new(consensus, Some(&high_threshold));
        for (pos, md) in microdescs.into_iter().enumerate() {
            if pos % 7 == 2 {
                continue; // skip a few relays.
            }
            dir.add_microdesc(md);
        }
        assert!(dir.unwrap_if_sufficient().is_err());
    }
    /// Return a 3-tuple for use by `test_pick_*()` of an Rng, a number of
    /// iterations, and a tolerance.
    ///
    /// If the Rng is deterministic (the default), we can use a faster setup,
    /// with a higher tolerance and fewer iterations.  But if you've explicitly
    /// opted into randomization (or are replaying a seed from an earlier
    /// randomized test), we give you more iterations and a tighter tolerance.
    fn testing_rng_with_tolerances() -> (impl rand::Rng, usize, f64) {
        // Use a deterministic RNG if none is specified, since this is slow otherwise.
        let config = test_rng::Config::from_env().unwrap_or(test_rng::Config::Deterministic);
        let (iters, tolerance) = match config {
            test_rng::Config::Deterministic => (5000, 0.02),
            _ => (50000, 0.01),
        };
        (config.into_rng(), iters, tolerance)
    }
    #[test]
    fn test_pick() {
        let (consensus, microdescs) = construct_network().unwrap();
        let mut dir = PartialNetDir::new(consensus, None);
        for md in microdescs.into_iter() {
            let wanted = dir.add_microdesc(md.clone());
            assert!(wanted);
        }
        let dir = dir.unwrap_if_sufficient().unwrap();
        let (mut rng, total, tolerance) = testing_rng_with_tolerances();
        let mut picked = [0_isize; 40];
        for _ in 0..total {
            let r = dir.pick_relay(&mut rng, WeightRole::Middle, |r| {
                r.low_level_details().supports_exit_port_ipv4(80)
            });
            let r = r.unwrap();
            let id_byte = r.identity(RelayIdType::Rsa).unwrap().as_bytes()[0];
            picked[id_byte as usize] += 1;
        }
        // non-exits should never get picked.
        picked[0..10].iter().for_each(|x| assert_eq!(*x, 0));
        picked[20..30].iter().for_each(|x| assert_eq!(*x, 0));
        let picked_f: Vec<_> = picked.iter().map(|x| *x as f64 / total as f64).collect();
        // We didn't we any non-default weights, so the other relays get
        // weighted proportional to their bandwidth.
        assert_float_eq!(picked_f[19], (10.0 / 110.0), abs <= tolerance);
        assert_float_eq!(picked_f[38], (9.0 / 110.0), abs <= tolerance);
        assert_float_eq!(picked_f[39], (10.0 / 110.0), abs <= tolerance);
    }
    #[test]
    fn test_pick_multiple() {
        // This is mostly a copy of test_pick, except that it uses
        // pick_n_relays to pick several relays at once.
        let dir = construct_netdir().unwrap_if_sufficient().unwrap();
        let (mut rng, total, tolerance) = testing_rng_with_tolerances();
        let mut picked = [0_isize; 40];
        for _ in 0..total / 4 {
            let relays = dir.pick_n_relays(&mut rng, 4, WeightRole::Middle, |r| {
                r.low_level_details().supports_exit_port_ipv4(80)
            });
            assert_eq!(relays.len(), 4);
            for r in relays {
                let id_byte = r.identity(RelayIdType::Rsa).unwrap().as_bytes()[0];
                picked[id_byte as usize] += 1;
            }
        }
        // non-exits should never get picked.
        picked[0..10].iter().for_each(|x| assert_eq!(*x, 0));
        picked[20..30].iter().for_each(|x| assert_eq!(*x, 0));
        let picked_f: Vec<_> = picked.iter().map(|x| *x as f64 / total as f64).collect();
        // We didn't we any non-default weights, so the other relays get
        // weighted proportional to their bandwidth.
        assert_float_eq!(picked_f[19], (10.0 / 110.0), abs <= tolerance);
        assert_float_eq!(picked_f[36], (7.0 / 110.0), abs <= tolerance);
        assert_float_eq!(picked_f[39], (10.0 / 110.0), abs <= tolerance);
    }
    #[test]
    fn test_pick_multiple_from_insufficient() {
        // This is intended to test `NetDir::pick_n_relays`, but targets the internal,
        // easier-to-test `NetDir::pick_n_weighted` that is used to implement it.
        let mut rng = testing_rng();
        // If *any* item (relay) has non-zero weight, then we return only those, even if we asked for more.
        let mostly_zeros = vec![("dud1", 0), ("dud2", 0), ("ok", 1), ("dud3", 0)];
        for n in [1, 2, 10] {
            assert_eq!(
                NetDir::pick_n_weighted(&mut rng, n, &mostly_zeros[..]),
                vec!["ok"],
                "where n={n}"
            );
        }
        // If *all* items have zero weight, and we ask for as many or more than
        // we have, we get back all of them.
        let all_zeros = vec![("dud1", 0), ("dud2", 0), ("dud3", 0)];
        let all_zeros_items = all_zeros.iter().map(|(x, _w)| *x).collect::<Vec<_>>();
        for n in [all_zeros.len(), all_zeros.len() + 10] {
            let mut res = NetDir::pick_n_weighted(&mut rng, n, &all_zeros[..]);
            res.sort();
            assert_eq!(res, all_zeros_items, "where n={n}");
        }
        // If *all* items have zero weight, and we ask for fewer than we have,
        // we get back as many as we asked for.
        let n = all_zeros.len() / 2;
        let res = NetDir::pick_n_weighted(&mut rng, n, &all_zeros[..]);
        assert_eq!(res.len(), n);
    }
    #[test]
    fn subnets() {
        let cfg = SubnetConfig::default();
        fn same_net(cfg: &SubnetConfig, a: &str, b: &str) -> bool {
            cfg.addrs_in_same_subnet(&a.parse().unwrap(), &b.parse().unwrap())
        }
        assert!(same_net(&cfg, "127.15.3.3", "127.15.9.9"));
        assert!(!same_net(&cfg, "127.15.3.3", "127.16.9.9"));
        assert!(!same_net(&cfg, "127.15.3.3", "127::"));
        assert!(same_net(&cfg, "ffff:ffff:90:33::", "ffff:ffff:91:34::"));
        assert!(!same_net(&cfg, "ffff:ffff:90:33::", "ffff:fffe:91:34::"));
        let cfg = SubnetConfig {
            subnets_family_v4: 32,
            subnets_family_v6: 128,
        };
        assert!(!same_net(&cfg, "127.15.3.3", "127.15.9.9"));
        assert!(!same_net(&cfg, "ffff:ffff:90:33::", "ffff:ffff:91:34::"));
        assert!(same_net(&cfg, "127.0.0.1", "127.0.0.1"));
        assert!(!same_net(&cfg, "127.0.0.1", "127.0.0.2"));
        assert!(same_net(&cfg, "ffff:ffff:90:33::", "ffff:ffff:90:33::"));
        let cfg = SubnetConfig {
            subnets_family_v4: 33,
            subnets_family_v6: 129,
        };
        assert!(!same_net(&cfg, "127.0.0.1", "127.0.0.1"));
        assert!(!same_net(&cfg, "::", "::"));
    }
    #[test]
    fn subnet_union() {
        let cfg1 = SubnetConfig {
            subnets_family_v4: 16,
            subnets_family_v6: 64,
        };
        let cfg2 = SubnetConfig {
            subnets_family_v4: 24,
            subnets_family_v6: 32,
        };
        let a1 = "1.2.3.4".parse().unwrap();
        let a2 = "1.2.10.10".parse().unwrap();
        let a3 = "ffff:ffff::7".parse().unwrap();
        let a4 = "ffff:ffff:1234::8".parse().unwrap();
        assert_eq!(cfg1.addrs_in_same_subnet(&a1, &a2), true);
        assert_eq!(cfg2.addrs_in_same_subnet(&a1, &a2), false);
        assert_eq!(cfg1.addrs_in_same_subnet(&a3, &a4), false);
        assert_eq!(cfg2.addrs_in_same_subnet(&a3, &a4), true);
        let cfg_u = cfg1.union(&cfg2);
        assert_eq!(
            cfg_u,
            SubnetConfig {
                subnets_family_v4: 16,
                subnets_family_v6: 32,
            }
        );
        assert_eq!(cfg_u.addrs_in_same_subnet(&a1, &a2), true);
        assert_eq!(cfg_u.addrs_in_same_subnet(&a3, &a4), true);
        assert_eq!(cfg1.union(&cfg1), cfg1);
        assert_eq!(cfg1.union(&SubnetConfig::no_addresses_match()), cfg1);
    }
    #[test]
    fn relay_funcs() {
        let (consensus, microdescs) = construct_custom_network(
            |pos, nb, _| {
                if pos == 15 {
                    nb.rs.add_or_port("[f0f0::30]:9001".parse().unwrap());
                } else if pos == 20 {
                    nb.rs.add_or_port("[f0f0::3131]:9001".parse().unwrap());
                }
            },
            None,
        )
        .unwrap();
        let subnet_config = SubnetConfig::default();
        let all_family_info = FamilyRules::all_family_info();
        let mut dir = PartialNetDir::new(consensus, None);
        for md in microdescs.into_iter() {
            let wanted = dir.add_microdesc(md.clone());
            assert!(wanted);
        }
        let dir = dir.unwrap_if_sufficient().unwrap();
        // Pick out a few relays by ID.
        let k0 = Ed25519Identity::from([0; 32]);
        let k1 = Ed25519Identity::from([1; 32]);
        let k2 = Ed25519Identity::from([2; 32]);
        let k3 = Ed25519Identity::from([3; 32]);
        let k10 = Ed25519Identity::from([10; 32]);
        let k15 = Ed25519Identity::from([15; 32]);
        let k20 = Ed25519Identity::from([20; 32]);
        let r0 = dir.by_id(&k0).unwrap();
        let r1 = dir.by_id(&k1).unwrap();
        let r2 = dir.by_id(&k2).unwrap();
        let r3 = dir.by_id(&k3).unwrap();
        let r10 = dir.by_id(&k10).unwrap();
        let r15 = dir.by_id(&k15).unwrap();
        let r20 = dir.by_id(&k20).unwrap();
        assert_eq!(r0.id(), &[0; 32].into());
        assert_eq!(r0.rsa_id(), &[0; 20].into());
        assert_eq!(r1.id(), &[1; 32].into());
        assert_eq!(r1.rsa_id(), &[1; 20].into());
        assert!(r0.same_relay_ids(&r0));
        assert!(r1.same_relay_ids(&r1));
        assert!(!r1.same_relay_ids(&r0));
        assert!(r0.low_level_details().is_dir_cache());
        assert!(!r1.low_level_details().is_dir_cache());
        assert!(r2.low_level_details().is_dir_cache());
        assert!(!r3.low_level_details().is_dir_cache());
        assert!(!r0.low_level_details().supports_exit_port_ipv4(80));
        assert!(!r1.low_level_details().supports_exit_port_ipv4(80));
        assert!(!r2.low_level_details().supports_exit_port_ipv4(80));
        assert!(!r3.low_level_details().supports_exit_port_ipv4(80));
        assert!(!r0.low_level_details().policies_allow_some_port());
        assert!(!r1.low_level_details().policies_allow_some_port());
        assert!(!r2.low_level_details().policies_allow_some_port());
        assert!(!r3.low_level_details().policies_allow_some_port());
        assert!(r10.low_level_details().policies_allow_some_port());
        assert!(r0.low_level_details().in_same_family(&r0, all_family_info));
        assert!(r0.low_level_details().in_same_family(&r1, all_family_info));
        assert!(r1.low_level_details().in_same_family(&r0, all_family_info));
        assert!(r1.low_level_details().in_same_family(&r1, all_family_info));
        assert!(!r0.low_level_details().in_same_family(&r2, all_family_info));
        assert!(!r2.low_level_details().in_same_family(&r0, all_family_info));
        assert!(r2.low_level_details().in_same_family(&r2, all_family_info));
        assert!(r2.low_level_details().in_same_family(&r3, all_family_info));
        assert!(r0.low_level_details().in_same_subnet(&r10, &subnet_config));
        assert!(r10.low_level_details().in_same_subnet(&r10, &subnet_config));
        assert!(r0.low_level_details().in_same_subnet(&r0, &subnet_config));
        assert!(r1.low_level_details().in_same_subnet(&r1, &subnet_config));
        assert!(!r1.low_level_details().in_same_subnet(&r2, &subnet_config));
        assert!(!r2.low_level_details().in_same_subnet(&r3, &subnet_config));
        // Make sure IPv6 families work.
        let subnet_config = SubnetConfig {
            subnets_family_v4: 128,
            subnets_family_v6: 96,
        };
        assert!(r15.low_level_details().in_same_subnet(&r20, &subnet_config));
        assert!(!r15.low_level_details().in_same_subnet(&r1, &subnet_config));
        // Make sure that subnet configs can be disabled.
        let subnet_config = SubnetConfig {
            subnets_family_v4: 255,
            subnets_family_v6: 255,
        };
        assert!(!r15.low_level_details().in_same_subnet(&r20, &subnet_config));
    }
    #[test]
    fn test_badexit() {
        // make a netdir where relays 10-19 are badexit, and everybody
        // exits to 443 on IPv6.
        use tor_netdoc::types::relay_flags::RelayFlag;
        let netdir = construct_custom_netdir(|pos, nb, _| {
            if (10..20).contains(&pos) {
                nb.rs.add_flags(RelayFlag::BadExit);
            }
            nb.md.parse_ipv6_policy("accept 443").unwrap();
        })
        .unwrap()
        .unwrap_if_sufficient()
        .unwrap();
        let e12 = netdir.by_id(&Ed25519Identity::from([12; 32])).unwrap();
        let e32 = netdir.by_id(&Ed25519Identity::from([32; 32])).unwrap();
        assert!(!e12.low_level_details().supports_exit_port_ipv4(80));
        assert!(e32.low_level_details().supports_exit_port_ipv4(80));
        assert!(!e12.low_level_details().supports_exit_port_ipv6(443));
        assert!(e32.low_level_details().supports_exit_port_ipv6(443));
        assert!(!e32.low_level_details().supports_exit_port_ipv6(555));
        assert!(!e12.low_level_details().policies_allow_some_port());
        assert!(e32.low_level_details().policies_allow_some_port());
        assert!(!e12.low_level_details().ipv4_policy().allows_some_port());
        assert!(!e12.low_level_details().ipv6_policy().allows_some_port());
        assert!(e32.low_level_details().ipv4_policy().allows_some_port());
        assert!(e32.low_level_details().ipv6_policy().allows_some_port());
        assert!(
            e12.low_level_details()
                .ipv4_declared_policy()
                .allows_some_port()
        );
        assert!(
            e12.low_level_details()
                .ipv6_declared_policy()
                .allows_some_port()
        );
    }
    #[cfg(feature = "experimental-api")]
    #[test]
    fn test_accessors() {
        let netdir = construct_netdir().unwrap_if_sufficient().unwrap();
        let r4 = netdir.by_id(&Ed25519Identity::from([4; 32])).unwrap();
        let r16 = netdir.by_id(&Ed25519Identity::from([16; 32])).unwrap();
        assert!(!r4.md().ipv4_policy().allows_some_port());
        assert!(r16.md().ipv4_policy().allows_some_port());
        assert!(!r4.rs().is_flagged_exit());
        assert!(r16.rs().is_flagged_exit());
    }
    #[test]
    fn test_by_id() {
        // Make a netdir that omits the microdescriptor for 0xDDDDDD...
        let netdir = construct_custom_netdir(|pos, nb, _| {
            nb.omit_md = pos == 13;
        })
        .unwrap();
        let netdir = netdir.unwrap_if_sufficient().unwrap();
        let r = netdir.by_id(&Ed25519Identity::from([0; 32])).unwrap();
        assert_eq!(r.id().as_bytes(), &[0; 32]);
        assert!(netdir.by_id(&Ed25519Identity::from([13; 32])).is_none());
        let r = netdir.by_rsa_id(&[12; 20].into()).unwrap();
        assert_eq!(r.rsa_id().as_bytes(), &[12; 20]);
        assert!(netdir.rsa_id_is_listed(&[12; 20].into()));
        assert!(netdir.by_rsa_id(&[13; 20].into()).is_none());
        assert!(netdir.by_rsa_id_unchecked(&[99; 20].into()).is_none());
        assert!(!netdir.rsa_id_is_listed(&[99; 20].into()));
        let r = netdir.by_rsa_id_unchecked(&[13; 20].into()).unwrap();
        assert_eq!(r.rs.rsa_identity().as_bytes(), &[13; 20]);
        assert!(netdir.rsa_id_is_listed(&[13; 20].into()));
        let pair_13_13 = RelayIds::builder()
            .ed_identity([13; 32].into())
            .rsa_identity([13; 20].into())
            .build()
            .unwrap();
        let pair_14_14 = RelayIds::builder()
            .ed_identity([14; 32].into())
            .rsa_identity([14; 20].into())
            .build()
            .unwrap();
        let pair_14_99 = RelayIds::builder()
            .ed_identity([14; 32].into())
            .rsa_identity([99; 20].into())
            .build()
            .unwrap();
        let r = netdir.by_ids(&pair_13_13);
        assert!(r.is_none());
        let r = netdir.by_ids(&pair_14_14).unwrap();
        assert_eq!(r.identity(RelayIdType::Rsa).unwrap().as_bytes(), &[14; 20]);
        assert_eq!(
            r.identity(RelayIdType::Ed25519).unwrap().as_bytes(),
            &[14; 32]
        );
        let r = netdir.by_ids(&pair_14_99);
        assert!(r.is_none());
        assert_eq!(
            netdir.id_pair_listed(&[13; 32].into(), &[13; 20].into()),
            None
        );
        assert_eq!(
            netdir.id_pair_listed(&[15; 32].into(), &[15; 20].into()),
            Some(true)
        );
        assert_eq!(
            netdir.id_pair_listed(&[15; 32].into(), &[99; 20].into()),
            Some(false)
        );
    }
    #[test]
    #[cfg(feature = "hs-common")]
    fn test_by_ids_detailed() {
        // Make a netdir that omits the microdescriptor for 0xDDDDDD...
        let netdir = construct_custom_netdir(|pos, nb, _| {
            nb.omit_md = pos == 13;
        })
        .unwrap();
        let netdir = netdir.unwrap_if_sufficient().unwrap();
        let id13_13 = RelayIds::builder()
            .ed_identity([13; 32].into())
            .rsa_identity([13; 20].into())
            .build()
            .unwrap();
        let id15_15 = RelayIds::builder()
            .ed_identity([15; 32].into())
            .rsa_identity([15; 20].into())
            .build()
            .unwrap();
        let id15_99 = RelayIds::builder()
            .ed_identity([15; 32].into())
            .rsa_identity([99; 20].into())
            .build()
            .unwrap();
        let id99_15 = RelayIds::builder()
            .ed_identity([99; 32].into())
            .rsa_identity([15; 20].into())
            .build()
            .unwrap();
        let id99_99 = RelayIds::builder()
            .ed_identity([99; 32].into())
            .rsa_identity([99; 20].into())
            .build()
            .unwrap();
        let id15_xx = RelayIds::builder()
            .ed_identity([15; 32].into())
            .build()
            .unwrap();
        let idxx_15 = RelayIds::builder()
            .rsa_identity([15; 20].into())
            .build()
            .unwrap();
        assert!(matches!(netdir.by_ids_detailed(&id13_13), Ok(None)));
        assert!(matches!(netdir.by_ids_detailed(&id15_15), Ok(Some(_))));
        assert!(matches!(
            netdir.by_ids_detailed(&id15_99),
            Err(RelayLookupError::Impossible)
        ));
        assert!(matches!(
            netdir.by_ids_detailed(&id99_15),
            Err(RelayLookupError::Impossible)
        ));
        assert!(matches!(netdir.by_ids_detailed(&id99_99), Ok(None)));
        assert!(matches!(netdir.by_ids_detailed(&id15_xx), Ok(Some(_))));
        assert!(matches!(netdir.by_ids_detailed(&idxx_15), Ok(Some(_))));
    }
    #[test]
    fn weight_type() {
        let r0 = RelayWeight(0);
        let r100 = RelayWeight(100);
        let r200 = RelayWeight(200);
        let r300 = RelayWeight(300);
        assert_eq!(r100 + r200, r300);
        assert_eq!(r100.checked_div(r200), Some(0.5));
        assert!(r100.checked_div(r0).is_none());
        assert_eq!(r200.ratio(0.5), Some(r100));
        assert!(r200.ratio(-1.0).is_none());
    }
    #[test]
    fn weight_accessors() {
        // Make a netdir that omits the microdescriptor for 0xDDDDDD...
        let netdir = construct_netdir().unwrap_if_sufficient().unwrap();
        let g_total = netdir.total_weight(WeightRole::Guard, |r| r.rs.is_flagged_guard());
        // This is just the total guard weight, since all our Wxy = 1.
        assert_eq!(g_total, RelayWeight(110_000));
        let g_total = netdir.total_weight(WeightRole::Guard, |_| false);
        assert_eq!(g_total, RelayWeight(0));
        let relay = netdir.by_id(&Ed25519Identity::from([35; 32])).unwrap();
        assert!(relay.rs.is_flagged_guard());
        let w = netdir.relay_weight(&relay, WeightRole::Guard);
        assert_eq!(w, RelayWeight(6_000));
        let w = netdir
            .weight_by_rsa_id(&[33; 20].into(), WeightRole::Guard)
            .unwrap();
        assert_eq!(w, RelayWeight(4_000));
        assert!(
            netdir
                .weight_by_rsa_id(&[99; 20].into(), WeightRole::Guard)
                .is_none()
        );
    }
    #[test]
    fn family_list() {
        let netdir = construct_custom_netdir(|pos, n, _| {
            if pos == 0x0a {
                n.md.family(
                    "$0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B \
                     $0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C \
                     $0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D0D"
                        .parse()
                        .unwrap(),
                );
            } else if pos == 0x0c {
                n.md.family("$0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A0A".parse().unwrap());
            }
        })
        .unwrap()
        .unwrap_if_sufficient()
        .unwrap();
        // In the testing netdir, adjacent members are in the same family by default...
        let r0 = netdir.by_id(&Ed25519Identity::from([0; 32])).unwrap();
        let family: Vec<_> = netdir.known_family_members(&r0).collect();
        assert_eq!(family.len(), 1);
        assert_eq!(family[0].id(), &Ed25519Identity::from([1; 32]));
        // But we've made this relay claim membership with several others.
        let r10 = netdir.by_id(&Ed25519Identity::from([10; 32])).unwrap();
        let family: HashSet<_> = netdir.known_family_members(&r10).map(|r| *r.id()).collect();
        assert_eq!(family.len(), 2);
        assert!(family.contains(&Ed25519Identity::from([11; 32])));
        assert!(family.contains(&Ed25519Identity::from([12; 32])));
        // Note that 13 doesn't get put in, even though it's listed, since it doesn't claim
        //  membership with 10.
    }
    #[test]
    #[cfg(feature = "geoip")]
    fn relay_has_country_code() {
        let src_v6 = r#"
        fe80:dead:beef::,fe80:dead:ffff::,US
        fe80:feed:eeee::1,fe80:feed:eeee::1,AT
        fe80:feed:eeee::2,fe80:feed:ffff::,DE
        "#;
        let db = GeoipDb::new_from_legacy_format("", src_v6, true).unwrap();
        let netdir = construct_custom_netdir_with_geoip(
            |pos, n, _| {
                if pos == 0x01 {
                    n.rs.add_or_port("[fe80:dead:beef::1]:42".parse().unwrap());
                }
                if pos == 0x02 {
                    n.rs.add_or_port("[fe80:feed:eeee::1]:42".parse().unwrap());
                    n.rs.add_or_port("[fe80:feed:eeee::2]:42".parse().unwrap());
                }
                if pos == 0x03 {
                    n.rs.add_or_port("[fe80:dead:beef::1]:42".parse().unwrap());
                    n.rs.add_or_port("[fe80:dead:beef::2]:42".parse().unwrap());
                }
            },
            &db,
        )
        .unwrap()
        .unwrap_if_sufficient()
        .unwrap();
        // No GeoIP data available -> None
        let r0 = netdir.by_id(&Ed25519Identity::from([0; 32])).unwrap();
        assert_eq!(r0.cc, None);
        // Exactly one match -> Some
        let r1 = netdir.by_id(&Ed25519Identity::from([1; 32])).unwrap();
        assert_eq!(r1.cc.as_ref().map(|x| x.as_ref()), Some("US"));
        // Conflicting matches -> None
        let r2 = netdir.by_id(&Ed25519Identity::from([2; 32])).unwrap();
        assert_eq!(r2.cc, None);
        // Multiple agreeing matches -> Some
        let r3 = netdir.by_id(&Ed25519Identity::from([3; 32])).unwrap();
        assert_eq!(r3.cc.as_ref().map(|x| x.as_ref()), Some("US"));
    }
    #[test]
    #[cfg(feature = "hs-common")]
    #[allow(deprecated)]
    fn hs_dirs_selection() {
        use tor_basic_utils::test_rng::testing_rng;
        const HSDIR_SPREAD_STORE: i32 = 6;
        const HSDIR_SPREAD_FETCH: i32 = 2;
        const PARAMS: [(&str, i32); 2] = [
            ("hsdir_spread_store", HSDIR_SPREAD_STORE),
            ("hsdir_spread_fetch", HSDIR_SPREAD_FETCH),
        ];
        let netdir: Arc<NetDir> =
            crate::testnet::construct_custom_netdir_with_params(|_, _, _| {}, PARAMS, None)
                .unwrap()
                .unwrap_if_sufficient()
                .unwrap()
                .into();
        let hsid = dummy_hs_blind_id();
        const OP_RELAY_COUNT: &[(HsDirOp, usize)] = &[
            // We can't upload to (hsdir_n_replicas * hsdir_spread_store) = 12, relays because there
            // are only 10 relays with the HsDir flag in the consensus.
            #[cfg(feature = "hs-service")]
            (HsDirOp::Upload, 10),
            (HsDirOp::Download, 4),
        ];
        for (op, relay_count) in OP_RELAY_COUNT {
            let relays = netdir.hs_dirs(&hsid, *op, &mut testing_rng());
            assert_eq!(relays.len(), *relay_count);
            // There should be no duplicates (the filtering function passed to
            // HsDirRing::ring_items_at() ensures the relays that are already in use for
            // lower-numbered replicas aren't considered a second time for a higher-numbered
            // replica).
            let unique = relays
                .iter()
                .map(|relay| relay.ed_identity())
                .collect::<HashSet<_>>();
            assert_eq!(unique.len(), relays.len());
        }
        // TODO: come up with a test that checks that HsDirRing::ring_items_at() skips over the
        // expected relays.
        //
        // For example, let's say we have the following hsdir ring:
        //
        //         A  -  B
        //        /       \
        //       F         C
        //        \       /
        //         E  -  D
        //
        // Let's also assume that:
        //
        //   * hsdir_spread_store = 3
        //   * the ordering of the relays on the ring is [A, B, C, D, E, F]
        //
        // If we use relays [A, B, C] for replica 1, and hs_index(2) = E, then replica 2 _must_ get
        // relays [E, F, D]. We should have a test that checks this.
    }
    #[test]
    fn zero_weights() {
        // Here we check the behavior of IndexedRandom::choose_weighted
        // in the presence of items whose weight is 0.
        //
        // We think that the behavior is:
        //   - If all items have weight 0, choose_weighted returns an error.
        //   - If any items have non-zero weight, one of them will be returned.
        let items = vec![1, 2, 3];
        let mut rng = testing_rng();
        let a = items.choose_weighted(&mut rng, |_| 0);
        assert!(matches!(a, Err(WeightError::InsufficientNonZero)));
        let only_one = |n: &i32| if *n == 1 { 1 } else { 0 };
        for _ in 0..100 {
            let a = items.choose_weighted(&mut rng, only_one);
            assert_eq!(a.unwrap(), &1);
        }
    }
}