Skip to main content

tor_netdoc/doc/
netstatus.rs

1//! Parsing implementation for networkstatus documents.
2//!
3//! In Tor, a networkstatus documents describes a complete view of the
4//! relays in the network: how many there are, how to contact them,
5//! and so forth.
6//!
7//! A networkstatus document can either be a "votes" -- an authority's
8//! view of the network, used as input to the voting process -- or a
9//! "consensus" -- a combined view of the network based on multiple
10//! authorities' votes, and signed by multiple authorities.
11//!
12//! A consensus document can itself come in two different flavors: a
13//! plain (unflavoured) consensus has references to router descriptors, and
14//! a "microdesc"-flavored consensus ("md") has references to
15//! microdescriptors.
16//!
17//! To keep an up-to-date view of the network, clients download
18//! microdescriptor-flavored consensuses periodically, and then
19//! download whatever microdescriptors the consensus lists that the
20//! client doesn't already have.
21//!
22//! For full information about the network status format, see
23//! [dir-spec.txt](https://spec.torproject.org/dir-spec).
24//!
25//! # Limitations
26//!
27//! NOTE: The consensus format has changes time, using a
28//! "consensus-method" mechanism.  This module is does not yet handle all
29//! all historical consensus-methods.
30//!
31//! NOTE: This module _does_ parse some fields that are not in current
32//! use, like relay nicknames, and the "published" times on
33//! microdescriptors. We should probably decide whether we actually
34//! want to do this.
35//!
36//! TODO: This module doesn't implement vote parsing at all yet.
37//!
38//! TODO: This module doesn't implement plain consensuses.
39//!
40//! TODO: We need an object safe trait that combines the common operations found
41//! on netstatus documents, so we can store one in a `Box<dyn CommonNs>` or
42//! something similar; otherwise interfacing applications have a hard time to
43//! process netstatus documents in a flavor agnostic fashion.
44//!
45//! TODO: More testing is needed!
46//!
47//! TODO: There should be accessor functions for most of the fields here.
48//! As with the other tor-netdoc types, I'm deferring those till I know what
49//! they should be.
50
51mod dir_source;
52mod rs;
53
54pub mod md;
55pub mod plain;
56pub mod vote;
57
58#[cfg(feature = "build_docs")]
59mod build;
60
61pub use proto_statuses_parse2_encode::ProtoStatusesNetdocParseAccumulator;
62
63use crate::doc::authcert::EncodedAuthCert;
64
65use crate::doc::authcert::{self, AuthCert, AuthCertKeyIds, AuthCertUnverified};
66use crate::encode::{
67    EncodeOrd, ItemArgument, ItemEncoder, ItemValueEncodable, NetdocEncodable, NetdocEncoder,
68};
69use crate::parse::keyword::Keyword;
70use crate::parse::parser::{Section, SectionRules, SectionRulesBuilder};
71use crate::parse::tokenize::{Item, ItemResult, NetDocReader};
72use crate::parse2::{
73    self, ArgumentError, ArgumentStream, ErrorProblem, IsStructural, ItemArgumentParseable,
74    ItemStream, ItemValueParseable, KeywordRef, NetdocParseable, NetdocParseableUnverified,
75    SignatureHashInputs, SignatureItemParseable, StopAt, UnparsedItem, VerifyFailed,
76};
77use crate::types::relay_flags::{self, DocRelayFlags};
78use crate::types::{self, *};
79use crate::util::PeekableIterator;
80use crate::{Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Pos};
81use std::collections::{BTreeSet, HashMap, HashSet};
82use std::fmt::{self, Display};
83use std::slice;
84use std::str::FromStr;
85use std::sync::Arc;
86use std::time::{self, SystemTime};
87use std::{net, result};
88use tor_basic_utils::iter_join;
89use tor_error::{Bug, HasKind, bad_api_usage, internal};
90use tor_protover::Protocols;
91use void::ResultVoidExt as _;
92
93use derive_deftly::{Deftly, define_derive_deftly};
94use digest::Digest;
95use educe::Educe;
96use itertools::Itertools;
97use saturating_time::SaturatingTime as _;
98use std::sync::LazyLock;
99use tor_checkable::{ExternallySigned, TimeBound, timed::TimeRangeBound};
100use tor_llcrypto as ll;
101use tor_llcrypto::pk::rsa::RsaIdentity;
102
103use serde::{Deserialize, Deserializer};
104
105#[cfg(feature = "build_docs")]
106pub use build::MdConsensusBuilder;
107#[cfg(feature = "build_docs")]
108pub use build::PlainConsensusBuilder;
109#[cfg(feature = "build_docs")]
110ns_export_each_flavor! {
111    ty: RouterStatusBuilder;
112}
113
114ns_export_each_variety! {
115    ty: Footer, RouterStatus, Preamble;
116}
117
118#[deprecated]
119pub use PlainConsensus as NsConsensus;
120#[deprecated]
121pub use PlainRouterStatus as NsRouterStatus;
122#[deprecated]
123pub use UncheckedPlainConsensus as UncheckedNsConsensus;
124#[deprecated]
125pub use UnvalidatedPlainConsensus as UnvalidatedNsConsensus;
126
127#[deprecated]
128pub use InvalidRelayBandwidth as InvalidRelayWeights;
129#[deprecated]
130pub use RelayBandwidth as RelayWeight;
131#[deprecated]
132pub use RelayBandwidthItem as RelayWeightsItem;
133#[deprecated]
134pub use VoteRelayBandwidthItem as VoteRelayWeightsItem;
135
136pub use rs::{RouterStatusMdDigestsVote, RouterStatusMdDigestsVoteConstructor, SoftwareVersion};
137
138pub use dir_source::{
139    ConsensusAuthoritySection, ConsensusAuthoritySectionConstructor, DirSource,
140    DirSourceConstructor, SupersededAuthorityKey,
141};
142
143define_constant_string! {
144    /// `network-status-version` version value
145    ///
146    /// This is the fixed string `3`.
147    ///
148    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:network-status-version>
149    //
150    // IMO this is nicer than the formulation with an enum.
151    // In practice we are not going to support other versions with the same parsing approach;
152    // probably not even with the same code.
153    NetworkStatusVersion = "3";
154}
155
156define_constant_string! {
157    /// The `status` value in a `vote-status` line in a consensus
158    ///
159    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-status>
160    VoteStatusConsensus = "consensus";
161}
162
163define_constant_string! {
164    /// The `vote` value in a `vote-status` line in a vote
165    ///
166    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-status>
167    VoteStatusVote = "vote";
168}
169
170/// `publiscation` field in routerstatus entry intro item other than in votes
171///
172/// Two arguments which are both ignored.
173/// This used to be an ISO8601 timestamp in anomalous two-argument format.
174///
175/// Nowadays, according to the spec, it can be a dummy value.
176/// So it can be a unit type.
177///
178/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:r>,
179/// except in votes which use [`Iso8601TimeSp`] instead.
180///
181/// **Not the same as** the `published` item:
182/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
183#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
184#[allow(clippy::exhaustive_structs)]
185pub struct IgnoredPublicationTimeSp;
186
187/// The lifetime of a networkstatus document.
188///
189/// In a consensus, this type describes when the consensus may safely
190/// be used.  In a vote, this type describes the proposed lifetime for a
191/// consensus.
192///
193/// Aggregate of three netdoc preamble fields.
194#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
195#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
196#[derive_deftly(Lifetime)]
197#[allow(clippy::exhaustive_structs)]
198pub struct Lifetime {
199    /// `valid-after` --- Time at which the document becomes valid
200    ///
201    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
202    ///
203    /// (You might see a consensus a little while before this time,
204    /// since voting tries to finish up before the.)
205    #[deftly(constructor)]
206    #[deftly(netdoc(single_arg))]
207    pub valid_after: Iso8601TimeSp,
208    /// `fresh-until` --- Time after which there is expected to be a better version
209    /// of this consensus
210    ///
211    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
212    ///
213    /// You can use the consensus after this time, but there is (or is
214    /// supposed to be) a better one by this point.
215    #[deftly(constructor)]
216    #[deftly(netdoc(single_arg))]
217    pub fresh_until: Iso8601TimeSp,
218    /// `valid-until` --- Time after which this consensus is expired.
219    ///
220    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
221    ///
222    /// You should try to get a better consensus after this time,
223    /// though it's okay to keep using this one if no more recent one
224    /// can be found.
225    #[deftly(constructor)]
226    #[deftly(netdoc(single_arg))]
227    pub valid_until: Iso8601TimeSp,
228
229    #[doc(hidden)]
230    #[deftly(netdoc(skip))]
231    pub __non_exhaustive: (),
232}
233
234define_derive_deftly! {
235    /// Bespoke derive for `Lifetime`, for `new` and accessors
236    Lifetime:
237
238    ${defcond FIELD not(approx_equal($fname, __non_exhaustive))}
239
240    impl Lifetime {
241        /// Construct a new Lifetime.
242        pub fn new(
243            $( ${when FIELD} $fname: time::SystemTime, )
244        ) -> crate::Result<Self> {
245            // Make this now because otherwise literal `valid_after` here in the body
246            // has the wrong span - the compiler refuses to look at the argument.
247            // But we can refer to the field names.
248            let self_ = Lifetime {
249                $( ${when FIELD} $fname: $fname.into(), )
250                __non_exhaustive: (),
251            };
252            if self_.valid_after < self_.fresh_until && self_.fresh_until < self_.valid_until {
253                Ok(self_)
254            } else {
255                Err(EK::InvalidLifetime.err())
256            }
257        }
258      $(
259        ${when FIELD}
260
261        ${fattrs doc}
262        pub fn $fname(&self) -> time::SystemTime {
263            *self.$fname
264        }
265      )
266        /// Return true if this consensus is officially valid at the provided time.
267        pub fn valid_at(&self, when: time::SystemTime) -> bool {
268            *self.valid_after <= when && when <= *self.valid_until
269        }
270
271        /// Return the voting period implied by this lifetime.
272        ///
273        /// (The "voting period" is the amount of time in between when a consensus first
274        /// becomes valid, and when the next consensus is expected to become valid)
275        pub fn voting_period(&self) -> time::Duration {
276            let valid_after = self.valid_after();
277            let fresh_until = self.fresh_until();
278            fresh_until
279                .duration_since(valid_after)
280                .expect("Mis-formed lifetime")
281        }
282    }
283}
284use derive_deftly_template_Lifetime;
285
286/// A single consensus method
287///
288/// These are integers, but we don't do arithmetic on them.
289///
290/// As defined here:
291/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-methods>
292/// <https://spec.torproject.org/dir-spec/computing-consensus.html#flavor:microdesc>
293///
294/// As used in a `consensus-method` item:
295/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-method>
296#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] //
297#[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
298#[allow(clippy::exhaustive_structs)] // we're v unlikely to want to change this to u16 or u64
299pub struct ConsensusMethod(pub u32);
300impl NormalItemArgument for ConsensusMethod {}
301
302/// A set of consensus methods
303///
304/// Implements `ItemValueParseable` as required for `consensus-methods`,
305/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-methods>
306///
307/// There is also [`consensus_methods_comma_separated`] for `m` lines in votes.
308///
309/// This is a parsing helper, a thin wrapper around `BTreeSet`
310#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Deftly)] //
311#[derive(derive_more::Into, derive_more::From, derive_more::Deref)]
312#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
313#[allow(clippy::exhaustive_structs)]
314pub struct ConsensusMethods {
315    /// Consensus methods.
316    pub methods: BTreeSet<ConsensusMethod>,
317}
318
319/// Module for use with parse2's `with`, to parse one argument of comma-separated consensus methods
320///
321/// As found in an `m` item in a vote:
322/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:m>
323pub mod consensus_methods_comma_separated {
324    use super::*;
325    use parse2::ArgumentError as AE;
326    use std::result::Result;
327
328    /// Parse
329    pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
330        let mut methods = BTreeSet::new();
331        for ent in args.next().ok_or(AE::Missing)?.split(',') {
332            let ent = ent.parse().map_err(|_| AE::Invalid)?;
333            if !methods.insert(ent) {
334                return Err(AE::Invalid);
335            }
336        }
337        Ok(ConsensusMethods { methods })
338    }
339
340    /// Encode
341    pub fn write_arg_onto(self_: &ConsensusMethods, out: &mut ItemEncoder) -> Result<(), Bug> {
342        out.args_raw_string(&iter_join(",", &self_.methods));
343        Ok(())
344    }
345}
346
347/// Contents of a `voting-delay` item in the network status preamble
348///
349/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:voting-delay>
350#[derive(Debug, Clone, Eq, PartialEq, Hash, Copy, Deftly)]
351#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
352#[allow(clippy::exhaustive_structs)]
353pub struct VotingDelay {
354    /// VoteSeconds
355    #[deftly(constructor)]
356    pub vote_seconds: u32,
357
358    /// DistSeconds
359    #[deftly(constructor)]
360    pub dist_seconds: u32,
361
362    #[doc(hidden)]
363    #[deftly(netdoc(skip))]
364    pub __non_exhaustive: (),
365}
366
367/// Some map of values for network parameters, eg for overriding
368///
369/// The whole consensus's network parameters (from the preamble) are a [`NetParams`]
370/// which is usually refined into a `tor_netdir::NetParameters` for use.
371///
372/// This is a convenience alias for the generic [`ParamValues`],
373/// which is used for other netdoc elements too.
374///
375/// See [`ParamValues`] for a discussion of the relationship between these types.
376pub type NetParamValues = ParamValues<i32>;
377
378/// A set of named parameter values
379///
380/// These are used to describe current settings for the Tor network,
381/// current weighting parameters for path selection, and so on.  They're
382/// encoded with a space-separated K=V format.
383///
384/// ### Overview of types for representing (network) parameter
385///
386/// This is at the root of four related types:
387///
388///  * `tor_netdir::NetParameters`: refined consensus parameters, ready for use.
389///      - impossible to accidentally refer to undefined parameter names
390///      - spec's defaults are applied
391///      - values' ranges are checked
392///
393///  * [`NetParams`]: network parameter settings from `params` in a consensus (or vote),
394///    parsed, but without interpretation and without defaults applied.
395///    This is the type of the `params` field in a `NetworkStatus`.
396///      - caller must get field names right; no central keyword list
397///      - user is reminded to apply defaults, but must do so manually
398///      - values are all unchecked `i32`
399///
400///  * [`NetParamValues`]: a set of network parameter values, for example
401///    as found in configuration for overriding netparams.
402///    [`NetParams`] contains one of these.
403///      - no checking of field names or values
404///      - missing values simply return `None` from `get`,
405///        nothing to stop failure to apply a default when needed
406///        (which is appropriate for an override set).
407///
408///  * [`ParamValues<T>`]: any kind of key=values list as used in various network
409///    documents, generic over the value type `T`.
410///      - no checking of field names or values, no defaulting
411///      - arbitrary value type - some netdoc elements have `u32`, some `i32`, etc.
412///
413/// ### In netdocs
414///
415/// Syntax is that found in `params` in a network status:
416/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:params>,
417/// The same syntax is also used, and this type used for parsing, in various other places,
418/// for example routerstatus entry `w` items (bandwidths):
419/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:w>
420//
421// TODO DIRAUTH torspec#401 Replace `String` with a suitable newtype
422// Currently:
423//  - Our parser allows any keyword that makes it into a netdoc argument,
424//    but it splits on the *first* `=` so a `NetParams<i32>` cannot parse a keyword with a `=`.
425//  - We provide constructors that allow any `String`, even ones containing space, `=`,
426//    newline, etc.
427//  - Encoding throws `Bug` if the resulting document will be clearly garbage,
428//    forbidding `=`, whitespace, and controls.  If the supplied keywords are bizarre,
429//    it may generate surprising documents (eg, containing exciting Unicode).
430#[derive(Debug, Clone, Educe, Eq, PartialEq)]
431#[educe(Default)]
432pub struct ParamValues<T> {
433    /// Map from keys to values.
434    params: HashMap<String, T>,
435}
436
437impl<T> ParamValues<T> {
438    /// Create a new empty list of NetParams.
439    #[allow(unused)]
440    pub fn new() -> Self {
441        ParamValues::default()
442    }
443    /// Retrieve a given network parameter, if it is present.
444    ///
445    /// There is no safeguard against getting parameter names wrong.
446    pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
447        self.params.get(v.as_ref())
448    }
449    /// Return an iterator over all key value pairs in an arbitrary order.
450    pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
451        self.params.iter()
452    }
453    /// Set or replace the value of a network parameter.
454    ///
455    /// There is no safeguard against getting parameter names wrong.
456    /// Prefer to refine into a cooked type such as `tor_netdir::NetParameters` if possible.
457    pub fn set(&mut self, k: String, v: T) {
458        self.params.insert(k, v);
459    }
460    /// Clear a network parameter from this set.
461    ///
462    /// The actual eventual value used will then be the default, or un-overridden parameter.
463    ///
464    /// There is no safeguard against getting parameter names wrong.
465    pub fn clear(&mut self, k: &str) {
466        self.params.remove(k);
467    }
468}
469
470impl<K: Into<String>, T> FromIterator<(K, T)> for ParamValues<T> {
471    fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
472        ParamValues {
473            params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
474        }
475    }
476}
477
478impl<T> std::iter::Extend<(String, T)> for ParamValues<T> {
479    fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
480        self.params.extend(iter);
481    }
482}
483
484impl<'de, T> Deserialize<'de> for ParamValues<T>
485where
486    T: Deserialize<'de>,
487{
488    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
489    where
490        D: Deserializer<'de>,
491    {
492        let params = HashMap::deserialize(deserializer)?;
493        Ok(ParamValues { params })
494    }
495}
496
497/// The network parameters as in the `params` line
498///
499/// <https://spec.torproject.org/param-spec.html>
500///
501/// As found in `params` in a network status:
502/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:params>
503///
504/// This type contains a [`NetParamValues`] ie a [`ParamValues<i32>`].
505/// That is not directly exposed in a `NetworkStatus`,
506/// because users of entries from `params` are supposed to apply default values
507/// for missing entries.
508///
509/// See [`ParamValues`] for a discussion of the relationship between these types.
510#[derive(Debug, Clone, Educe, Eq, PartialEq, derive_more::From, derive_more::FromStr)]
511#[educe(Default)]
512pub struct NetParams {
513    /// Map from keys to values.
514    params: NetParamValues,
515}
516
517impl NetParams {
518    /// Access the parameter set, without applying default values
519    ///
520    /// The caller must supply default values as appropriate.
521    ///
522    /// Prefer to refine into a `tor_netdir::NetParameters` if possible.
523    pub fn without_defaults(&self) -> &NetParamValues {
524        &self.params
525    }
526
527    /// Unwrap into the contained parameter set, without applying default values
528    ///
529    /// The caller must supply default values as appropriate,
530    ///
531    /// Prefer to refine into a `tor_netdir::NetParameters` if possible.
532    pub fn into_without_defaults(self) -> NetParamValues {
533        self.params
534    }
535
536    /// Set or replace the value of a network parameter.
537    ///
538    /// There is no safeguard against getting parameter names wrong.
539    pub fn set(&mut self, k: String, v: i32) {
540        self.params.set(k, v);
541    }
542
543    /// Reset a network parameter back to the default.
544    ///
545    /// If this set is later correctly used as an actual netparams set,
546    /// the actual eventual value used will then be the default.
547    ///
548    /// There is no safeguard against getting parameter names wrong.
549    pub fn clear(&mut self, k: &str) {
550        self.params.clear(k);
551    }
552}
553
554impl<K: Into<String>> FromIterator<(K, i32)> for NetParams {
555    fn from_iter<I: IntoIterator<Item = (K, i32)>>(i: I) -> Self {
556        NetParams {
557            params: i.into_iter().collect(),
558        }
559    }
560}
561
562/// A list of subprotocol versions that implementors should/must provide.
563///
564/// This struct represents a pair of (optional) items:
565/// `recommended-FOO-protocols` and `required-FOO-protocols`.
566///
567/// Each consensus has two of these: one for relays, and one for clients.
568///
569/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:required-relay-protocols>
570#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
571#[derive_deftly(Constructor)]
572#[allow(clippy::exhaustive_structs)]
573pub struct ProtoStatus {
574    /// Set of protocols that are recommended; if we're missing a protocol
575    /// in this list we should warn the user.
576    ///
577    /// `recommended-client-protocols` or `recommended-relay-protocols`
578    pub recommended: Protocols,
579
580    /// Set of protocols that are required; if we're missing a protocol
581    /// in this list we should refuse to start.
582    ///
583    /// `required-client-protocols` or `required-relay-protocols`
584    pub required: Protocols,
585
586    #[doc(hidden)]
587    #[serde(skip)]
588    pub __non_exhaustive: (),
589}
590
591impl ProtoStatus {
592    /// Check whether the list of supported protocols
593    /// is sufficient to satisfy this list of recommendations and requirements.
594    ///
595    /// If any required protocol is missing, returns [`ProtocolSupportError::MissingRequired`].
596    ///
597    /// Otherwise, if no required protocol is missing, but some recommended protocol is missing,
598    /// returns [`ProtocolSupportError::MissingRecommended`].
599    ///
600    /// Otherwise, if no recommended or required protocol is missing, returns `Ok(())`.
601    pub fn check_protocols(
602        &self,
603        supported_protocols: &Protocols,
604    ) -> Result<(), ProtocolSupportError> {
605        // Required protocols take precedence, so we check them first.
606        let missing_required = self.required.difference(supported_protocols);
607        if !missing_required.is_empty() {
608            return Err(ProtocolSupportError::MissingRequired(missing_required));
609        }
610        let missing_recommended = self.recommended.difference(supported_protocols);
611        if !missing_recommended.is_empty() {
612            return Err(ProtocolSupportError::MissingRecommended(
613                missing_recommended,
614            ));
615        }
616
617        Ok(())
618    }
619}
620
621/// A subprotocol that is recommended or required in the consensus was not present.
622#[derive(Clone, Debug, thiserror::Error)]
623#[cfg_attr(test, derive(PartialEq))]
624#[non_exhaustive]
625pub enum ProtocolSupportError {
626    /// At least one required protocol was not in our list of supported protocols.
627    #[error("Required protocols are not implemented: {0}")]
628    MissingRequired(Protocols),
629
630    /// At least one recommended protocol was not in our list of supported protocols.
631    ///
632    /// Also implies that no _required_ protocols were missing.
633    #[error("Recommended protocols are not implemented: {0}")]
634    MissingRecommended(Protocols),
635}
636
637impl ProtocolSupportError {
638    /// Return true if the suggested behavior for this error is a shutdown.
639    pub fn should_shutdown(&self) -> bool {
640        matches!(self, Self::MissingRequired(_))
641    }
642}
643
644impl HasKind for ProtocolSupportError {
645    fn kind(&self) -> tor_error::ErrorKind {
646        tor_error::ErrorKind::SoftwareDeprecated
647    }
648}
649
650/// A set of recommended and required protocols when running
651/// in various scenarios.
652///
653/// Represents the collection of four items: `{recommended,required}-{client,relay}-protocols`.
654///
655/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:required-relay-protocols>
656#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
657#[derive_deftly(Constructor)]
658#[allow(clippy::exhaustive_structs)]
659pub struct ProtoStatuses {
660    /// Lists of recommended and required subprotocol versions for clients
661    pub client: ProtoStatus,
662
663    /// Lists of recommended and required subprotocol versions for relays
664    pub relay: ProtoStatus,
665
666    #[doc(hidden)]
667    #[serde(skip)]
668    pub __non_exhaustive: (),
669}
670
671impl ProtoStatuses {
672    /// Return the list of recommended and required protocols for running as a client.
673    pub fn client(&self) -> &ProtoStatus {
674        &self.client
675    }
676
677    /// Return the list of recommended and required protocols for running as a relay.
678    pub fn relay(&self) -> &ProtoStatus {
679        &self.relay
680    }
681}
682
683/// List of recommended Tor versions
684///
685/// As seen in `client-versions` and `server-versions` in the preamble.
686///
687/// Technically these are supposed to be as according to
688/// "`version-spec.txt`" but we actually allow anything that doesn't contain commas.
689///
690/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:client-versions>
691/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:server-versions>
692///
693/// An empty set means no information, not no recommended versions.
694//
695// TODO should we have a CommaSeparated<T> type for arguments like this?
696// But maybe we wouldn't be able to use it here anyway because of
697// the special handling of the missing value.
698//
699// This is yet a third version number representation in arti!  Here it's just String.
700// TODO unify RecommendedTorVersions, RelayPlatform, TorVersion
701// When this is fixed, remove the workaround in netstatus::test::roundtrip_netstatus
702#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] //
703#[derive(derive_more::Deref, derive_more::Into)]
704pub struct RecommendedTorVersions(BTreeSet<String>);
705
706/// Erroneous "recommended Tor versions" information
707#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
708#[non_exhaustive]
709pub enum InvalidRecommendedTorVersions {
710    /// Identical version appears twice
711    #[error("version {_0:?} contains whitespace")]
712    ContainsWhitespace(String),
713
714    /// Identical version appears twice
715    #[error("version {_0:?} is repeated")]
716    Repeated(String),
717}
718
719impl RecommendedTorVersions {
720    /// Return a `RecommendedTorVersions` that has no information
721    pub fn new_unknown() -> Self {
722        Self::default()
723    }
724
725    /// Does this `RecommendedTorVersions` have any information?
726    ///
727    /// Ie, is it not empty.
728    ///
729    /// The opposite of [`BTreeSet::is_empty()`] (which available via deref).
730    pub fn is_known(&self) -> bool {
731        !self.is_empty()
732    }
733
734    /// Construct a RecommendedTorVersions from a list of strings
735    #[allow(clippy::should_implement_trait)] // we can't due to coherence
736    pub fn from_iter<I, S>(i: I) -> Result<Self, InvalidRecommendedTorVersions>
737    where
738        I: IntoIterator<Item = S>,
739        S: AsRef<str>,
740    {
741        let mut set = BTreeSet::new();
742        for v in i {
743            let v = v.as_ref();
744            if v.is_empty() {
745                continue;
746            }
747            if v.chars().any(|c| c.is_whitespace()) {
748                return Err(InvalidRecommendedTorVersions::ContainsWhitespace(
749                    v.to_owned(),
750                ));
751            }
752            if !set.insert(v.to_owned()) {
753                return Err(InvalidRecommendedTorVersions::Repeated(v.to_owned()));
754            }
755        }
756        Ok(RecommendedTorVersions(set))
757    }
758}
759
760impl FromStr for RecommendedTorVersions {
761    type Err = InvalidRecommendedTorVersions;
762    fn from_str(s: &str) -> Result<Self, InvalidRecommendedTorVersions> {
763        Self::from_iter(s.split(','))
764    }
765}
766
767impl Display for RecommendedTorVersions {
768    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769        write!(f, "{}", iter_join(",", &self.0))
770    }
771}
772
773impl NormalItemArgument for RecommendedTorVersions {}
774
775impl ItemValueEncodable for RecommendedTorVersions {
776    fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
777        out.args_raw_string(self);
778        Ok(())
779    }
780}
781
782impl ItemValueParseable for RecommendedTorVersions {
783    fn from_unparsed(mut item: UnparsedItem) -> Result<Self, ErrorProblem> {
784        const FIELD: &str = "versions";
785        item.check_no_object()?;
786        let args = item.args_mut();
787        let arg = args.next().unwrap_or("");
788        arg.parse::<Self>()
789            .map_err(|_| args.handle_error(FIELD, ArgumentError::Invalid))
790    }
791}
792
793/// A recognized 'flavor' of consensus document.
794///
795/// The enum is exhaustive because the addition/removal of a consensus flavor
796/// should indeed be a breaking change, as it would inevitable require
797/// interfacing code to think about the handling of it.
798///
799/// <https://spec.torproject.org/dir-spec/computing-consensus.html#flavors>
800#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
801#[allow(clippy::exhaustive_enums)]
802pub enum ConsensusFlavor {
803    /// A "microdesc"-flavored consensus.  This is the one that
804    /// clients and relays use today.
805    Microdesc,
806    /// A "networkstatus"-flavored consensus.  It's used for
807    /// historical and network-health purposes.  Instead of listing
808    /// microdescriptor digests, it lists digests of full relay
809    /// descriptors.
810    Plain,
811}
812
813impl ConsensusFlavor {
814    /// Return the name of this consensus flavor.
815    pub fn name(&self) -> &'static str {
816        match self {
817            ConsensusFlavor::Plain => "ns", // spec bug, now baked in
818            ConsensusFlavor::Microdesc => "microdesc",
819        }
820    }
821    /// Try to find the flavor whose name is `name`.
822    ///
823    /// For historical reasons, an unnamed flavor indicates an "Plain"
824    /// document.
825    pub fn from_opt_name(name: Option<&str>) -> crate::Result<Self> {
826        match name {
827            Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
828            Some("ns") | None => Ok(ConsensusFlavor::Plain),
829            Some(other) => {
830                Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
831            }
832        }
833    }
834}
835
836define_derive_deftly! {
837    /// Bespoke derives applied to [`DirectorySignatureHashAlgo`]
838    ///
839    /// Generates:
840    ///
841    ///  * [`DirectorySignaturesHashesAccu`]
842    ///  * [`DirectorySignaturesHashesAccu::update_from`]
843    ///  * [`DirectorySignaturesHashesAccu::hash_slice_for_verification`]
844    DirectorySignaturesHashesAccu:
845
846    ${define FNAME ${paste ${snake_case $vname}} }
847
848    /// `directory-signature`a hash algorithm argument
849    #[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Deftly)]
850    #[derive_deftly(AsMutSelf)]
851    #[non_exhaustive]
852    pub struct DirectorySignaturesHashesAccu {
853      $(
854        ${vattrs doc}
855        pub $FNAME: Option<[u8; ${vmeta(hash_len) as expr}]>,
856      )
857    }
858
859    impl DirectorySignaturesHashesAccu {
860        /// Calculate the hash for a signature item and update this accumulator
861        fn update_from(
862            &mut self,
863            algo: &DigestAlgoInSignature,
864            body: &SignatureHashInputs,
865        ) {
866            // Update the hash in self.$UPDATE according to algorithm $AGLO
867            // (uses dynamic bindings of those parameters)
868            ${define HASH {
869                // Avoid recalculating if we don't need to
870                self.$UPDATE.get_or_insert_with(|| {
871                    let mut h = tor_llcrypto::d::$ALGO::new();
872                    h.update(body.body().body());
873                    h.update(body.signature_item_kw_spc);
874                    h.finalize().into()
875                });
876            }}
877
878            match &**algo {
879              $(
880                Some(KeywordOrString::Known($vtype)) => {
881                    ${define UPDATE $FNAME}
882                    ${define ALGO $vname}
883                    $HASH
884                }
885              )
886                None => {
887                    ${define UPDATE sha1}
888                    ${define ALGO Sha1}
889                    $HASH
890                }
891                Some(KeywordOrString::Unknown(..)) => {}
892            }
893        }
894
895        /// Return the hash value for a specific algorithm, as a slice
896        ///
897        /// `None` if the value wasn't computed.
898        /// That shouldn't happen.
899        fn hash_slice(
900            &self,
901            algo: &DigestAlgoInSignature,
902        ) -> Option<&[u8]> {
903            match &**algo {
904              $(
905                Some(KeywordOrString::Known($vtype)) => Some(self.$FNAME.as_ref()?),
906              )
907                None => Some(self.sha1.as_ref()?),
908                Some(KeywordOrString::Unknown(..)) => None,
909            }
910        }
911    }
912}
913
914/// `directory-signature` hash algorithm argument
915#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, Deftly)]
916#[derive_deftly(DirectorySignaturesHashesAccu)]
917#[non_exhaustive]
918#[strum(serialize_all = "snake_case")]
919pub enum DirectorySignatureHashAlgo {
920    /// SHA-1
921    #[deftly(hash_len = "20")]
922    Sha1,
923    /// SHA-256
924    #[deftly(hash_len = "32")]
925    Sha256,
926}
927
928/// `algorithm` field in a `directory-signature` item
929///
930/// This is extremely bizarre: it's an *optional item at the start of the arguments*!
931// TODO SPEC #350
932///
933/// So we parse it with some kind of nightmarish lookahead.
934///
935/// Additionally, to be able to convey the signatures accurately, without breaking them,
936/// we must remember whether the argument was present.
937///
938/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:directory-signature>
939#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
940#[allow(clippy::exhaustive_structs)]
941pub struct DigestAlgoInSignature(pub Option<KeywordOrString<DirectorySignatureHashAlgo>>);
942
943impl ItemArgumentParseable for DigestAlgoInSignature {
944    fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<Self, ArgumentError> {
945        let v = if args
946            .clone()
947            .next()
948            // Treat it as a fingerprint if it doesn't have any non-hex characters
949            // (including lowercase ones).  If we reuse this item for new algorithms
950            // they should have at least one letter g-z in their name.
951            .and_then(|s| s.chars().all(|c| c.is_ascii_hexdigit()).then_some(()))
952            .is_some()
953        {
954            // next argument looks enough like a fingerprint that we don't treat as an algo name
955            None
956        } else {
957            Some(KeywordOrString::from_args(args)?)
958        };
959        Ok(DigestAlgoInSignature(v))
960    }
961}
962impl ItemArgument for DigestAlgoInSignature {
963    fn write_arg_onto(&self, out: &mut ItemEncoder<'_>) -> Result<(), Bug> {
964        if let Some(y) = &self.0 {
965            y.write_arg_onto(out)?;
966        }
967        Ok(())
968    }
969}
970impl DigestAlgoInSignature {
971    /// Return the actual algorithm
972    ///
973    /// This handles the defaulting, where an absent argument means `sha1`.
974    pub fn algorithm(&self) -> &KeywordOrString<DirectorySignatureHashAlgo> {
975        self.as_ref()
976            .unwrap_or(&KeywordOrString::Known(DirectorySignatureHashAlgo::Sha1))
977    }
978}
979
980impl DigestAlgoInSignature {
981    /// Represent a known algorithm in the form used for the actual signature item
982    pub fn from_algo(algo: DirectorySignatureHashAlgo) -> Self {
983        DigestAlgoInSignature(match algo {
984            DirectorySignatureHashAlgo::Sha1 => None,
985            other => Some(KeywordOrString::Known(other)),
986        })
987    }
988}
989
990impl From<DirectorySignatureHashAlgo> for DigestAlgoInSignature {
991    fn from(algo: DirectorySignatureHashAlgo) -> Self {
992        Self::from_algo(algo)
993    }
994}
995
996impl NormalItemArgument for DirectorySignatureHashAlgo {}
997
998/// The signature of a single directory authority on a networkstatus document.
999///
1000/// Implements `ItemValueParseable` which parses without hashing anything;
1001/// this is mostly useful for use by the `SignatureItemParseable` implementation.
1002#[derive(Debug, Clone, Deftly)]
1003#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1004#[allow(clippy::exhaustive_structs)]
1005pub struct Signature {
1006    /// The name of the digest algorithm used to make the signature.
1007    ///
1008    /// Currently sha1 and sh256 are recognized.  Here we only support
1009    /// sha256.
1010    #[deftly(constructor)]
1011    pub digest_algo: DigestAlgoInSignature,
1012
1013    /// Fingerprints of the keys for the authority that made
1014    /// this signature.
1015    #[deftly(netdoc(with = authcert::keyids_directory_signature_args))]
1016    #[deftly(constructor)]
1017    pub key_ids: AuthCertKeyIds,
1018
1019    /// The signature itself.
1020    #[deftly(netdoc(object(label = "SIGNATURE"), with = types::raw_data_object))]
1021    #[deftly(constructor)]
1022    pub signature: Vec<u8>,
1023
1024    #[doc(hidden)]
1025    #[deftly(netdoc(skip))]
1026    pub __non_exhaustive: (),
1027}
1028
1029impl SignatureItemParseable for Signature {
1030    type HashAccu = DirectorySignaturesHashesAccu;
1031
1032    fn from_unparsed_and_body(
1033        item: UnparsedItem,
1034        body: &SignatureHashInputs<'_>,
1035        hash: &mut Self::HashAccu,
1036    ) -> Result<Self, ErrorProblem> {
1037        let signature = Signature::from_unparsed(item)?;
1038        hash.update_from(&signature.digest_algo, body);
1039        Ok(signature)
1040    }
1041}
1042
1043/// Error when trying to sign a network status
1044#[derive(Debug, thiserror::Error)]
1045#[non_exhaustive]
1046pub enum SigningError {
1047    /// Error making the actual RSA signature
1048    #[error("signing netdoc: rsa")]
1049    Rsa(#[from] ll::pk::rsa::Error),
1050    /// Internal error
1051    #[error("signing netdoc: internal error")]
1052    Internal(#[from] Bug),
1053}
1054
1055impl Signature {
1056    /// Make a network status document `Signature`, given the document text
1057    //
1058    // We provide this rather uncooked API, rather than (say) encode_sign,
1059    // because we need to excitingly manipulate consensus signatures,
1060    // adding them to existing documents, etc.
1061    //
1062    // The cooked encode_sign would have only one call site (dirauth voting),
1063    // so maybe we won't bother with it.
1064    pub fn sign_text(
1065        key: &ll::pk::rsa::KeyPair,
1066        text: &str,
1067        algo: DirectorySignatureHashAlgo,
1068        key_ids: AuthCertKeyIds,
1069    ) -> Result<Self, SigningError> {
1070        // We take AuthCertKeyIds since that seems better than taking a single loose
1071        // fingerprint for KP_auth_id_rsa and making it easy to pass KP_auth_sign_rsa
1072        // instead.  But this does mean we should probably check that KP_auth_sign_rsa
1073        // is right.
1074        if key_ids.sk_fingerprint != key.to_public_key().to_rsa_identity() {
1075            Err(bad_api_usage!(
1076                "incorrect KP_auth_sign_rsa passed in to netdoc signing"
1077            ))?;
1078        }
1079
1080        let digest_algo = DigestAlgoInSignature::from_algo(algo);
1081
1082        let mut accu = DirectorySignaturesHashesAccu::default();
1083        accu.update_from(
1084            &digest_algo,
1085            &SignatureHashInputs::new_for_signature(text, "directory-signature "),
1086        );
1087        let hash_slice = accu
1088            .hash_slice(&digest_algo)
1089            .ok_or_else(|| internal!("somehow failed to record hash of the in-use algo"))?;
1090
1091        let signature = key.sign(hash_slice)?;
1092
1093        Ok(SignatureConstructor {
1094            digest_algo,
1095            key_ids,
1096            signature,
1097        }
1098        .construct())
1099    }
1100}
1101
1102/// A collection of signatures that can be checked on a networkstatus document
1103///
1104/// This is derived from the signatures section of a netstatus,
1105/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:signature>,
1106/// but it is not isomorphic to it, and is not directly parseable.
1107#[derive(Debug, Clone)]
1108#[non_exhaustive]
1109pub struct SignatureGroup {
1110    /// The document hashes of the signed part of the document
1111    ///
1112    /// The pre-parse2 parser always sets `hashes.sha1` and `hashes.sha1_unnamed`
1113    /// to the same value, which is wrong. which is
1114    /// [bug #2530](https://gitlab.torproject.org/tpo/core/arti/-/work_items/2530)
1115    pub hashes: DirectorySignaturesHashesAccu,
1116    /// The signatures listed on the document.
1117    pub signatures: Vec<Signature>,
1118}
1119
1120/// Error which will prevent us from attempting to verify signatures on a consensus
1121///
1122/// This error occurs if we the consensus isn't signed by the right people,
1123/// or we are lacking authcerts.
1124///
1125/// Does not represent actual verification errors.
1126/// Those show up as `VerifyFailed`, typically [`ConsensusVerifyFailed::InvalidSignature`].
1127///
1128/// Can be converted to a `VerifyFailed`,
1129/// giving [`InsufficientTrustedSigners`](VerifyFailed::InsufficientTrustedSigners).
1130#[derive(Clone, Debug, thiserror::Error)]
1131#[allow(clippy::exhaustive_enums)]
1132pub enum ConsensusVerifiabilityError {
1133    /// Insufficient trusted signers
1134    #[error("consensus not signed by enough authorities")]
1135    InsufficientTrustedSigners,
1136
1137    /// Insufficient trusted signers because we are missing authcerts
1138    #[error("missing auth certs mean we could not verify enough consensus signatures (need at least {deficit} more, out of {} that are missing)", missing.len())]
1139    MissingAuthCerts {
1140        /// The number of additional useful authcerts that would be sufficient
1141        deficit: usize,
1142        /// All the authcerts that would be useful
1143        missing: HashSet<AuthCertKeyIds>,
1144    },
1145}
1146
1147/// Error encountered while verifying a consensus
1148///
1149/// Thrown by
1150/// [`plain::NetworkStatusUnverified::verify`]
1151/// and
1152/// [`md::NetworkStatusUnverified::verify`].
1153///
1154/// Not used for problems with the validity period:
1155/// that's handled by `tor-checkable` and shows up as [`tor_checkable::TimeValidityError`].
1156///
1157/// Can be converted to a `VerifyFailed` (which, in effect, summarises the error).
1158#[derive(Clone, Debug, thiserror::Error)]
1159#[non_exhaustive]
1160pub enum ConsensusVerifyFailed {
1161    /// Certificates or signatures insufficient
1162    #[error("certs/sigs insufficient")]
1163    CertificationInsufficient(#[from] ConsensusVerifiabilityError),
1164
1165    /// One or more signatures failed to verify
1166    #[error("invalid signature")]
1167    //
1168    // Not `#[from]` because we don't want to accidentally convert
1169    // ConsensusVerifiabilityError -> VerifyFailed -> ConsensusVerifyFailed
1170    // since that would give the wrong variant.
1171    InvalidSignature(#[source] VerifyFailed),
1172}
1173
1174/// Context for verifying one or more votes intended for the same consensus period
1175///
1176/// Construct this from a set of trusted identities with [`VoteVerifier::new`]
1177/// and then call [`vote::NetworkStatusUnverified::verify`] for each vote.
1178///
1179/// Tracks which authorities' votes have already been verified, and throws
1180/// [`VoteVerifyFailed::DuplicateAuthority`] if one is repeated.
1181///
1182/// To verify a vote in isolation, use `vote.verify(&mut VoteVerifier::new(..))`,
1183/// but note that then any detection of duplicates in a set of votes is up to you.
1184pub struct VoteVerifier {
1185    /// The trusted authorites (including ones we've already seen).
1186    trusted: Vec<RsaIdentity>,
1187
1188    /// The authorities whose votes we haven't yet verified, so we can still verify.
1189    remaining_good: HashSet<RsaIdentity>,
1190}
1191
1192impl VoteVerifier {
1193    /// Start verifying votes: construct a new `VoteVerifier` from a set of trusted authorities
1194    pub fn new(trusted: impl IntoIterator<Item = RsaIdentity>) -> Self {
1195        let trusted = trusted.into_iter().collect_vec();
1196        let remaining_good = trusted.iter().copied().collect();
1197        VoteVerifier {
1198            trusted,
1199            remaining_good,
1200        }
1201    }
1202}
1203
1204/// Error encountered while verifying a vote
1205///
1206/// Thrown by
1207/// [`vote::NetworkStatusUnverified::verify`].
1208///
1209/// Not used for problems with the validity period:
1210/// that's handled by `tor-checkable` and shows up as [`tor_checkable::TimeValidityError`].
1211///
1212/// Can be converted to a `VerifyFailed` (which, in effect, summarises the error).
1213#[derive(Clone, Debug, thiserror::Error)]
1214#[non_exhaustive]
1215pub enum VoteVerifyFailed {
1216    /// The document signature failed to verify
1217    #[error("invalid signature")]
1218    //
1219    // Not `#[from]` because we don't want to accidentally convert
1220    // VoteVerifyFailed::Something -> VerifyFailed -> VoteVerifyFailed
1221    // since that would give the wrong variant.
1222    InvalidSignature(#[source] VerifyFailed),
1223
1224    /// Authcert couldn't be parsed
1225    #[error("unparseable authcert")]
1226    AuthCertParseError(#[source] parse2::ParseError),
1227
1228    /// Authcert isn't valid for this vote's validity period
1229    #[error("authcert not valid for vote period")]
1230    AuthCertWrongValidity(#[source] tor_checkable::TimeValidityError),
1231
1232    /// Authcert is for a different authority
1233    #[error("wrong authcert")]
1234    AuthCertWrongAuthority,
1235
1236    /// Two or more votes from the same authority
1237    ///
1238    /// Often, this will be the result of a bug.
1239    #[error("duplicate authority {_0}")]
1240    DuplicateAuthority(RsaIdentity),
1241}
1242
1243/// A shared random value produced by the directory authorities.
1244#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] //
1245#[derive(derive_more::From, derive_more::Into, derive_more::AsRef)]
1246// (This doesn't need to use CtByteArray; we don't really need to compare these.)
1247pub struct SharedRandVal([u8; 32]);
1248
1249/// A shared-random value produced by the directory authorities,
1250/// along with meta-information about that value.
1251#[derive(Debug, Clone, Deftly, Eq, PartialEq, Hash)]
1252#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1253#[allow(clippy::exhaustive_structs)]
1254pub struct SharedRandStatus {
1255    /// How many authorities revealed shares that contributed to this value.
1256    #[deftly(constructor)]
1257    pub n_reveals: u8,
1258
1259    /// The current random value.
1260    ///
1261    /// The properties of the secure shared-random system guarantee
1262    /// that this value isn't predictable before it first becomes
1263    /// live, and that a hostile party could not have forced it to
1264    /// have any more than a small number of possible random values.
1265    #[deftly(constructor)]
1266    pub value: SharedRandVal,
1267
1268    /// The time when this SharedRandVal becomes (or became) the latest.
1269    ///
1270    /// (This is added per proposal 342, assuming that gets accepted.)
1271    pub timestamp: Option<Iso8601TimeNoSp>,
1272
1273    #[doc(hidden)]
1274    #[deftly(netdoc(skip))]
1275    pub __non_exhaustive: (),
1276}
1277
1278/// The two shared random values, `shared-rand-*-value`
1279///
1280/// As found in the consensus preamble
1281/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-current-value>
1282/// and a vote's authority section
1283/// <https://spec.torproject.org/dir-spec/consensus-formats.html#authority-item-shared-rand-value>
1284#[derive(Debug, Clone, Default, Deftly)]
1285#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1286#[allow(clippy::exhaustive_structs)]
1287pub struct SharedRandStatuses {
1288    /// Global shared-random value for the previous shared-random period.
1289    pub shared_rand_previous_value: Option<SharedRandStatus>,
1290
1291    /// Global shared-random value for the current shared-random period.
1292    pub shared_rand_current_value: Option<SharedRandStatus>,
1293
1294    #[doc(hidden)]
1295    #[deftly(netdoc(skip))]
1296    pub __non_exhaustive: (),
1297}
1298
1299/// Relay bandwidth information - `w` item in routerstatus in consensuses
1300///
1301/// This is a combination of two representations of (subsets of) the same information,
1302/// from an optional `w` in the document.
1303///
1304///  * [`effective`](RelayBandwidthItem::effective):
1305///
1306///    Always contains the effective bandwidth, as [`RelayBandwidth`].
1307///    This is what is used by clients.
1308///    It does not record whether a `w` line was actually present.
1309///
1310///  * [`params`](RelayBandwidthItem::params):
1311///
1312///    Can represent the presence and whole contents of the `w` line,
1313///    including all the known and unknown parameters.
1314///    This is within [`Unknown`], so it is only present with crate `feature = "retain-unknown"`,
1315///    and only some constructors/parsers record it.
1316///
1317/// # Parsing
1318///
1319/// Parsing is done with `NetdocParseableFields` rather than `ItemValueParseable`.
1320/// The `params` are [`Retained`](Unknown::Retained) if `retain_unknown_values` is
1321/// selected in [`parse2::ParseOptions`].
1322//
1323// We use NetdocParseableFields because the containing document, RouterStatus,
1324// contains `RelayBandwidthItem` rather than `Option<RelayBandwidthItem>`.
1325// The item parsing multiplicity machinery would see plain `RelayBandwidthItem` as a required item.
1326//
1327// This representation also means so that if retaining unknown information is compiled out
1328// (ie, in clients) each routerstatus entry stored in memory does not need to record
1329// whether `w` was present, merely what the implications were.
1330//
1331// We can't use ItemValueParseable with #[deftly(netdoc(default))]
1332// because `RelayBandwidthItem::default()` is a RelayBandwidthItem that definitively
1333// contains no pazrameters, ie with `Unknown::Retained`,
1334// and is therefore only conditionally available.
1335/// # Encoding
1336///
1337/// Encoding requires knowing whether a `w` line is to be included, and its contents,
1338/// so is implemented only with if `effective` is `Unknown::Retained`.
1339/// The encoding impl is only compiled in with `"retain-unknown"`,
1340/// and throws [`Bug`] if applied to a `RelayBandwidthItem` whose `params` are `Discarded`.
1341///
1342/// # Constructors
1343///
1344/// An "empty" `RelayBandwidthItem` can be constructed with [`RelayBandwidthItem::new_no_info`].
1345///
1346/// A `RelayBandwidthItem` containing only the effective `RelayBandwidth`
1347/// can be constructed using [`RelayBandwidthItem::from_effective`].
1348///
1349/// With `"retain-unknown"`:
1350/// a `RelayBandwidthItem` can be constructed from a [`ParamValues<u32>`] using `TryFrom`;
1351/// and, implements `Default`, which yields a `RelayBandwidthItem`
1352/// representing the (known) absence of a `w` line.
1353//
1354// Fields are private to maintain the invariant.
1355#[derive(Debug, Clone)]
1356pub struct RelayBandwidthItem {
1357    /// The effective relay bandwidth
1358    effective: RelayBandwidth,
1359
1360    /// The complete parameter set, if available and `w` was present.
1361    params: Unknown<Option<ParamValues<u32>>>,
1362}
1363
1364/// Relay bandwidth information - `w` item in routerstatus in votes
1365#[derive(Debug, Clone, Deftly)]
1366#[derive_deftly(NetdocEncodableFields, NetdocParseableFields)]
1367#[allow(clippy::exhaustive_structs)] // this is always just this single item
1368pub struct VoteRelayBandwidthItem {
1369    /// The parameters, uninterpreted.
1370    pub w: Option<ParamValues<u32>>,
1371}
1372
1373/// Recognized bandwidth fields on a single relay in a consensus
1374///
1375/// The part of a `w` item that we understand as a client.
1376#[non_exhaustive]
1377#[derive(Debug, Clone, Copy)]
1378pub enum RelayBandwidth {
1379    /// An unmeasured bandwidth for a relay.
1380    Unmeasured(u32),
1381    /// An measured bandwidth for a relay.
1382    Measured(u32),
1383}
1384
1385/// Error processing a `w` line's netparams into an effective relay bandwidth
1386#[derive(Debug, Clone, thiserror::Error)]
1387#[non_exhaustive]
1388pub enum InvalidRelayBandwidth {
1389    /// Invalid value for `Unmeasured`
1390    #[error("invalid value for Unmeasured")]
1391    InvalidUnmeasured,
1392}
1393
1394/// Authority entry in a consensus - deprecated compatibility type alias
1395#[deprecated = "renamed to ConsensusAuthorityEntry"]
1396pub type ConsensusVoterInfo = ConsensusAuthorityEntry;
1397
1398/// Authority entry in a plain consensus - type alias provided for consistency
1399pub type PlainAuthorityEntry = ConsensusAuthorityEntry;
1400/// Authority entry in an md consensus - type alias provided for consistency
1401pub type MdAuthorityEntry = ConsensusAuthorityEntry;
1402
1403/// An authority entry as found in a consensus
1404///
1405/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority-entry>
1406///
1407/// See also [`VoteAuthorityEntry`]
1408//
1409// We don't use the `each_variety` system for this because:
1410//  1. That avoids separating the two consensus authority entry types, which are identical
1411//  2. The only common fields are `dir-source` and `contact`, so there is little duplication
1412#[derive(Debug, Clone, Deftly)]
1413#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1414#[allow(clippy::exhaustive_structs)]
1415pub struct ConsensusAuthorityEntry {
1416    /// Contents of the `dir-source` line about an authority
1417    #[deftly(constructor)]
1418    pub dir_source: DirSource,
1419
1420    /// Human-readable contact information about the authority
1421    //
1422    // If more non-intro fields get added that are the same in votes and cosensuses,
1423    // consider using each_variety.rs or breaking those fields out into
1424    // `AuthorityEntryCommon` implementing `NetdocParseableFields`, or something.
1425    #[deftly(constructor)]
1426    pub contact: ContactInfo,
1427
1428    /// Digest of the vote that the authority cast to contribute to
1429    /// this consensus.
1430    ///
1431    /// This is not a fixed-length, fixed-algorithm field.
1432    /// Bizarrely, the algorithm is supposed to be inferred from the length!
1433    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-digest>
1434    #[deftly(netdoc(single_arg))]
1435    #[deftly(constructor)]
1436    pub vote_digest: B16U,
1437
1438    #[doc(hidden)]
1439    #[deftly(netdoc(skip))]
1440    pub __non_exhaustive: (),
1441}
1442
1443/// An authority entry as found in a vote
1444///
1445/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority-entry>
1446///
1447/// See also [`ConsensusAuthorityEntry`]
1448#[derive(Debug, Clone, Deftly)]
1449#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1450#[allow(clippy::exhaustive_structs)]
1451pub struct VoteAuthorityEntry {
1452    /// Contents of the `dir-source` line about an authority
1453    #[deftly(constructor)]
1454    pub dir_source: DirSource,
1455
1456    /// Human-readable contact information about the authority
1457    #[deftly(constructor)]
1458    pub contact: ContactInfo,
1459
1460    /// `legacy-dir-key` - superseded authority identity key
1461    ///
1462    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:legacy-dir-key>
1463    #[deftly(netdoc(single_arg))]
1464    pub legacy_dir_key: Option<Fingerprint>,
1465
1466    /// `shared-rand-participate` - Indicate shared random participation
1467    ///
1468    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-participate>
1469    pub shared_rand_participate: Option<SharedRandParticipate>,
1470
1471    /// `shared-rand-commit` - Shared random commitment
1472    ///
1473    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
1474    pub shared_rand_commit: Vec<SharedRandCommit>,
1475
1476    /// Global shared-random values
1477    #[deftly(netdoc(flatten))]
1478    pub shared_rand: SharedRandStatuses,
1479
1480    #[doc(hidden)]
1481    #[deftly(netdoc(skip))]
1482    pub __non_exhaustive: (),
1483}
1484
1485/// `shared-rand-participate` in a vote authority entry
1486///
1487/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-participate>
1488//
1489// We could have done `shared_rand_participate: Option<()>` in VoteAuthorityEntry,
1490// but then we might end up with variables of type `&Option<()>` etc.
1491// whose meaning has been detached from its type.
1492//
1493// TODO DIRAUTH rework this according to the API design conclusion from !3977 when there is one
1494#[derive(Debug, Clone, Deftly)]
1495#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1496#[allow(clippy::exhaustive_structs)]
1497pub struct SharedRandParticipate {
1498    #[doc(hidden)]
1499    #[deftly(netdoc(skip))]
1500    pub __non_exhaustive: (),
1501}
1502
1503/// `shared-rand-commit` in a vote authority entry
1504///
1505/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
1506#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1507// If new protocols use this item with a different version, we'll call it an API break.
1508#[allow(clippy::exhaustive_enums)]
1509pub enum SharedRandCommit {
1510    /// Version 1, the only one supported
1511    V1(SharedRandCommitV1),
1512
1513    /// Other versions.  Cannot be encoded.
1514    // It's not clear that future versions will use this version mechanism.  torspec#408.
1515    Unknown {},
1516}
1517
1518/// `shared-rand-commit` in a vote authority entry
1519///
1520/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
1521///
1522/// Version and hash are not explicitly represented.  See torspec#407.
1523///
1524/// `ItemValueEncodable` and `ItemValueParseable` impls do not include the fixed arguments;
1525/// in a netdoc, this type should be used within `SharedRandCommit::V1`.
1526#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1527#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1528#[allow(clippy::exhaustive_structs)]
1529pub struct SharedRandCommitV1 {
1530    /// Authority id key, recapitulated.
1531    // TODO this field shouldn't here at all torspec#407
1532    #[deftly(constructor)]
1533    h_kp_auth_id_rsa: Fingerprint,
1534
1535    /// Commitment
1536    ///
1537    /// `TIMESTAMP || SHA3_256(REVEAL)`, as per
1538    /// <https://spec.torproject.org/srv-spec/specification.html#COMMITREVEAL>
1539    //
1540    // TOOD we would like to replace this with a type that separates out the pieces!
1541    // But that would need a FixedB64 generic over some tor-bytes trait, or something.
1542    #[deftly(constructor)]
1543    commit: FixedB64<40>,
1544
1545    /// Reveal
1546    ///
1547    /// `TIMESTAMP || random number`, as per
1548    /// <https://spec.torproject.org/srv-spec/specification.html#COMMITREVEAL>
1549    reveal: Option<FixedB64<40>>,
1550
1551    #[doc(hidden)]
1552    #[deftly(netdoc(skip))]
1553    pub __non_exhaustive: (),
1554}
1555
1556impl SharedRandCommitV1 {
1557    /// The fixed arguments that precede the actual value in `shared-rand-commit 1 ...`
1558    const FIXED_ARGUMENTS: &[&str] = &["1", "sha3-256"];
1559}
1560impl ItemValueEncodable for SharedRandCommit {
1561    fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
1562        match self {
1563            SharedRandCommit::V1(values) => {
1564                for fixed in SharedRandCommitV1::FIXED_ARGUMENTS {
1565                    out.args_raw_string(fixed);
1566                }
1567                values.write_item_value_onto(out)
1568            }
1569            SharedRandCommit::Unknown {} => Err(internal!("encoding SharedRandCommit::Unknown")),
1570        }
1571    }
1572}
1573impl ItemValueParseable for SharedRandCommit {
1574    fn from_unparsed(mut item: UnparsedItem<'_>) -> Result<Self, ErrorProblem> {
1575        let mut fixed = SharedRandCommitV1::FIXED_ARGUMENTS.iter().copied();
1576        let args = item.args_mut();
1577        let version = args
1578            .next()
1579            .ok_or_else(|| args.handle_error("version", ArgumentError::Missing))?;
1580        if version != fixed.next().expect("nonempty") {
1581            return Ok(SharedRandCommit::Unknown {});
1582        }
1583        for exp in fixed {
1584            let got = args
1585                .next()
1586                .ok_or_else(|| args.handle_error(exp, ArgumentError::Missing))?;
1587            if got != exp {
1588                Err(args.handle_error(exp, ArgumentError::Invalid))?;
1589            }
1590        }
1591        let values = SharedRandCommitV1::from_unparsed(item)?;
1592        Ok(SharedRandCommit::V1(values))
1593    }
1594}
1595
1596// For `ConsensusAuthoritySection`, see `dir_source.rs`.
1597
1598define_derive_deftly! {
1599    /// Ad-hoc derive, `impl NetdocParseable for VoteAuthoritySection`
1600    ///
1601    /// We can't derive from `VoteAuthoritySection` with the normal macros, because
1602    /// it's not a document, with its own intro item.  It's just a collection of sub-documents.
1603    /// The netdoc derive macros don't have support for that - and it would be a fairly
1604    /// confusing thing to support because you'd end up with nested multiplicities and a whole
1605    /// variety of "intro item keywords" that were keywords for arbitrary sub-documents.
1606    ///
1607    /// Instead, we do that ad-hoc here.  It's less confusing because we don't need to
1608    /// worry about multiplicity, and because we know what only the outer document is
1609    /// that will contain this.
1610    VoteAuthoritySection:
1611
1612    ${defcond F_NORMAL not(fmeta(netdoc(skip)))}
1613
1614    impl NetdocParseable for VoteAuthoritySection {
1615        fn doctype_for_error() -> &'static str {
1616            "vote.authority.section"
1617        }
1618        fn is_intro_item_keyword(kw: KeywordRef<'_>) -> bool {
1619            VoteAuthorityEntry::is_intro_item_keyword(kw)
1620        }
1621        fn is_structural_keyword(kw: KeywordRef<'_>) -> Option<IsStructural> {
1622          $(
1623            ${when F_NORMAL}
1624            if let y @ Some(_) = $ftype::is_structural_keyword(kw) {
1625                return y;
1626            }
1627          )
1628            None
1629        }
1630        fn from_items<'s>(
1631            input: &mut ItemStream<'s>,
1632            stop_outer: stop_at!(),
1633        ) -> Result<Self, ErrorProblem> {
1634            let stop_inner = stop_outer
1635              $(
1636                ${when F_NORMAL}
1637                | StopAt($ftype::is_intro_item_keyword)
1638              )
1639            ;
1640            Ok(VoteAuthoritySection { $(
1641                ${when F_NORMAL}
1642                $fname: NetdocParseable::from_items(input, stop_inner)?,
1643            )
1644                __non_exhaustive: (),
1645            })
1646        }
1647    }
1648
1649    impl NetdocEncodable for VoteAuthoritySection {
1650        fn encode_unsigned(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
1651          $(
1652            ${when F_NORMAL}
1653            self.$fname.encode_unsigned(out)?;
1654          )
1655          Ok(())
1656        }
1657    }
1658}
1659
1660/// An authority section in a vote
1661///
1662/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority>
1663//
1664// We have split this out to help encapsulate vote/consensus-specific
1665// information in a forthcoming overall network status document type.
1666#[derive(Deftly, Clone, Debug)]
1667#[derive_deftly(VoteAuthoritySection, Constructor)]
1668#[allow(clippy::exhaustive_structs)]
1669pub struct VoteAuthoritySection {
1670    /// Authority entry
1671    #[deftly(constructor)]
1672    pub authority: VoteAuthorityEntry,
1673
1674    /// Authority key certificate
1675    #[deftly(constructor)]
1676    pub cert: EmbeddedCert<AuthCert, EncodedAuthCert>,
1677
1678    #[doc(hidden)]
1679    #[deftly(netdoc(skip))]
1680    pub __non_exhaustive: (),
1681}
1682
1683/// Fields in the footer of a consensus
1684///
1685/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:footer>
1686///
1687/// Not the whole footer, because it lacks the `directory-footer` item.
1688#[derive(Debug, Clone, Deftly)]
1689#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1690#[allow(clippy::exhaustive_structs)]
1691pub struct ConsensusFooterFields {
1692    /// `bandwidth-weights`
1693    ///
1694    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:bandwidth-weights>
1695    #[deftly(netdoc(default))]
1696    pub bandwidth_weights: ParamValues<i32>,
1697
1698    #[doc(hidden)]
1699    #[deftly(netdoc(skip))]
1700    pub __non_exhaustive: (),
1701}
1702
1703/// A consensus document that lists relays along with their
1704/// microdescriptor documents.
1705pub type MdConsensus = md::Consensus;
1706
1707/// An MdConsensus that has been parsed and checked for timeliness,
1708/// but not for signatures.
1709pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
1710
1711/// An MdConsensus that has been parsed but not checked for signatures
1712/// and timeliness.
1713pub type UncheckedMdConsensus = md::UncheckedConsensus;
1714
1715/// A consensus document that lists relays along with their
1716/// router descriptor documents.
1717pub type PlainConsensus = plain::Consensus;
1718
1719/// An PlainConsensus that has been parsed and checked for timeliness,
1720/// but not for signatures.
1721pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
1722
1723/// An PlainConsensus that has been parsed but not checked for signatures
1724/// and timeliness.
1725pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
1726
1727decl_keyword! {
1728    /// Keywords that can be used in votes and consensuses.
1729    // TODO: This is public because otherwise we can't use it in the
1730    // ParseRouterStatus crate.  But I'd rather find a way to make it
1731    // private.
1732    #[non_exhaustive]
1733    #[allow(missing_docs)]
1734    pub NetstatusKwd {
1735        // Header
1736        "network-status-version" => NETWORK_STATUS_VERSION,
1737        "vote-status" => VOTE_STATUS,
1738        "consensus-methods" => CONSENSUS_METHODS,
1739        "consensus-method" => CONSENSUS_METHOD,
1740        "published" => PUBLISHED,
1741        "valid-after" => VALID_AFTER,
1742        "fresh-until" => FRESH_UNTIL,
1743        "valid-until" => VALID_UNTIL,
1744        "voting-delay" => VOTING_DELAY,
1745        "client-versions" => CLIENT_VERSIONS,
1746        "server-versions" => SERVER_VERSIONS,
1747        "known-flags" => KNOWN_FLAGS,
1748        "flag-thresholds" => FLAG_THRESHOLDS,
1749        "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
1750        "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
1751        "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
1752        "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
1753        "params" => PARAMS,
1754        "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
1755        "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
1756        // "package" is now ignored.
1757
1758        // header in consensus, voter section in vote?
1759        "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
1760        "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
1761
1762        // Voter section (both)
1763        "dir-source" => DIR_SOURCE,
1764        "contact" => CONTACT,
1765
1766        // voter section (vote, but not consensus)
1767        "legacy-dir-key" => LEGACY_DIR_KEY,
1768        "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
1769        "shared-rand-commit" => SHARED_RAND_COMMIT,
1770
1771        // voter section (consensus, but not vote)
1772        "vote-digest" => VOTE_DIGEST,
1773
1774        // voter cert beginning (but only the beginning)
1775        "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
1776
1777        // routerstatus
1778        "r" => RS_R,
1779        "a" => RS_A,
1780        "s" => RS_S,
1781        "v" => RS_V,
1782        "pr" => RS_PR,
1783        "w" => RS_W,
1784        "p" => RS_P,
1785        "m" => RS_M,
1786        "id" => RS_ID,
1787
1788        // footer
1789        "directory-footer" => DIRECTORY_FOOTER,
1790        "bandwidth-weights" => BANDWIDTH_WEIGHTS,
1791        "directory-signature" => DIRECTORY_SIGNATURE,
1792    }
1793}
1794
1795/// Shared parts of rules for all kinds of netstatus headers
1796static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
1797    use NetstatusKwd::*;
1798    let mut rules = SectionRules::builder();
1799    rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
1800    rules.add(VOTE_STATUS.rule().required().args(1..));
1801    rules.add(VALID_AFTER.rule().required());
1802    rules.add(FRESH_UNTIL.rule().required());
1803    rules.add(VALID_UNTIL.rule().required());
1804    rules.add(VOTING_DELAY.rule().args(2..));
1805    rules.add(CLIENT_VERSIONS.rule());
1806    rules.add(SERVER_VERSIONS.rule());
1807    rules.add(KNOWN_FLAGS.rule().required());
1808    rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
1809    rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
1810    rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
1811    rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
1812    rules.add(PARAMS.rule());
1813    rules
1814});
1815/// Rules for parsing the header of a consensus.
1816static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1817    use NetstatusKwd::*;
1818    let mut rules = NS_HEADER_RULES_COMMON_.clone();
1819    rules.add(CONSENSUS_METHOD.rule().args(1..=1));
1820    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1821    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1822    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1823    rules.build()
1824});
1825/*
1826/// Rules for parsing the header of a vote.
1827static NS_HEADER_RULES_VOTE: SectionRules<NetstatusKwd> = {
1828    use NetstatusKwd::*;
1829    let mut rules = NS_HEADER_RULES_COMMON_.clone();
1830    rules.add(CONSENSUS_METHODS.rule().args(1..));
1831    rules.add(FLAG_THRESHOLDS.rule());
1832    rules.add(BANDWIDTH_FILE_HEADERS.rule());
1833    rules.add(BANDWIDTH_FILE_DIGEST.rule().args(1..));
1834    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1835    rules
1836};
1837/// Rules for parsing a single voter's information in a vote.
1838static NS_VOTERINFO_RULES_VOTE: SectionRules<NetstatusKwd> = {
1839    use NetstatusKwd::*;
1840    let mut rules = SectionRules::new();
1841    rules.add(DIR_SOURCE.rule().required().args(6..));
1842    rules.add(CONTACT.rule().required());
1843    rules.add(LEGACY_DIR_KEY.rule().args(1..));
1844    rules.add(SHARED_RAND_PARTICIPATE.rule().no_args());
1845    rules.add(SHARED_RAND_COMMIT.rule().may_repeat().args(4..));
1846    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1847    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1848    // then comes an entire cert: When we implement vote parsing,
1849    // we should use the authcert code for handling that.
1850    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1851    rules
1852};
1853 */
1854/// Rules for parsing a single voter's information in a consensus
1855static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1856    use NetstatusKwd::*;
1857    let mut rules = SectionRules::builder();
1858    rules.add(DIR_SOURCE.rule().required().args(6..));
1859    rules.add(CONTACT.rule().required());
1860    rules.add(VOTE_DIGEST.rule().required());
1861    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1862    rules.build()
1863});
1864/// Shared rules for parsing a single routerstatus
1865static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
1866    LazyLock::new(|| {
1867        use NetstatusKwd::*;
1868        let mut rules = SectionRules::builder();
1869        rules.add(RS_A.rule().may_repeat().args(1..));
1870        rules.add(RS_S.rule().required());
1871        rules.add(RS_V.rule());
1872        rules.add(RS_PR.rule().required());
1873        rules.add(RS_W.rule());
1874        rules.add(RS_P.rule().args(2..));
1875        rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1876        rules
1877    });
1878
1879/// Rules for parsing a single routerstatus in an NS consensus
1880static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1881    use NetstatusKwd::*;
1882    let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1883    rules.add(RS_R.rule().required().args(8..));
1884    rules.build()
1885});
1886
1887/*
1888/// Rules for parsing a single routerstatus in a vote
1889static NS_ROUTERSTATUS_RULES_VOTE: SectionRules<NetstatusKwd> = {
1890    use NetstatusKwd::*;
1891        let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1892        rules.add(RS_R.rule().required().args(8..));
1893        rules.add(RS_M.rule().may_repeat().args(2..));
1894        rules.add(RS_ID.rule().may_repeat().args(2..)); // may-repeat?
1895        rules
1896    };
1897*/
1898/// Rules for parsing a single routerstatus in a microdesc consensus
1899static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1900    use NetstatusKwd::*;
1901    let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1902    rules.add(RS_R.rule().required().args(6..));
1903    rules.add(RS_M.rule().required().args(1..));
1904    rules.build()
1905});
1906/// Rules for parsing consensus fields from a footer.
1907static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1908    use NetstatusKwd::*;
1909    let mut rules = SectionRules::builder();
1910    rules.add(DIRECTORY_FOOTER.rule().required().no_args());
1911    // consensus only
1912    rules.add(BANDWIDTH_WEIGHTS.rule());
1913    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1914    rules.build()
1915});
1916
1917impl ProtoStatus {
1918    /// Construct a ProtoStatus from two chosen keywords in a section.
1919    fn from_section(
1920        sec: &Section<'_, NetstatusKwd>,
1921        recommend_token: NetstatusKwd,
1922        required_token: NetstatusKwd,
1923    ) -> crate::Result<ProtoStatus> {
1924        /// Helper: extract a Protocols entry from an item's arguments.
1925        fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> crate::Result<Protocols> {
1926            if let Some(item) = t {
1927                item.args_as_str()
1928                    .parse::<Protocols>()
1929                    .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
1930            } else {
1931                Ok(Protocols::new())
1932            }
1933        }
1934
1935        let recommended = parse(sec.get(recommend_token))?;
1936        let required = parse(sec.get(required_token))?;
1937        Ok(ProtoStatus {
1938            recommended,
1939            required,
1940            __non_exhaustive: (),
1941        })
1942    }
1943
1944    /// Return the protocols that are listed as "required" in this `ProtoStatus`.
1945    ///
1946    /// Implementations may assume that relays on the network implement all the
1947    /// protocols in the relays' required-protocols list.  Implementations should
1948    /// refuse to start if they do not implement all the protocols on their own
1949    /// (client or relay) required-protocols list.
1950    pub fn required_protocols(&self) -> &Protocols {
1951        &self.required
1952    }
1953
1954    /// Return the protocols that are listed as "recommended" in this `ProtoStatus`.
1955    ///
1956    /// Implementations should warn if they do not implement all the protocols
1957    /// on their own (client or relay) recommended-protocols list.
1958    pub fn recommended_protocols(&self) -> &Protocols {
1959        &self.recommended
1960    }
1961}
1962
1963impl<T> std::str::FromStr for ParamValues<T>
1964where
1965    T: std::str::FromStr,
1966    T::Err: std::error::Error,
1967{
1968    type Err = Error;
1969    fn from_str(s: &str) -> crate::Result<Self> {
1970        /// Helper: parse a single K=V pair.
1971        fn parse_pair<U>(p: &str) -> crate::Result<(String, U)>
1972        where
1973            U: std::str::FromStr,
1974            U::Err: std::error::Error,
1975        {
1976            let parts: Vec<_> = p.splitn(2, '=').collect();
1977            if parts.len() != 2 {
1978                return Err(EK::BadArgument
1979                    .at_pos(Pos::at(p))
1980                    .with_msg("Missing = in key=value list"));
1981            }
1982            let num = parts[1].parse::<U>().map_err(|e| {
1983                EK::BadArgument
1984                    .at_pos(Pos::at(parts[1]))
1985                    .with_msg(e.to_string())
1986            })?;
1987            Ok((parts[0].to_string(), num))
1988        }
1989
1990        let params = s
1991            .split(' ')
1992            .filter(|p| !p.is_empty())
1993            .map(parse_pair)
1994            .try_collect()?;
1995        Ok(ParamValues { params })
1996    }
1997}
1998
1999impl FromStr for SharedRandVal {
2000    type Err = Error;
2001    fn from_str(s: &str) -> crate::Result<Self> {
2002        let val: B64 = s.parse()?;
2003        let val = SharedRandVal(val.into_array()?);
2004        Ok(val)
2005    }
2006}
2007impl Display for SharedRandVal {
2008    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2009        Display::fmt(&B64::from(Vec::from(self.0)), f)
2010    }
2011}
2012impl NormalItemArgument for SharedRandVal {}
2013
2014impl SharedRandStatus {
2015    /// Parse a current or previous shared rand value from a given
2016    /// SharedRandPreviousValue or SharedRandCurrentValue.
2017    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
2018        match item.kwd() {
2019            NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
2020            _ => {
2021                return Err(Error::from(internal!(
2022                    "wrong keyword {:?} on shared-random value",
2023                    item.kwd()
2024                ))
2025                .at_pos(item.pos()));
2026            }
2027        }
2028        let n_reveals: u8 = item.parse_arg(0)?;
2029        let value: SharedRandVal = item.parse_arg(1)?;
2030        // Added in proposal 342
2031        let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
2032        Ok(SharedRandStatus {
2033            n_reveals,
2034            value,
2035            timestamp,
2036            __non_exhaustive: (),
2037        })
2038    }
2039
2040    /// Return the actual shared random value.
2041    pub fn value(&self) -> &SharedRandVal {
2042        &self.value
2043    }
2044
2045    /// Return the timestamp (if any) associated with this `SharedRandValue`.
2046    pub fn timestamp(&self) -> Option<std::time::SystemTime> {
2047        self.timestamp.map(|t| t.0)
2048    }
2049}
2050
2051impl DirSource {
2052    /// Parse a "dir-source" item
2053    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
2054        if item.kwd() != NetstatusKwd::DIR_SOURCE {
2055            return Err(
2056                Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
2057                    .at_pos(item.pos()),
2058            );
2059        }
2060        let nickname = item
2061            .required_arg(0)?
2062            .parse()
2063            .map_err(|e: InvalidNickname| {
2064                EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
2065            })?;
2066        let identity = item.parse_arg(1)?;
2067        let hostname = item
2068            .required_arg(2)?
2069            .parse()
2070            .map_err(|e: InvalidInternetHost| {
2071                EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
2072            })?;
2073        let ip = item.parse_arg(3)?;
2074        let dir_port = item.parse_arg(4)?;
2075        let or_port = item.parse_arg(5)?;
2076
2077        Ok(DirSource {
2078            nickname,
2079            identity,
2080            hostname,
2081            ip,
2082            dir_port,
2083            or_port,
2084            __non_exhaustive: (),
2085        })
2086    }
2087}
2088
2089impl ConsensusAuthorityEntry {
2090    /// Parse a single ConsensusAuthorityEntry from a voter info section.
2091    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusAuthorityEntry> {
2092        use NetstatusKwd::*;
2093        // this unwrap should be safe because if there is not at least one
2094        // token in the section, the section is unparsable.
2095        #[allow(clippy::unwrap_used)]
2096        let first = sec.first_item().unwrap();
2097        if first.kwd() != DIR_SOURCE {
2098            return Err(Error::from(internal!(
2099                "Wrong keyword {:?} at start of voter info",
2100                first.kwd()
2101            ))
2102            .at_pos(first.pos()));
2103        }
2104        let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
2105
2106        let contact = sec.required(CONTACT)?;
2107        // Ideally we would parse_args_as_str but that requires us to
2108        // impl From<InvalidContactInfo> for crate::Error which is wrong
2109        // because many it's a footgun which lets you just write ? here
2110        // resulting in lack of position information.
2111        // (This is a general problem with the error handling in crate::parse.)
2112        let contact = contact
2113            .args_as_str()
2114            .parse()
2115            .map_err(|err: InvalidContactInfo| {
2116                EK::BadArgument
2117                    .with_msg(err.to_string())
2118                    .at_pos(contact.pos())
2119            })?;
2120
2121        let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16U>(0)?;
2122
2123        Ok(ConsensusAuthorityEntry {
2124            dir_source,
2125            contact,
2126            vote_digest,
2127            __non_exhaustive: (),
2128        })
2129    }
2130}
2131
2132impl RelayBandwidthItem {
2133    /// Return a new `RelayBandwidthItem` containing no information
2134    ///
2135    /// As if parsed from a document with no `w` line, discarding unknown information.
2136    pub fn new_no_info() -> Self {
2137        RelayBandwidthItem {
2138            effective: RelayBandwidth::default(),
2139            params: Unknown::new_discard(),
2140        }
2141    }
2142
2143    /// Return a new `RelayBandwidthItem` containing only the effective bandwidth
2144    pub fn from_effective(effective: RelayBandwidth) -> Self {
2145        RelayBandwidthItem {
2146            effective,
2147            params: Unknown::new_discard(),
2148        }
2149    }
2150
2151    /// Get the effective relay bandwidth (bandwidth estimate) for path selection.
2152    ///
2153    /// Invariant: consistent with from [`params`](RelayBandwidthItem::params),
2154    /// if `parsed` isn't [`Discarded`](Unknown::Discarded).
2155    //
2156    // We open-code this rather than deriving it so we can provide better docs.
2157    pub fn effective(&self) -> RelayBandwidth {
2158        self.effective
2159    }
2160
2161    /// Get the complete parameter set, if this information is available.
2162    ///
2163    /// After parsing, this is the parsed but not interpreted `w` item,
2164    /// or `None` if the document contained no `w` item.
2165    //
2166    // We open-code this rather than deriving it because we want to return
2167    // `Unknown<&...>` rather than `&Unknown<..>`, which the user would just have to .as_ref().
2168    pub fn params(&self) -> Unknown<&Option<ParamValues<u32>>> {
2169        self.params.as_ref()
2170    }
2171
2172    /// Parse a routerbandwidth from a "w" line.
2173    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<RelayBandwidthItem> {
2174        if item.kwd() != NetstatusKwd::RS_W {
2175            return Err(
2176                Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
2177                    .at_pos(item.pos()),
2178            );
2179        }
2180
2181        let params = item.args_as_str().parse()?;
2182        let effective =
2183            RelayBandwidth::from_param_values(&params).map_err(|e| e.at_pos(item.pos()))?;
2184
2185        Ok(RelayBandwidthItem {
2186            effective,
2187            params: Unknown::new_discard(),
2188        })
2189    }
2190
2191    /// The keyword for parsing and encoding
2192    const KEYWORD: &str = "w";
2193}
2194
2195#[cfg(feature = "retain-unknown")]
2196impl Default for RelayBandwidthItem {
2197    fn default() -> Self {
2198        RelayBandwidthItem {
2199            effective: RelayBandwidth::default(),
2200            params: Unknown::Retained(None),
2201        }
2202    }
2203}
2204
2205impl RelayBandwidth {
2206    /// Return the value, whether measured or not
2207    pub fn value(&self) -> u32 {
2208        match *self {
2209            RelayBandwidth::Measured(v) => v,
2210            RelayBandwidth::Unmeasured(v) => v,
2211        }
2212    }
2213
2214    /// Return true if this bandwidth is the result of a successful measurement
2215    pub fn is_measured(&self) -> bool {
2216        matches!(self, RelayBandwidth::Measured(_))
2217    }
2218
2219    /// Return true if this bandwidth is nonzero
2220    pub fn is_nonzero(&self) -> bool {
2221        self.value() != 0
2222    }
2223
2224    /// Parse a routerbandwidth from partially-parsed `w` line in the form of a `NetParams`
2225    ///
2226    /// This function is the common part shared between `parse2` and `parse`.
2227    fn from_param_values(params: &ParamValues<u32>) -> crate::Result<RelayBandwidth> {
2228        params
2229            .try_into()
2230            .map_err(|e: InvalidRelayBandwidth| EK::BadArgument.with_msg(e.to_string()))
2231    }
2232}
2233
2234impl Default for RelayBandwidth {
2235    fn default() -> RelayBandwidth {
2236        RelayBandwidth::Unmeasured(0)
2237    }
2238}
2239
2240impl TryFrom<&ParamValues<u32>> for RelayBandwidth {
2241    type Error = InvalidRelayBandwidth;
2242
2243    fn try_from(params: &ParamValues<u32>) -> Result<RelayBandwidth, InvalidRelayBandwidth> {
2244        let bw = params.params.get("Bandwidth");
2245        let unmeas = params.params.get("Unmeasured");
2246
2247        let bw = match bw {
2248            None => return Ok(RelayBandwidth::Unmeasured(0)),
2249            Some(b) => *b,
2250        };
2251
2252        match unmeas {
2253            None | Some(0) => Ok(RelayBandwidth::Measured(bw)),
2254            Some(1) => Ok(RelayBandwidth::Unmeasured(bw)),
2255            _ => Err(InvalidRelayBandwidth::InvalidUnmeasured),
2256        }
2257    }
2258}
2259
2260#[cfg(feature = "retain-unknown")]
2261impl TryFrom<ParamValues<u32>> for RelayBandwidthItem {
2262    type Error = InvalidRelayBandwidth;
2263
2264    fn try_from(params: ParamValues<u32>) -> Result<RelayBandwidthItem, InvalidRelayBandwidth> {
2265        Ok(RelayBandwidthItem {
2266            effective: (&params).try_into()?,
2267            params: Unknown::Retained(Some(params)),
2268        })
2269    }
2270}
2271
2272/// `parse2` impls for types in this modulea
2273///
2274/// Separate module for a separate namespace.
2275mod parse2_impls {
2276    use super::*;
2277    pub(super) use parse2::{
2278        ArgumentError as AE, ArgumentStream, ErrorProblem as EP, ItemArgumentParseable,
2279        ItemValueParseable, NetdocParseableFields,
2280    };
2281    use std::result::Result;
2282
2283    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
2284    impl<T: FromStr + NormalItemArgument> ItemValueParseable for ParamValues<T>
2285    where
2286        T::Err: std::error::Error,
2287    {
2288        fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2289            item.check_no_object()?;
2290            item.args_copy()
2291                .into_remaining()
2292                .parse()
2293                .map_err(item.invalid_argument_handler("parameters"))
2294        }
2295    }
2296
2297    impl ItemValueParseable for NetParams {
2298        fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2299            let params = ParamValues::from_unparsed(item)?;
2300            Ok(NetParams { params })
2301        }
2302    }
2303
2304    impl NetdocParseableFields for RelayBandwidthItem {
2305        type Accumulator = Option<ParamValues<u32>>;
2306
2307        fn is_item_keyword(kw: KeywordRef) -> bool {
2308            kw == Self::KEYWORD
2309        }
2310
2311        fn accumulate_item(acc: &mut Self::Accumulator, item: UnparsedItem) -> Result<(), EP> {
2312            if acc.is_some() {
2313                return Err(EP::ItemRepeated);
2314            }
2315            item.check_no_object()?;
2316            let params = ParamValues::from_unparsed(item)?;
2317            *acc = Some(params);
2318            Ok(())
2319        }
2320
2321        fn finish(params: Self::Accumulator, items: &ItemStream) -> Result<Self, EP> {
2322            let effective = params
2323                .as_ref()
2324                .map(TryFrom::try_from)
2325                .transpose()
2326                .map_err(|_| EP::OtherBadDocument("invalid information in `w` item"))?
2327                .unwrap_or_default();
2328
2329            let params = items.parse_options().retain_unknown_values.map(|()| params);
2330
2331            Ok(RelayBandwidthItem { effective, params })
2332        }
2333    }
2334
2335    impl ItemValueParseable for rs::SoftwareVersion {
2336        fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2337            item.check_no_object()?;
2338            item.args_mut()
2339                .into_remaining()
2340                .parse()
2341                .map_err(item.invalid_argument_handler("version"))
2342        }
2343    }
2344
2345    impl ItemArgumentParseable for IgnoredPublicationTimeSp {
2346        fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
2347            let mut next_arg = || a.next().ok_or(AE::Missing);
2348            let _: &str = next_arg()?;
2349            let _: &str = next_arg()?;
2350            Ok(IgnoredPublicationTimeSp)
2351        }
2352    }
2353}
2354
2355/// `encode` impls for types in this modulea
2356///
2357/// Separate module for a separate namespace.
2358mod encode_impls {
2359    use super::*;
2360    use std::result::Result;
2361    pub(crate) use {
2362        crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodableFields},
2363        tor_error::Bug,
2364    };
2365
2366    impl NetdocEncodableFields for RelayBandwidthItem {
2367        fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2368            if let Some(w) = self.params.as_ref().into_retained()? {
2369                w.write_item_value_onto(out.item(Self::KEYWORD))?;
2370            }
2371            Ok(())
2372        }
2373    }
2374
2375    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
2376    impl<T: NormalItemArgument + Ord + Display> ItemValueEncodable for ParamValues<T> {
2377        fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2378            for (k, v) in self.iter().collect::<BTreeSet<_>>() {
2379                if k.is_empty()
2380                    || k.chars()
2381                        .any(|c| c.is_whitespace() || c.is_control() || c == '=')
2382                {
2383                    // TODO torspec#401 see TODO in ParamValues<T> definition
2384                    return Err(bad_api_usage!(
2385                        "tried to encode NetParms with unreasonable keyword {k:?}"
2386                    ));
2387                }
2388                out.args_raw_string(&format_args!("{k}={v}"));
2389            }
2390            Ok(())
2391        }
2392    }
2393
2394    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
2395    impl ItemValueEncodable for NetParams {
2396        fn write_item_value_onto(&self, out: ItemEncoder) -> Result<(), Bug> {
2397            self.params.write_item_value_onto(out)
2398        }
2399    }
2400
2401    impl ItemValueEncodable for rs::SoftwareVersion {
2402        fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2403            out.args_raw_string(self);
2404            Ok(())
2405        }
2406    }
2407
2408    impl ItemArgument for IgnoredPublicationTimeSp {
2409        fn write_arg_onto(&self, out: &mut ItemEncoder) -> Result<(), Bug> {
2410            out.args_raw_string(&"2000-01-01 00:00:01");
2411            Ok(())
2412        }
2413    }
2414}
2415
2416impl ConsensusFooterFields {
2417    /// Parse a directory footer from a footer section.
2418    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
2419        use NetstatusKwd::*;
2420        sec.required(DIRECTORY_FOOTER)?;
2421
2422        let bandwidth_weights = sec
2423            .maybe(BANDWIDTH_WEIGHTS)
2424            .args_as_str()
2425            .unwrap_or("")
2426            .parse()?;
2427
2428        Ok(ConsensusFooterFields {
2429            bandwidth_weights,
2430            __non_exhaustive: (),
2431        })
2432    }
2433}
2434
2435/// `ProtoStatuses` parsing and encoding
2436///
2437/// Separate module for separate namespace
2438mod proto_statuses_parse2_encode {
2439    use super::encode_impls::*;
2440    use super::parse2_impls::*;
2441    use super::*;
2442    use paste::paste;
2443    use std::result::Result;
2444
2445    /// Implements `NetdocParseableFields` for `ProtoStatuses`
2446    ///
2447    /// We have this macro so that it's impossible to write things like
2448    /// ```text
2449    ///      ProtoStatuses {
2450    ///          client: ProtoStatus {
2451    ///              recommended: something something recommended_relay_versions something,
2452    /// ```
2453    ///
2454    /// (The structure of `ProtoStatuses` means the normal parse2 derive won't work for it.
2455    /// Note the bug above: the recommended *relay* version info is put in the *client* field.
2456    /// Preventing this bug must involve: avoiding writing twice the field name elements,
2457    /// such as `relay` and `client`, during this kind of construction/conversion.)
2458    macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
2459        #[derive(Deftly)]
2460        #[derive_deftly(NetdocParseableFields)]
2461        // Only ProtoStatusesParseNetdocParseAccumulator is exposed.
2462        #[allow(unreachable_pub)]
2463        pub struct ProtoStatusesParseHelper {
2464            $(
2465                #[deftly(netdoc(default))]
2466                [<$rr _ $cr _protocols>]: Protocols,
2467            )*
2468        }
2469
2470        /// Partially parsed `ProtoStatuses`
2471        pub use ProtoStatusesParseHelperNetdocParseAccumulator
2472            as ProtoStatusesNetdocParseAccumulator;
2473
2474        impl NetdocParseableFields for ProtoStatuses {
2475            type Accumulator = ProtoStatusesNetdocParseAccumulator;
2476            fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
2477                ProtoStatusesParseHelper::is_item_keyword(kw)
2478            }
2479            fn accumulate_item(
2480                acc: &mut Self::Accumulator,
2481                item: UnparsedItem<'_>,
2482            ) -> Result<(), EP> {
2483                ProtoStatusesParseHelper::accumulate_item(acc, item)
2484            }
2485            fn finish(acc: Self::Accumulator, items: &ItemStream<'_>) -> Result<Self, EP> {
2486                let parse = ProtoStatusesParseHelper::finish(acc, items)?;
2487                let mut out = ProtoStatuses::default();
2488                $(
2489                    out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
2490                )*
2491                Ok(out)
2492            }
2493        }
2494
2495        impl NetdocEncodableFields for ProtoStatuses {
2496            fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2497              $(
2498                self.$cr.$rr.write_item_value_onto(
2499                    out.item(concat!(stringify!($rr), "-", stringify!($cr), "-protocols"))
2500                )?;
2501              )*
2502                Ok(())
2503            }
2504        }
2505    } } }
2506
2507    impl_proto_statuses! {
2508        recommended client;
2509        recommended relay;
2510        required client;
2511        required relay;
2512    }
2513}
2514
2515impl Signature {
2516    /// Parse a Signature from a directory-signature section
2517    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Signature> {
2518        if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
2519            return Err(Error::from(internal!(
2520                "Wrong keyword {:?} for directory signature",
2521                item.kwd()
2522            ))
2523            .at_pos(item.pos()));
2524        }
2525
2526        let (digest_algo, id_fp, sk_fp) = if item.n_args() > 2 {
2527            (
2528                item.required_arg(0)?,
2529                item.required_arg(1)?,
2530                item.required_arg(2)?,
2531            )
2532        } else {
2533            // TODO #2530 digest_algo needs to depend on whether SHA1 was stated
2534            ("sha1", item.required_arg(0)?, item.required_arg(1)?)
2535        };
2536
2537        let digest_algo = digest_algo.to_string().parse().void_unwrap();
2538        let digest_algo = DigestAlgoInSignature(Some(digest_algo));
2539        let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
2540        let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
2541        let key_ids = AuthCertKeyIds {
2542            id_fingerprint,
2543            sk_fingerprint,
2544        };
2545        let signature = item.obj("SIGNATURE")?;
2546
2547        Ok(Signature {
2548            digest_algo,
2549            key_ids,
2550            signature,
2551            __non_exhaustive: (),
2552        })
2553    }
2554
2555    /// Return true if this signature has the identity key and signing key
2556    /// that match a given cert.
2557    fn matches_cert(&self, cert: &AuthCert) -> bool {
2558        cert.key_ids() == self.key_ids
2559    }
2560
2561    /// If possible, find the right certificate for checking this signature
2562    /// from among a slice of certificates.
2563    fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
2564        certs.iter().find(|&c| self.matches_cert(c))
2565    }
2566
2567    /// Find the certificate and assemble the pieces ready for verification
2568    ///
2569    /// `None` means precisely that we're missing the authcert.
2570    fn signature_to_verify<'r>(
2571        &'r self,
2572        signed_digest: &'r [u8],
2573        certs: &'r [AuthCert],
2574    ) -> Option<ConsensusSignatureToVerify> {
2575        let cert = self.find_cert(certs)?;
2576        let key = cert.signing_key();
2577        Some(ConsensusSignatureToVerify {
2578            key,
2579            signed_digest,
2580            signature: &self.signature,
2581        })
2582    }
2583}
2584
2585impl EncodeOrd for Signature {
2586    fn encode_cmp(&self, other: &Self) -> std::cmp::Ordering {
2587        let k: for<'s> fn(&'_ Signature) -> (&'_ _, &'_ _) = |s| (&s.key_ids, &s.signature);
2588        Ord::cmp(&k(self), &k(other))
2589    }
2590}
2591
2592/// Signature information in a consensus, to be verified
2593///
2594/// Used by callers of [`SignatureGroup::verify_general`],
2595/// to allow verification to be suppressed if all we wanted to know was
2596/// whether we have enough signatures and enough authcerts.
2597#[derive(Debug, Clone, Copy)]
2598struct ConsensusSignatureToVerify<'r> {
2599    /// KP_auth_sign_rsa
2600    key: &'r ll::pk::rsa::PublicKey,
2601
2602    /// The digest (actual RSA signature payload, before PKCS#11 padding)
2603    signed_digest: &'r [u8],
2604
2605    /// The RSA signature value
2606    signature: &'r [u8],
2607}
2608
2609/// Token indicating that signature verification has been done, if required
2610///
2611/// Prevents accidentally passing an unintended no-op function as
2612/// `do_verify` to [`SignatureGroup::verify_general`].
2613///
2614/// Write `SignatureVerifiedIfIntended {}` to construct this,
2615/// only in code which has actually done the verification,
2616/// or code which is deliberately not verifying at all.
2617pub(crate) struct SignatureVerifiedIfIntended {}
2618
2619impl<'r> ConsensusSignatureToVerify<'r> {
2620    /// Verify this signature
2621    ///
2622    fn verify(self) -> Result<SignatureVerifiedIfIntended, VerifyFailed> {
2623        self.key.verify(self.signed_digest, self.signature)?;
2624        Ok(SignatureVerifiedIfIntended {})
2625    }
2626}
2627
2628/// How `verify_general` should decide who is a trusted authority
2629///
2630/// Don't use this for other purposes
2631#[derive(Debug, Clone, Copy)]
2632pub(crate) enum VerifyGeneralTrustedAuthorities<'r> {
2633    /// Trust these authorities.
2634    TrustThese {
2635        /// The HKP_auth_id_rsa
2636        trusted: &'r [RsaIdentity],
2637    },
2638
2639    /// Document is a a vote, so OK if signed by any one of the listed authorities
2640    AnyOneOfThese {
2641        /// The HKP_auth_id_rsa
2642        trusted: &'r [RsaIdentity],
2643    },
2644
2645    /// For the benefit of `SignatureGroup::validate`, used by the old parser, only
2646    ///
2647    /// Every `AuthCert` passed to `verify_general` is a real authority (!)
2648    /// (But not necessarily a different one!)
2649    HazardouslyAssumeAllAuthCertsAreReal {
2650        /// Total number of authorities that we trust
2651        ///
2652        /// Used only to calculate the threshold
2653        n_authorities: usize,
2654    },
2655}
2656
2657/// Return the minimum number of authorities that we need signatures from
2658///
2659/// Enough is strictly more than half.
2660///
2661/// The returned value is a [`RangeFrom`](std::ops::RangeFrom), ie an inclusive range.
2662/// Its `start` value is the minimum acceptable number of authorities
2663/// from whom we have good signatures.
2664///
2665/// Should usually be followed by
2666/// [`.contains`](std::ops::RangeFrom::contains)`(&actual_number)`.
2667///
2668/// # Example
2669///
2670/// ```
2671/// use tor_netdoc::{doc::netstatus::consensus_threshold, parse2::VerifyFailed};
2672/// # fn main() -> Result<(), VerifyFailed> {
2673///
2674/// let n_trusted_authorities = 3;
2675/// let n_good_signatures_from_different_authorities = 2;
2676///
2677/// if consensus_threshold(n_trusted_authorities)
2678///      .contains(&n_good_signatures_from_different_authorities)
2679/// {
2680///     Ok(())
2681/// } else {
2682///     Err(VerifyFailed::InsufficientTrustedSigners)
2683/// }
2684/// # }
2685/// ```
2686pub fn consensus_threshold(n_authorities: usize) -> std::ops::RangeFrom<usize> {
2687    (n_authorities / 2) + 1 // strict majority
2688        ..
2689}
2690
2691impl SignatureGroup {
2692    // TODO: these functions are pretty similar and could probably stand to be
2693    // refactored a lot.
2694
2695    /// Helper: Return a pair of the number of possible authorities'
2696    /// signatures in this object for which we _could_ find certs, and
2697    /// a list of the signatures we couldn't find certificates for.
2698    fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
2699        let mut ok: HashSet<RsaIdentity> = HashSet::new();
2700        let mut missing = Vec::new();
2701        for sig in &self.signatures {
2702            let id_fingerprint = &sig.key_ids.id_fingerprint;
2703            if ok.contains(id_fingerprint) {
2704                continue;
2705            }
2706            if sig.find_cert(certs).is_some() {
2707                ok.insert(*id_fingerprint);
2708                continue;
2709            }
2710
2711            missing.push(sig);
2712        }
2713        (ok.len(), missing)
2714    }
2715
2716    /// Given a list of authority identity key fingerprints, return true if
2717    /// this signature group is _potentially_ well-signed according to those
2718    /// authorities.
2719    fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
2720        let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
2721        for sig in &self.signatures {
2722            let id_fp = &sig.key_ids.id_fingerprint;
2723            if signed_by.contains(id_fp) {
2724                // Already found this in the list.
2725                continue;
2726            }
2727            if authorities.contains(&id_fp) {
2728                signed_by.insert(*id_fp);
2729            }
2730        }
2731
2732        consensus_threshold(authorities.len()).contains(&signed_by.len())
2733    }
2734
2735    /// Return true if the signature group defines a valid signature.
2736    ///
2737    /// A signature is valid if it signed by more than half of the
2738    /// authorities.  This API requires that `n_authorities` is the number of
2739    /// authorities we believe in, and that every cert in `certs` belongs
2740    /// to a real authority.
2741    fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> Result<(), VerifyFailed> {
2742        // TODO we ought to take the set of trusted authorities as an argument,
2743        // rather than use VGTA::HazardouslyAssumeAllAuthCertsAreReal.
2744        self.verify_general(
2745            VerifyGeneralTrustedAuthorities::HazardouslyAssumeAllAuthCertsAreReal { n_authorities },
2746            certs,
2747            |tv| tv.verify(),
2748        )
2749    }
2750
2751    /// Check signatures (maybe), but not timeliness
2752    ///
2753    /// Examines the signatures and collates them with authcerts.
2754    /// Performs the necessary consensus signature verifications, via `do_verify`.
2755    ///
2756    /// If there are not enough authcerts or not enough signatures,
2757    /// throws a `ConsensusVerifiabilityError`.
2758    ///
2759    /// Differs from [`SignatureGroup::validate`]:
2760    ///
2761    ///  * Intended also for use with types from parse2.
2762    ///
2763    ///  * Yields information about missing authcerts directly in the return value,
2764    ///    and can be used without actually doing the verification,
2765    ///    so there's no need for a separate "which certs are we missing" function.
2766    ///
2767    ///  * Threshold is passed as a parameter (wanted for votes).
2768    ///
2769    ///  * Ability to check authority identities, by passing `trusted_authorities`.
2770    ///    (done with `authorities_are_correct` in old parser,
2771    ///    apparently with no engineered safeguard against consensus user omitting to do so).
2772    ///
2773    ///    **If `trusted_authorities` is None, all authorities in `certs` are treated as trusted**.
2774    ///
2775    ///  * Returns `Result`, not a boolean
2776    ///
2777    ///  * We prefer the term `verify` to `validate`.  All this does is signature verification.
2778    ///
2779    fn verify_general<E>(
2780        &self,
2781        trusted_authorities: VerifyGeneralTrustedAuthorities,
2782        certs: &[AuthCert],
2783        do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
2784    ) -> Result<(), E>
2785    where
2786        ConsensusVerifiabilityError: Into<E>,
2787    {
2788        use VerifyGeneralTrustedAuthorities as TA;
2789
2790        // A set of the authorities (by identity) who have have signed
2791        // this document.  We use a set here in case `certs` has more
2792        // than one certificate for a single authority.
2793        let mut ok: HashSet<RsaIdentity> = HashSet::new();
2794        let mut missing = HashSet::new();
2795        let mut verify_failed = Ok(());
2796
2797        for sig in &self.signatures {
2798            // Exhaustive pattern makes it hard to accidentally ignore a field.
2799            let Signature {
2800                digest_algo,
2801                key_ids:
2802                    AuthCertKeyIds {
2803                        id_fingerprint,
2804                        // h_kp_auth_sign_rsa, which Signature::check_signature
2805                        // checks against the authcert.
2806                        sk_fingerprint: _,
2807                    },
2808                // Used by Signature::check_signature
2809                signature: _,
2810                __non_exhaustive: (),
2811            } = sig;
2812
2813            match trusted_authorities {
2814                TA::TrustThese { trusted } | TA::AnyOneOfThese { trusted } => {
2815                    if !trusted.contains(id_fingerprint) {
2816                        continue;
2817                    }
2818                }
2819                TA::HazardouslyAssumeAllAuthCertsAreReal { .. } => {
2820                    // OK then!
2821                }
2822            }
2823
2824            if ok.contains(id_fingerprint) {
2825                // We already checked at least one signature using this
2826                // authority's identity fingerprint.
2827                continue;
2828            }
2829
2830            let Some(d) = self.hashes.hash_slice(digest_algo) else {
2831                // We don't support this kind of digest for this kind
2832                // of document.
2833                continue;
2834            };
2835
2836            let Some(tv) = sig.signature_to_verify(d, certs) else {
2837                missing.insert(sig.key_ids);
2838                continue;
2839            };
2840            match do_verify(tv) {
2841                Ok::<SignatureVerifiedIfIntended, _>(_) => {
2842                    ok.insert(*id_fingerprint);
2843                }
2844                Err(e) => {
2845                    verify_failed = Err(e);
2846                }
2847            }
2848        }
2849
2850        let n_authorities = match trusted_authorities {
2851            TA::TrustThese { trusted } => trusted.len(),
2852            TA::HazardouslyAssumeAllAuthCertsAreReal { n_authorities: n } => n,
2853            TA::AnyOneOfThese { .. } => {
2854                // strict majority of 1 is 1, so n_authorites being 1 leads to threshold of 1
2855                // (doing it this way avoids having both thresholds and authority counts
2856                // in the same code area, which might lead to confusing one with the other.
2857                1
2858            }
2859        };
2860        let threshold = consensus_threshold(n_authorities);
2861
2862        if threshold.contains(&ok.len()) {
2863            Ok(())
2864        } else {
2865            // Throw the verification error if any of the verifications failed
2866            verify_failed?;
2867
2868            // Otherwise report that we're missing certs and/or signers
2869            Err(if missing.is_empty() {
2870                ConsensusVerifiabilityError::InsufficientTrustedSigners
2871            } else {
2872                let deficit = threshold.start - ok.len();
2873                ConsensusVerifiabilityError::MissingAuthCerts { missing, deficit }
2874            }
2875            .into())
2876        }
2877    }
2878}
2879
2880impl From<ConsensusVerifiabilityError> for VerifyFailed {
2881    fn from(cve: ConsensusVerifiabilityError) -> VerifyFailed {
2882        use ConsensusVerifiabilityError as CVE;
2883        use VerifyFailed as VF;
2884        match cve {
2885            CVE::InsufficientTrustedSigners => VF::InsufficientTrustedSigners,
2886            CVE::MissingAuthCerts { .. } => VF::InsufficientTrustedSigners,
2887        }
2888    }
2889}
2890
2891impl From<ConsensusVerifyFailed> for VerifyFailed {
2892    fn from(cvf: ConsensusVerifyFailed) -> VerifyFailed {
2893        use ConsensusVerifyFailed as CVF;
2894        use VerifyFailed as VF;
2895        match cvf {
2896            CVF::CertificationInsufficient { .. } => VF::InsufficientTrustedSigners,
2897            CVF::InvalidSignature { .. } => VF::VerifyFailed,
2898        }
2899    }
2900}
2901
2902#[cfg(test)]
2903mod test {
2904    // @@ begin test lint list maintained by maint/add_warning @@
2905    #![allow(clippy::bool_assert_comparison)]
2906    #![allow(clippy::clone_on_copy)]
2907    #![allow(clippy::dbg_macro)]
2908    #![allow(clippy::mixed_attributes_style)]
2909    #![allow(clippy::print_stderr)]
2910    #![allow(clippy::print_stdout)]
2911    #![allow(clippy::single_char_pattern)]
2912    #![allow(clippy::unwrap_used)]
2913    #![allow(clippy::unchecked_time_subtraction)]
2914    #![allow(clippy::useless_vec)]
2915    #![allow(clippy::needless_pass_by_value)]
2916    #![allow(clippy::string_slice)] // See arti#2571
2917    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
2918    use super::*;
2919    use crate::doc::authcert::AuthCertUnverified;
2920    use crate::encode::{NetdocEncodable, NetdocEncodableFields};
2921    use crate::parse2::{ParseInput, parse_netdoc, parse_netdoc_multiple};
2922    use crate::test_support::{raw_find_item_rhs, regsub};
2923    use anyhow::Context as _;
2924    use assert_matches::assert_matches;
2925    use hex_literal::hex;
2926    use humantime::parse_rfc3339;
2927    use std::fmt::Debug;
2928    use std::fs;
2929    use std::time::Duration;
2930    use tor_checkable::TimeBound;
2931
2932    const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
2933    const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
2934
2935    const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
2936    const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
2937
2938    fn read_bad(fname: &str) -> String {
2939        use std::fs;
2940        use std::path::PathBuf;
2941        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2942        path.push("testdata");
2943        path.push("bad-mdconsensus");
2944        path.push(fname);
2945
2946        fs::read_to_string(path).unwrap()
2947    }
2948
2949    #[test]
2950    fn parse_and_validate_md() -> crate::Result<()> {
2951        use std::net::SocketAddr;
2952        use tor_checkable::{SelfSigned, TimeBound};
2953        let mut certs = Vec::new();
2954        for cert in AuthCert::parse_multiple(CERTS)? {
2955            let cert = cert?.check_signature()?.dangerously_assume_timely();
2956            certs.push(cert);
2957        }
2958        let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2959
2960        assert_eq!(certs.len(), 3);
2961
2962        let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
2963        let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2964
2965        // The set of authorities we know _could_ validate this cert.
2966        assert!(consensus.authorities_are_correct(&auth_ids));
2967        // A subset would also work.
2968        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2969        {
2970            // If we only believe in an authority that isn't listed,
2971            // that won't work.
2972            let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
2973            assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
2974        }
2975
2976        let missing = consensus.key_is_correct(&[]).err().unwrap();
2977        assert_eq!(3, missing.len());
2978        assert!(consensus.key_is_correct(&certs).is_ok());
2979        let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
2980        assert_eq!(2, missing.len());
2981
2982        // here is a trick that had better not work.
2983        let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
2984        let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
2985
2986        assert_eq!(2, missing.len());
2987        assert!(consensus.is_well_signed(&same_three_times).is_err());
2988
2989        assert!(consensus.key_is_correct(&certs).is_ok());
2990        let consensus = consensus.check_signature(&certs)?;
2991
2992        assert_eq!(6, consensus.relays().len());
2993        let r0 = &consensus.relays()[0];
2994        assert_eq!(
2995            r0.md_digest(),
2996            &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
2997        );
2998        assert_eq!(
2999            r0.rsa_identity().as_bytes(),
3000            &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
3001        );
3002        assert!(!r0.bandwidth().is_measured());
3003        assert!(!r0.bandwidth().is_nonzero());
3004        let pv = &r0.protovers();
3005        assert!(pv.supports_subver("HSDir", 2));
3006        assert!(!pv.supports_subver("HSDir", 3));
3007        let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
3008        let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
3009        assert!(r0.addrs().any(|a| a == ip4));
3010        assert!(r0.addrs().any(|a| a == ip6));
3011
3012        Ok(())
3013    }
3014
3015    #[test]
3016    fn parse_and_validate_ns() -> crate::Result<()> {
3017        use tor_checkable::{SelfSigned, TimeBound};
3018        let mut certs = Vec::new();
3019        for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
3020            let cert = cert?.check_signature()?.dangerously_assume_timely();
3021            certs.push(cert);
3022        }
3023        let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
3024        assert_eq!(certs.len(), 4);
3025
3026        let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
3027        let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
3028        // The set of authorities we know _could_ validate this cert.
3029        assert!(consensus.authorities_are_correct(&auth_ids));
3030        // A subset would also work.
3031        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
3032
3033        assert!(consensus.key_is_correct(&certs).is_ok());
3034
3035        let _consensus = consensus.check_signature(&certs)?;
3036
3037        Ok(())
3038    }
3039
3040    #[test]
3041    fn test_bad() {
3042        use crate::Pos;
3043        fn check(fname: &str, e: &Error) {
3044            let content = read_bad(fname);
3045            let res = MdConsensus::parse(&content);
3046            assert!(res.is_err());
3047            assert_eq!(&res.err().unwrap(), e);
3048        }
3049
3050        check(
3051            "bad-flags",
3052            &EK::BadArgument
3053                .at_pos(Pos::from_line(27, 1))
3054                .with_msg("Flags out of order"),
3055        );
3056        check(
3057            "bad-md-digest",
3058            &EK::BadArgument
3059                .at_pos(Pos::from_line(40, 3))
3060                .with_msg("Invalid base64"),
3061        );
3062        check(
3063            "bad-weight",
3064            &EK::BadArgument
3065                .at_pos(Pos::from_line(67, 141))
3066                .with_msg("invalid digit found in string"),
3067        );
3068        check(
3069            "bad-weights",
3070            &EK::BadArgument
3071                .at_pos(Pos::from_line(51, 13))
3072                .with_msg("invalid digit found in string"),
3073        );
3074        check(
3075            "wrong-order",
3076            &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
3077        );
3078        check(
3079            "wrong-start",
3080            &EK::UnexpectedToken
3081                .with_msg("vote-status")
3082                .at_pos(Pos::from_line(1, 1)),
3083        );
3084        check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
3085    }
3086
3087    fn gettok(s: &str) -> crate::Result<Item<'_, NetstatusKwd>> {
3088        let mut reader = NetDocReader::new(s)?;
3089        let tok = reader.next().unwrap();
3090        assert!(reader.next().is_none());
3091        tok
3092    }
3093
3094    #[test]
3095    fn test_weight() {
3096        let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
3097        let w = RelayBandwidthItem::from_item(&w).unwrap();
3098        assert!(!w.effective.is_measured());
3099        assert!(w.effective.is_nonzero());
3100
3101        let w = gettok("w Bandwidth=10\n").unwrap();
3102        let w = RelayBandwidthItem::from_item(&w).unwrap();
3103        assert!(w.effective.is_measured());
3104        assert!(w.effective.is_nonzero());
3105
3106        let w = RelayBandwidthItem::new_no_info();
3107        assert!(!w.effective.is_measured());
3108        assert!(!w.effective.is_nonzero());
3109
3110        let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
3111        let w = RelayBandwidthItem::from_item(&w).unwrap();
3112        assert!(!w.effective.is_measured());
3113        assert!(!w.effective.is_nonzero());
3114
3115        let w = gettok("r foo\n").unwrap();
3116        let w = RelayBandwidthItem::from_item(&w);
3117        assert!(w.is_err());
3118
3119        let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
3120        let w = RelayBandwidthItem::from_item(&w);
3121        assert!(w.is_err());
3122
3123        let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
3124        let w = RelayBandwidthItem::from_item(&w);
3125        assert!(w.is_err());
3126    }
3127
3128    #[test]
3129    fn test_netparam() {
3130        let p = "Hello=600 Goodbye=5 Fred=7"
3131            .parse::<ParamValues<u32>>()
3132            .unwrap();
3133        assert_eq!(p.get("Hello"), Some(&600_u32));
3134
3135        let p = "Hello=Goodbye=5 Fred=7".parse::<ParamValues<u32>>();
3136        assert!(p.is_err());
3137
3138        let p = "Hello=Goodbye Fred=7".parse::<ParamValues<u32>>();
3139        assert!(p.is_err());
3140
3141        for bad_kw in ["What=The", "", "\n", "\0"] {
3142            let p = [(bad_kw, 42)].into_iter().collect::<ParamValues<i32>>();
3143            let mut d = NetdocEncoder::new();
3144            let d = (|| {
3145                let i = d.item("bad-psrams");
3146                p.write_item_value_onto(i)?;
3147                d.finish()
3148            })();
3149            let _: tor_error::Bug = d.expect_err(bad_kw);
3150        }
3151    }
3152
3153    #[test]
3154    fn test_sharedrand() {
3155        let sr =
3156            gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
3157                .unwrap();
3158        let sr = SharedRandStatus::from_item(&sr).unwrap();
3159
3160        assert_eq!(sr.n_reveals, 9);
3161        assert_eq!(
3162            sr.value.0,
3163            hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
3164        );
3165        assert!(sr.timestamp.is_none());
3166
3167        let sr2 = gettok(
3168            "shared-rand-current-value 9 \
3169                    5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
3170        )
3171        .unwrap();
3172        let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
3173        assert_eq!(sr2.n_reveals, sr.n_reveals);
3174        assert_eq!(sr2.value.0, sr.value.0);
3175        assert_eq!(
3176            sr2.timestamp.unwrap().0,
3177            humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
3178        );
3179
3180        let sr = gettok("foo bar\n").unwrap();
3181        let sr = SharedRandStatus::from_item(&sr);
3182        assert!(sr.is_err());
3183    }
3184
3185    #[test]
3186    fn test_protostatus() {
3187        let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
3188
3189        let outcome = ProtoStatus {
3190            recommended: "Link=7".parse().unwrap(),
3191            required: "Desc=5".parse().unwrap(),
3192            __non_exhaustive: (),
3193        }
3194        .check_protocols(&my_protocols);
3195        assert!(outcome.is_ok());
3196
3197        let outcome = ProtoStatus {
3198            recommended: "Microdesc=4 Link=7".parse().unwrap(),
3199            required: "Desc=5".parse().unwrap(),
3200            __non_exhaustive: (),
3201        }
3202        .check_protocols(&my_protocols);
3203        assert_eq!(
3204            outcome,
3205            Err(ProtocolSupportError::MissingRecommended(
3206                "Microdesc=4".parse().unwrap()
3207            ))
3208        );
3209
3210        let outcome = ProtoStatus {
3211            recommended: "Microdesc=4 Link=7".parse().unwrap(),
3212            required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
3213            __non_exhaustive: (),
3214        }
3215        .check_protocols(&my_protocols);
3216        assert_eq!(
3217            outcome,
3218            Err(ProtocolSupportError::MissingRequired(
3219                "Cons=6-12 Wombat=15".parse().unwrap()
3220            ))
3221        );
3222    }
3223
3224    #[test]
3225    fn serialize_protostatus() {
3226        let ps = ProtoStatuses {
3227            client: ProtoStatus {
3228                recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
3229                required: "Link=5 LinkAuth=3".parse().unwrap(),
3230                __non_exhaustive: (),
3231            },
3232            relay: ProtoStatus {
3233                recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
3234                required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
3235                __non_exhaustive: (),
3236            },
3237            __non_exhaustive: (),
3238        };
3239        let json = serde_json::to_string(&ps).unwrap();
3240        let ps2 = serde_json::from_str(json.as_str()).unwrap();
3241        assert_eq!(ps, ps2);
3242
3243        let ps3: ProtoStatuses = serde_json::from_str(
3244            r#"{
3245            "client":{
3246                "required":"Link=5 LinkAuth=3",
3247                "recommended":"Link=1-5 LinkAuth=2-5"
3248            },
3249            "relay":{
3250                "required":"Wombat=20-22 Knish=25-27",
3251                "recommended":"Wombat=20-30 Knish=20-30"
3252            }
3253        }"#,
3254        )
3255        .unwrap();
3256        assert_eq!(ps, ps3);
3257    }
3258
3259    // consensuses are done in each_flavor.rs: see verify_error_netstatus
3260    #[test]
3261    fn verify_error_netstatus_vote() -> Result<(), anyhow::Error> {
3262        use VerifyFailed as VF;
3263        use VoteVerifyFailed as VVF;
3264        use vote::NetworkStatusUnverified as UV;
3265
3266        let file = "testdata2/v3-status-votes--1";
3267        let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3268        let input = ParseInput::new(&text, file);
3269        let doc: UV = parse_netdoc(&input)?;
3270        let trusted = || VoteVerifier::new([doc.peek_alleged_authority()]);
3271
3272        let edit_body = |f: &dyn Fn(&mut _)| {
3273            let (mut body, sigs) = doc.clone().unwrap_unverified();
3274            f(&mut body);
3275            UV::from_parts(body, sigs)
3276        };
3277
3278        // sabotage the overall signature
3279        {
3280            let mut doc = doc.clone();
3281            doc.sigs.sigs.directory_signature.signature.fill(0xff);
3282            assert_matches!(
3283                doc.verify(&mut trusted()),
3284                Err(VVF::InvalidSignature(VF::VerifyFailed))
3285            );
3286        }
3287
3288        // wrong authority
3289        {
3290            let doc = doc.clone();
3291            assert_matches!(
3292                doc.verify(&mut VoteVerifier::new([[0x55; _].into()])),
3293                Err(VVF::InvalidSignature(VF::InsufficientTrustedSigners))
3294            );
3295        }
3296
3297        // authcert is for a different authority
3298        {
3299            let doc = edit_body(&|body| {
3300                body.authority.authority.dir_source.identity.0 = [0x55; _].into();
3301            });
3302            assert_matches!(
3303                //
3304                doc.verify(&mut trusted()),
3305                Err(VVF::AuthCertWrongAuthority)
3306            );
3307        }
3308
3309        // authcert is from a different time
3310        let with_mutated_lifetime = |f: &dyn Fn(&mut Lifetime)| {
3311            let doc = edit_body(&|body| f(&mut body.preamble.lifetime));
3312            assert_matches!(
3313                //
3314                doc.verify(&mut trusted()),
3315                Err(VVF::AuthCertWrongValidity(_))
3316            );
3317        };
3318        let t_past = parse_rfc3339("1990-01-01T00:02:25Z")?;
3319        let t_future = parse_rfc3339("2010-01-01T00:02:25Z")?;
3320        with_mutated_lifetime(&|lifetime| lifetime.valid_after.0 = t_future);
3321        with_mutated_lifetime(&|lifetime| lifetime.fresh_until.0 = t_past);
3322        with_mutated_lifetime(&|lifetime| lifetime.valid_until.0 = t_past);
3323
3324        // syntactically invalid authcert
3325        {
3326            let mut text = text.clone();
3327            regsub(&mut text, "^dir-key-expires ", "dir-key-expires-SABOTAGED ");
3328            let input = ParseInput::new(&text, file);
3329            let doc: UV = parse_netdoc(&input)?;
3330            assert_matches!(
3331                //
3332                doc.verify(&mut trusted()),
3333                Err(VVF::AuthCertParseError(..))
3334            );
3335        }
3336
3337        // duplicate authorities
3338        {
3339            let mut trusted = trusted();
3340            assert_matches!(
3341                //
3342                doc.clone().verify(&mut trusted),
3343                Ok(_)
3344            );
3345            assert_matches!(
3346                doc.clone().verify(&mut trusted),
3347                Err(VVF::DuplicateAuthority(_))
3348            );
3349        }
3350
3351        Ok(())
3352    }
3353
3354    #[cfg(feature = "retain-unknown")]
3355    #[allow(clippy::type_complexity)]
3356    pub(super) fn prep_netstatus_verify<UV: NetdocParseable>(
3357        file: &str,
3358    ) -> anyhow::Result<(UV, String, Vec<AuthCert>, Vec<RsaIdentity>, SystemTime)> {
3359        let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3360
3361        let now = *raw_find_item_rhs(
3362            include_str!("../../testdata2/cached-microdesc-consensus"),
3363            "valid-after",
3364        )
3365        .parse::<Iso8601TimeSp>()
3366        .unwrap()
3367            + Duration::from_secs(1);
3368
3369        let input = ParseInput::new(&text, file).retain_unknown_values();
3370        let doc: UV = parse_netdoc(&input)?;
3371
3372        let certs = {
3373            let file = "testdata2/cached-certs";
3374            let text = fs::read_to_string(file)?;
3375            let input = ParseInput::new(&text, file);
3376            let certs: Vec<AuthCertUnverified> = parse_netdoc_multiple(&input)?;
3377            certs
3378                .into_iter()
3379                .map(|cert| cert.verify_selfcert(now))
3380                .collect::<Result<Vec<AuthCert>, _>>()?
3381        };
3382
3383        let authorities = certs.iter().map(|cert| *cert.fingerprint).collect_vec();
3384
3385        Ok((doc, text, certs, authorities, now))
3386    }
3387
3388    /// Check that a network document can be parsed and regenerated, mostly identically
3389    ///
3390    /// The regenerated encoded form doesn't need to be 100% identical:
3391    /// it is compared with a *munged* version of the the original input file,
3392    /// to cope with differences between C Tor and Arti.
3393    ///
3394    /// The mungings are:
3395    ///
3396    ///  * Some fields' syntax are adjusted, where C Tor and Arti disagree
3397    ///    in all kinds of network document.
3398    ///
3399    ///  * Document-specific, [`MungeForRoundtrip::adjust_exp`]
3400    #[cfg(feature = "retain-unknown")]
3401    fn roundtrip_netstatus<UV, V, VE>(
3402        // TODO DIRAUTH use include_str!, so, at call sites
3403        // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4121#note_3428675
3404        file: &str,
3405        verify: impl FnOnce(UV, &[RsaIdentity], &[AuthCert]) -> Result<TimeRangeBound<V>, VE>,
3406        adjust_now: Duration,
3407    ) -> anyhow::Result<()>
3408    where
3409        UV: NetdocParseable + NetdocParseableUnverified + MungeForRoundtrip,
3410        UV::Signatures: Clone + Debug + NetdocEncodableFields,
3411        VE: Debug + std::error::Error + Send + Sync + 'static,
3412        V: Debug + NetdocEncodable,
3413    {
3414        let (doc, text, certs, authorities, now) = prep_netstatus_verify::<UV>(file)?;
3415
3416        let now = now + adjust_now;
3417
3418        let sigs = doc.inspect_unverified().1.sigs.clone();
3419
3420        let doc = verify(doc, &authorities, &certs)?.if_valid_at(&now)?;
3421
3422        println!("{doc:#?}");
3423
3424        let mut enc = NetdocEncoder::new();
3425        doc.encode_unsigned(&mut enc)?;
3426        sigs.encode_fields(&mut enc)?;
3427        let enc = enc.finish()?;
3428
3429        let mut exp: String = text.clone();
3430
3431        // TODO DIRAUTH torspec!507 C Tor emits padded base64 in shared-rand-* items.
3432        regsub(
3433            //
3434            &mut exp,
3435            r#"^(shared-rand-.*)$"#,
3436            |c: &regex::Captures| {
3437                let mut s = c[1].to_owned();
3438                regsub(&mut s, r#"="#, "");
3439                s
3440            },
3441        );
3442
3443        // We don't manage proper numerical sorting of version numbers.
3444        // Doing so is awkward.  See the (2nd) TODO on RecommendedTorVersions.
3445        regsub(
3446            //
3447            &mut exp,
3448            r#"^(client|server)-versions (.+)$"#,
3449            |c: &regex::Captures| -> String {
3450                format!(
3451                    "{}-versions {}",
3452                    &c[1],
3453                    iter_join(",", c[2].split(',').sorted()),
3454                )
3455            },
3456        );
3457
3458        let mut regsub = |re, repl| regsub(&mut exp, re, repl);
3459
3460        // C Tor writes empty versions lines with trailing space
3461        regsub(
3462            //
3463            r#"^((?:client|server)-versions) $"#,
3464            "$1",
3465        );
3466
3467        // C Tor sometimes writes `shared-rand-commit` with trailing space
3468        regsub(
3469            //
3470            r#"^(shared-rand-commit .*) $"#,
3471            "$1",
3472        );
3473
3474        // C Tor emits `m` in varying places: after `a` in votes,
3475        // and at the end of each routerstatus in md consensuses.
3476        // We emit it at the start of each routerstatus, right after `r`.
3477        regsub(
3478            r#"(?x)
3479                   ( ^    r\ .* \n     )  #  ( r  )  $1, part before where we want to put m's
3480                   ( (?:     .* \n )*? )  #  (.*? )  $2, the rest, before the m's
3481                   ( (?:  m\ .* \n )+  )  #  ( m+ )  $3, one or more m's
3482            "#,
3483            r#"$1$3$2"#,
3484        );
3485
3486        UV::adjust_exp(&mut exp);
3487
3488        assert_eq_or_diff!(&exp, &enc);
3489
3490        Ok(())
3491    }
3492
3493    trait MungeForRoundtrip {
3494        /// Munge `s` so that it resembles the output of C Tor
3495        fn adjust_exp(exp: &mut String);
3496    }
3497
3498    /// Test that we can re-encode the consensus we parsed, and that we get the same thing back.
3499    ///
3500    /// Well, roughly the same thing.
3501    #[cfg(feature = "retain-unknown")]
3502    #[test]
3503    fn roundtrip_netstatus_plain() -> anyhow::Result<()> {
3504        roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3505            "testdata2/cached-consensus",
3506            plain::NetworkStatusUnverified::verify,
3507            Duration::ZERO,
3508        )
3509    }
3510
3511    impl MungeForRoundtrip for plain::NetworkStatusUnverified {
3512        fn adjust_exp(exp: &mut String) {
3513            let mut regsub = |re, repl| regsub(exp, re, repl);
3514
3515            // We emit the optional `ns`
3516            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:network-status-version
3517            regsub(
3518                r#"^network-status-version 3$"#,
3519                "network-status-version 3 ns",
3520            );
3521
3522            // C Tor writes nontrivial values for `publication` in rs `r` items,
3523            // but we use a fixed string.
3524            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:r
3525            regsub(
3526                r#"^(r \S+ \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3527                "$1 2000-01-01 00:00:01",
3528            );
3529        }
3530    }
3531
3532    #[cfg(feature = "retain-unknown")]
3533    #[test]
3534    fn roundtrip_netstatus_md() -> anyhow::Result<()> {
3535        roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3536            "testdata2/cached-microdesc-consensus",
3537            md::NetworkStatusUnverified::verify,
3538            Duration::ZERO,
3539        )
3540    }
3541
3542    impl MungeForRoundtrip for md::NetworkStatusUnverified {
3543        fn adjust_exp(exp: &mut String) {
3544            let mut regsub = |re, repl| regsub(exp, re, repl);
3545
3546            // C Tor writes nontrivial values for `publication` in rs `r` items,
3547            // but we use a fixed string.
3548            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:r
3549            //
3550            // Not the same as in plain consensus: one fewer fields!
3551            regsub(
3552                r#"^(r \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3553                "$1 2000-01-01 00:00:01",
3554            );
3555        }
3556    }
3557
3558    #[cfg(feature = "retain-unknown")]
3559    #[test]
3560    fn roundtrip_netstatus_vote() -> anyhow::Result<()> {
3561        roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3562            "testdata2/v3-status-votes--1",
3563            |doc, trusted, _| {
3564                vote::NetworkStatusUnverified::verify(
3565                    doc,
3566                    &mut VoteVerifier::new(trusted.iter().copied()),
3567                )
3568            },
3569            Duration::from_secs(20),
3570        )
3571    }
3572
3573    impl MungeForRoundtrip for vote::NetworkStatusUnverified {
3574        fn adjust_exp(exp: &mut String) {
3575            // C Tor writes items in consensuses a different order to in votes!
3576
3577            // C Tor writes different stats items with different floating point formats!
3578            let stats_massage_entry = |e: &str| {
3579                let mut e = e.to_owned();
3580                if e.contains('.') {
3581                    regsub(
3582                        &mut e,
3583                        // strip trailing 0's and then trailing `.`
3584                        r#"(?x)^ ( (?:wfu) = [0-9.]*? )( \.? 0+ ) $"#,
3585                        "$1",
3586                    );
3587                }
3588                e
3589            };
3590
3591            // C Tor writes stats items in votes in an apparently arbitrarily chosen order
3592            regsub(exp, r#"^stats (.+)$"#, |c: &regex::Captures| -> String {
3593                format!(
3594                    "stats {}",
3595                    iter_join(" ", c[1].split(' ').sorted().map(stats_massage_entry)),
3596                )
3597            });
3598
3599            let mut regsub = |re: &_, repl| regsub(exp, re, repl);
3600
3601            // C Tor writes *-protocols in an apparently arbitrarily chosen order
3602            regsub(
3603                r#"(?x)
3604                       ^ (recommended-relay-protocols\ .*)  \n
3605                         (recommended-client-protocols\ .*) \n
3606                         (required-relay-protocols\ .*)     \n
3607                         (required-client-protocols\ .*)    \n
3608                         (known-flags .*)$                  \n
3609                    "#,
3610                r#"$5
3611$2
3612$1
3613$4
3614$3
3615"#,
3616            );
3617
3618            // C Tor emits empty `client-versions` in consensuses, but not in votes.
3619            // (See also the fixup in `roundtrip_netstatus`, which relates to the *syntax*)
3620            //
3621            // Some of our inputs (eg the testdata2 votes) don't contain meaningful
3622            // info, so to make the C Tor output match our output, add them.
3623            regsub(
3624                r#"(?x) ^ (voting-delay\ .*) \n
3625                          (known-flags\ .*) \n"#,
3626                "$1
3627client-versions
3628server-versions
3629$2
3630",
3631            );
3632
3633            //#                         (?:  a\ .* \n )?    )   #    a? )           we want to put m's
3634
3635            for missing_field in [
3636                "bandwidth-file-headers", // TODO DIRAUTH implement
3637                "bandwidth-file-digest",  // TODO DIRAUTH implement
3638                "flag-thresholds",        // TODO DIRAUTH implement
3639            ] {
3640                regsub(&format!(r#"^{missing_field} .*\n"#), "");
3641            }
3642        }
3643    }
3644
3645    fn testdata_live(f: &str) -> String {
3646        // We implement an overrideable *prefix* rather than suffix, here,
3647        // so that we can access the files in a totally different directory.
3648        // (This is helpful with nailing-cargo, amongst other things.)
3649        let var = "TOR_NETDOC_TESTDATA_LIVE_PREFIX";
3650        let prefix = std::env::var_os(var)
3651            .map(|s| s.into_string().expect(var))
3652            .unwrap_or_else(|| "testdata-live/".into());
3653        format!("{prefix}{f}")
3654    }
3655
3656    #[allow(clippy::unnecessary_wraps)] // signature needs to match for roundtrip_netstatus
3657    fn unwrap_unverified_for_test<UV: NetdocParseableUnverified>(
3658        uv: UV,
3659        _ids: &[RsaIdentity],
3660        _certs: &[AuthCert],
3661    ) -> Result<TimeRangeBound<UV::Body>, std::convert::Infallible> {
3662        Ok(TimeRangeBound::new(uv.unwrap_unverified().0, ..))
3663    }
3664
3665    #[cfg(feature = "retain-unknown")]
3666    #[test]
3667    fn roundtrip_live_plain() -> anyhow::Result<()> {
3668        roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3669            &testdata_live("consensus"),
3670            unwrap_unverified_for_test,
3671            Duration::ZERO,
3672        )
3673    }
3674
3675    #[cfg(feature = "retain-unknown")]
3676    #[test]
3677    fn roundtrip_live_md() -> anyhow::Result<()> {
3678        roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3679            &testdata_live("consensus-microdesc"),
3680            unwrap_unverified_for_test,
3681            Duration::ZERO,
3682        )
3683    }
3684
3685    #[cfg(feature = "retain-unknown")]
3686    #[test]
3687    fn roundtrip_live_vote() -> anyhow::Result<()> {
3688        roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3689            &testdata_live("authority"),
3690            unwrap_unverified_for_test,
3691            Duration::ZERO,
3692        )
3693    }
3694
3695    #[cfg(feature = "retain-unknown")]
3696    #[test]
3697    fn sign_vote() -> anyhow::Result<()> {
3698        use crate::{
3699            encode::{encode_netdoc_fields, encode_netdoc_unsigned},
3700            test_support, testdata2,
3701        };
3702        use tor_llcrypto::pk::rsa;
3703
3704        let authcert = parse_netdoc::<AuthCertUnverified>(
3705            &ParseInput::new(testdata2::keys::AUTHORITY_CERTIFICATE, "authcert")
3706                .retain_unknown_values(),
3707        )?;
3708        let authcert = authcert.unwrap_unverified().0;
3709        let authority_id = authcert.fingerprint;
3710
3711        let doc = test_support::find_vote_by_authority_id(
3712            &ParseInput::new(testdata2::V3_STATUS_VOTES, "v3-status-votes").retain_unknown_values(),
3713            *authority_id,
3714        )
3715        .0
3716        .unwrap_unverified()
3717        .0;
3718
3719        let body = encode_netdoc_unsigned([&doc])?;
3720
3721        let sk =
3722            rsa::KeyPair::from_der(pem::parse(testdata2::keys::AUTHORITY_SIGNING_KEY)?.contents())
3723                .unwrap();
3724
3725        for hash_algo in [
3726            DirectorySignatureHashAlgo::Sha1,
3727            DirectorySignatureHashAlgo::Sha256,
3728        ] {
3729            let directory_signature =
3730                Signature::sign_text(&sk, &body, hash_algo, authcert.key_ids())?;
3731
3732            let sig = encode_netdoc_fields(&vote::NetworkStatusSignatures {
3733                directory_signature,
3734                __non_exhaustive: (),
3735            })?;
3736
3737            let signed = body.clone() + &sig;
3738
3739            let _: vote::NetworkStatus = parse_netdoc::<vote::NetworkStatusUnverified>(
3740                &ParseInput::new(&signed, "<signed>"),
3741            )?
3742            .verify(&mut VoteVerifier::new([*authority_id]))?
3743            .dangerously_assume_timely();
3744        }
3745
3746        Ok(())
3747    }
3748}