tor_netdir/
lib.rs

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