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

            
51
mod dir_source;
52
mod rs;
53

            
54
pub mod md;
55
pub mod plain;
56
pub mod vote;
57

            
58
#[cfg(feature = "build_docs")]
59
mod build;
60

            
61
pub use proto_statuses_parse2_encode::ProtoStatusesNetdocParseAccumulator;
62

            
63
use crate::doc::authcert::EncodedAuthCert;
64

            
65
use crate::doc::authcert::{self, AuthCert, AuthCertKeyIds, AuthCertUnverified};
66
use crate::encode::{
67
    EncodeOrd, ItemArgument, ItemEncoder, ItemValueEncodable, NetdocEncodable, NetdocEncoder,
68
};
69
use crate::parse::keyword::Keyword;
70
use crate::parse::parser::{Section, SectionRules, SectionRulesBuilder};
71
use crate::parse::tokenize::{Item, ItemResult, NetDocReader};
72
use crate::parse2::{
73
    self, ArgumentError, ArgumentStream, ErrorProblem, IsStructural, ItemArgumentParseable,
74
    ItemStream, ItemValueParseable, KeywordRef, NetdocParseable, NetdocParseableUnverified,
75
    SignatureHashInputs, SignatureItemParseable, StopAt, UnparsedItem, VerifyFailed,
76
};
77
use crate::types::relay_flags::{self, DocRelayFlags};
78
use crate::types::{self, *};
79
use crate::util::PeekableIterator;
80
use crate::{Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Pos};
81
use std::collections::{BTreeSet, HashMap, HashSet};
82
use std::fmt::{self, Display};
83
use std::slice;
84
use std::str::FromStr;
85
use std::sync::Arc;
86
use std::time::{self, SystemTime};
87
use std::{net, result};
88
use tor_basic_utils::iter_join;
89
use tor_error::{Bug, HasKind, bad_api_usage, internal};
90
use tor_protover::Protocols;
91
use void::ResultVoidExt as _;
92

            
93
use derive_deftly::{Deftly, define_derive_deftly};
94
use digest::Digest;
95
use educe::Educe;
96
use itertools::Itertools;
97
use saturating_time::SaturatingTime as _;
98
use std::sync::LazyLock;
99
use tor_checkable::{ExternallySigned, TimeBound, timed::TimeRangeBound};
100
use tor_llcrypto as ll;
101
use tor_llcrypto::pk::rsa::RsaIdentity;
102

            
103
use serde::{Deserialize, Deserializer};
104

            
105
#[cfg(feature = "build_docs")]
106
pub use build::MdConsensusBuilder;
107
#[cfg(feature = "build_docs")]
108
pub use build::PlainConsensusBuilder;
109
#[cfg(feature = "build_docs")]
110
ns_export_each_flavor! {
111
    ty: RouterStatusBuilder;
112
}
113

            
114
ns_export_each_variety! {
115
    ty: Footer, RouterStatus, Preamble;
116
}
117

            
118
#[deprecated]
119
pub use PlainConsensus as NsConsensus;
120
#[deprecated]
121
pub use PlainRouterStatus as NsRouterStatus;
122
#[deprecated]
123
pub use UncheckedPlainConsensus as UncheckedNsConsensus;
124
#[deprecated]
125
pub use UnvalidatedPlainConsensus as UnvalidatedNsConsensus;
126

            
127
#[deprecated]
128
pub use InvalidRelayBandwidth as InvalidRelayWeights;
129
#[deprecated]
130
pub use RelayBandwidth as RelayWeight;
131
#[deprecated]
132
pub use RelayBandwidthItem as RelayWeightsItem;
133
#[deprecated]
134
pub use VoteRelayBandwidthItem as VoteRelayWeightsItem;
135

            
136
pub use rs::{RouterStatusMdDigestsVote, RouterStatusMdDigestsVoteConstructor, SoftwareVersion};
137

            
138
pub use dir_source::{
139
    ConsensusAuthoritySection, ConsensusAuthoritySectionConstructor, DirSource,
140
    DirSourceConstructor, SupersededAuthorityKey,
141
};
142

            
143
define_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

            
156
define_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

            
163
define_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)]
185
pub 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)]
198
pub 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

            
234
define_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
14107
        pub fn new(
243
14107
            $( ${when FIELD} $fname: time::SystemTime, )
244
14107
        ) -> 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
148029
        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
530
        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
54696
        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
}
284
use 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
299
pub struct ConsensusMethod(pub u32);
300
impl 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)]
314
pub 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>
323
pub mod consensus_methods_comma_separated {
324
    use super::*;
325
    use parse2::ArgumentError as AE;
326
    use std::result::Result;
327

            
328
    /// Parse
329
1488
    pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
330
1488
        let mut methods = BTreeSet::new();
331
1488
        for ent in args.next().ok_or(AE::Missing)?.split(',') {
332
3052
            let ent = ent.parse().map_err(|_| AE::Invalid)?;
333
3052
            if !methods.insert(ent) {
334
                return Err(AE::Invalid);
335
3052
            }
336
        }
337
1488
        Ok(ConsensusMethods { methods })
338
1488
    }
339

            
340
    /// Encode
341
86
    pub fn write_arg_onto(self_: &ConsensusMethods, out: &mut ItemEncoder) -> Result<(), Bug> {
342
86
        out.args_raw_string(&iter_join(",", &self_.methods));
343
86
        Ok(())
344
86
    }
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)]
353
pub 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.
376
pub 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)]
432
pub struct ParamValues<T> {
433
    /// Map from keys to values.
434
    params: HashMap<String, T>,
435
}
436

            
437
impl<T> ParamValues<T> {
438
    /// Create a new empty list of NetParams.
439
    #[allow(unused)]
440
4
    pub fn new() -> Self {
441
4
        ParamValues::default()
442
4
    }
443
    /// Retrieve a given network parameter, if it is present.
444
    ///
445
    /// There is no safeguard against getting parameter names wrong.
446
203434
    pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
447
203434
        self.params.get(v.as_ref())
448
203434
    }
449
    /// Return an iterator over all key value pairs in an arbitrary order.
450
33927
    pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
451
33927
        self.params.iter()
452
33927
    }
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
2128
    pub fn set(&mut self, k: String, v: T) {
458
2128
        self.params.insert(k, v);
459
2128
    }
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
1325
    pub fn clear(&mut self, k: &str) {
466
1325
        self.params.remove(k);
467
1325
    }
468
}
469

            
470
impl<K: Into<String>, T> FromIterator<(K, T)> for ParamValues<T> {
471
6762
    fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
472
        ParamValues {
473
8294
            params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
474
        }
475
6762
    }
476
}
477

            
478
impl<T> std::iter::Extend<(String, T)> for ParamValues<T> {
479
3633
    fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
480
3633
        self.params.extend(iter);
481
3633
    }
482
}
483

            
484
impl<'de, T> Deserialize<'de> for ParamValues<T>
485
where
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)]
512
pub struct NetParams {
513
    /// Map from keys to values.
514
    params: NetParamValues,
515
}
516

            
517
impl 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
897502
    pub fn without_defaults(&self) -> &NetParamValues {
524
897502
        &self.params
525
897502
    }
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
1855
    pub fn set(&mut self, k: String, v: i32) {
540
1855
        self.params.set(k, v);
541
1855
    }
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
1325
    pub fn clear(&mut self, k: &str) {
550
1325
        self.params.clear(k);
551
1325
    }
552
}
553

            
554
impl<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)]
573
pub 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

            
591
impl 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
162
    pub fn check_protocols(
602
162
        &self,
603
162
        supported_protocols: &Protocols,
604
162
    ) -> Result<(), ProtocolSupportError> {
605
        // Required protocols take precedence, so we check them first.
606
162
        let missing_required = self.required.difference(supported_protocols);
607
162
        if !missing_required.is_empty() {
608
54
            return Err(ProtocolSupportError::MissingRequired(missing_required));
609
108
        }
610
108
        let missing_recommended = self.recommended.difference(supported_protocols);
611
108
        if !missing_recommended.is_empty() {
612
54
            return Err(ProtocolSupportError::MissingRecommended(
613
54
                missing_recommended,
614
54
            ));
615
54
        }
616

            
617
54
        Ok(())
618
162
    }
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]
625
pub 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

            
637
impl 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

            
644
impl 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)]
659
pub 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

            
671
impl ProtoStatuses {
672
    /// Return the list of recommended and required protocols for running as a client.
673
159
    pub fn client(&self) -> &ProtoStatus {
674
159
        &self.client
675
159
    }
676

            
677
    /// Return the list of recommended and required protocols for running as a relay.
678
2385
    pub fn relay(&self) -> &ProtoStatus {
679
2385
        &self.relay
680
2385
    }
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)]
704
pub struct RecommendedTorVersions(BTreeSet<String>);
705

            
706
/// Erroneous "recommended Tor versions" information
707
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
708
#[non_exhaustive]
709
pub 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

            
719
impl 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
173628
    pub fn is_known(&self) -> bool {
731
173628
        !self.is_empty()
732
173628
    }
733

            
734
    /// Construct a RecommendedTorVersions from a list of strings
735
    #[allow(clippy::should_implement_trait)] // we can't due to coherence
736
91482
    pub fn from_iter<I, S>(i: I) -> Result<Self, InvalidRecommendedTorVersions>
737
91482
    where
738
91482
        I: IntoIterator<Item = S>,
739
91482
        S: AsRef<str>,
740
    {
741
91482
        let mut set = BTreeSet::new();
742
91482
        for v in i {
743
93526
            let v = v.as_ref();
744
93526
            if v.is_empty() {
745
91186
                continue;
746
2340
            }
747
17840
            if v.chars().any(|c| c.is_whitespace()) {
748
                return Err(InvalidRecommendedTorVersions::ContainsWhitespace(
749
                    v.to_owned(),
750
                ));
751
2340
            }
752
2340
            if !set.insert(v.to_owned()) {
753
                return Err(InvalidRecommendedTorVersions::Repeated(v.to_owned()));
754
2340
            }
755
        }
756
91482
        Ok(RecommendedTorVersions(set))
757
91482
    }
758
}
759

            
760
impl FromStr for RecommendedTorVersions {
761
    type Err = InvalidRecommendedTorVersions;
762
91410
    fn from_str(s: &str) -> Result<Self, InvalidRecommendedTorVersions> {
763
91410
        Self::from_iter(s.split(','))
764
91410
    }
765
}
766

            
767
impl Display for RecommendedTorVersions {
768
14
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769
14
        write!(f, "{}", iter_join(",", &self.0))
770
14
    }
771
}
772

            
773
impl NormalItemArgument for RecommendedTorVersions {}
774

            
775
impl ItemValueEncodable for RecommendedTorVersions {
776
14
    fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
777
14
        out.args_raw_string(self);
778
14
        Ok(())
779
14
    }
780
}
781

            
782
impl ItemValueParseable for RecommendedTorVersions {
783
91396
    fn from_unparsed(mut item: UnparsedItem) -> Result<Self, ErrorProblem> {
784
        const FIELD: &str = "versions";
785
91396
        item.check_no_object()?;
786
91396
        let args = item.args_mut();
787
91396
        let arg = args.next().unwrap_or("");
788
91396
        arg.parse::<Self>()
789
            .map_err(|_| args.handle_error(FIELD, ArgumentError::Invalid))
790
91396
    }
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)]
802
pub 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

            
813
impl ConsensusFlavor {
814
    /// Return the name of this consensus flavor.
815
44944
    pub fn name(&self) -> &'static str {
816
44944
        match self {
817
17225
            ConsensusFlavor::Plain => "ns", // spec bug, now baked in
818
27719
            ConsensusFlavor::Microdesc => "microdesc",
819
        }
820
44944
    }
821
    /// Try to find the flavor whose name is `name`.
822
    ///
823
    /// For historical reasons, an unnamed flavor indicates an "Plain"
824
    /// document.
825
7
    pub fn from_opt_name(name: Option<&str>) -> crate::Result<Self> {
826
7
        match name {
827
6
            Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
828
1
            Some("ns") | None => Ok(ConsensusFlavor::Plain),
829
            Some(other) => {
830
                Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
831
            }
832
        }
833
7
    }
834
}
835

            
836
define_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
182544
        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
45707
                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
3160
        fn hash_slice(
900
3160
            &self,
901
3160
            algo: &DigestAlgoInSignature,
902
3160
        ) -> 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")]
919
pub 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)]
941
pub struct DigestAlgoInSignature(pub Option<KeywordOrString<DirectorySignatureHashAlgo>>);
942

            
943
impl ItemArgumentParseable for DigestAlgoInSignature {
944
182542
    fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<Self, ArgumentError> {
945
182542
        let v = if args
946
182542
            .clone()
947
182542
            .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
3817732
            .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
93210
            None
956
        } else {
957
89332
            Some(KeywordOrString::from_args(args)?)
958
        };
959
182542
        Ok(DigestAlgoInSignature(v))
960
182542
    }
961
}
962
impl ItemArgument for DigestAlgoInSignature {
963
30
    fn write_arg_onto(&self, out: &mut ItemEncoder<'_>) -> Result<(), Bug> {
964
30
        if let Some(y) = &self.0 {
965
14
            y.write_arg_onto(out)?;
966
16
        }
967
30
        Ok(())
968
30
    }
969
}
970
impl 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

            
980
impl DigestAlgoInSignature {
981
    /// Represent a known algorithm in the form used for the actual signature item
982
2
    pub fn from_algo(algo: DirectorySignatureHashAlgo) -> Self {
983
2
        DigestAlgoInSignature(match algo {
984
1
            DirectorySignatureHashAlgo::Sha1 => None,
985
1
            other => Some(KeywordOrString::Known(other)),
986
        })
987
2
    }
988
}
989

            
990
impl From<DirectorySignatureHashAlgo> for DigestAlgoInSignature {
991
    fn from(algo: DirectorySignatureHashAlgo) -> Self {
992
        Self::from_algo(algo)
993
    }
994
}
995

            
996
impl NormalItemArgument for DirectorySignatureHashAlgo {}
997

            
998
/// The signature of a single directory authority on a networkstatus document.
999
///
/// Implements `ItemValueParseable` which parses without hashing anything;
/// this is mostly useful for use by the `SignatureItemParseable` implementation.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
#[allow(clippy::exhaustive_structs)]
pub struct Signature {
    /// The name of the digest algorithm used to make the signature.
    ///
    /// Currently sha1 and sh256 are recognized.  Here we only support
    /// sha256.
    #[deftly(constructor)]
    pub digest_algo: DigestAlgoInSignature,
    /// Fingerprints of the keys for the authority that made
    /// this signature.
    #[deftly(netdoc(with = authcert::keyids_directory_signature_args))]
    #[deftly(constructor)]
    pub key_ids: AuthCertKeyIds,
    /// The signature itself.
    #[deftly(netdoc(object(label = "SIGNATURE"), with = types::raw_data_object))]
    #[deftly(constructor)]
    pub signature: Vec<u8>,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
impl SignatureItemParseable for Signature {
    type HashAccu = DirectorySignaturesHashesAccu;
182542
    fn from_unparsed_and_body(
182542
        item: UnparsedItem,
182542
        body: &SignatureHashInputs<'_>,
182542
        hash: &mut Self::HashAccu,
182542
    ) -> Result<Self, ErrorProblem> {
182542
        let signature = Signature::from_unparsed(item)?;
182542
        hash.update_from(&signature.digest_algo, body);
182542
        Ok(signature)
182542
    }
}
/// Error when trying to sign a network status
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SigningError {
    /// Error making the actual RSA signature
    #[error("signing netdoc: rsa")]
    Rsa(#[from] ll::pk::rsa::Error),
    /// Internal error
    #[error("signing netdoc: internal error")]
    Internal(#[from] Bug),
}
impl Signature {
    /// Make a network status document `Signature`, given the document text
    //
    // We provide this rather uncooked API, rather than (say) encode_sign,
    // because we need to excitingly manipulate consensus signatures,
    // adding them to existing documents, etc.
    //
    // The cooked encode_sign would have only one call site (dirauth voting),
    // so maybe we won't bother with it.
2
    pub fn sign_text(
2
        key: &ll::pk::rsa::KeyPair,
2
        text: &str,
2
        algo: DirectorySignatureHashAlgo,
2
        key_ids: AuthCertKeyIds,
2
    ) -> Result<Self, SigningError> {
        // We take AuthCertKeyIds since that seems better than taking a single loose
        // fingerprint for KP_auth_id_rsa and making it easy to pass KP_auth_sign_rsa
        // instead.  But this does mean we should probably check that KP_auth_sign_rsa
        // is right.
2
        if key_ids.sk_fingerprint != key.to_public_key().to_rsa_identity() {
            Err(bad_api_usage!(
                "incorrect KP_auth_sign_rsa passed in to netdoc signing"
            ))?;
2
        }
2
        let digest_algo = DigestAlgoInSignature::from_algo(algo);
2
        let mut accu = DirectorySignaturesHashesAccu::default();
2
        accu.update_from(
2
            &digest_algo,
2
            &SignatureHashInputs::new_for_signature(text, "directory-signature "),
2
        );
2
        let hash_slice = accu
2
            .hash_slice(&digest_algo)
            .ok_or_else(|| internal!("somehow failed to record hash of the in-use algo"))?;
2
        let signature = key.sign(hash_slice)?;
2
        Ok(SignatureConstructor {
2
            digest_algo,
2
            key_ids,
2
            signature,
2
        }
2
        .construct())
2
    }
}
/// A collection of signatures that can be checked on a networkstatus document
///
/// This is derived from the signatures section of a netstatus,
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:signature>,
/// but it is not isomorphic to it, and is not directly parseable.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SignatureGroup {
    /// The document hashes of the signed part of the document
    ///
    /// The pre-parse2 parser always sets `hashes.sha1` and `hashes.sha1_unnamed`
    /// to the same value, which is wrong. which is
    /// [bug #2530](https://gitlab.torproject.org/tpo/core/arti/-/work_items/2530)
    pub hashes: DirectorySignaturesHashesAccu,
    /// The signatures listed on the document.
    pub signatures: Vec<Signature>,
}
/// Error which will prevent us from attempting to verify signatures on a consensus
///
/// This error occurs if we the consensus isn't signed by the right people,
/// or we are lacking authcerts.
///
/// Does not represent actual verification errors.
/// Those show up as `VerifyFailed`, typically [`ConsensusVerifyFailed::InvalidSignature`].
///
/// Can be converted to a `VerifyFailed`,
/// giving [`InsufficientTrustedSigners`](VerifyFailed::InsufficientTrustedSigners).
#[derive(Clone, Debug, thiserror::Error)]
#[allow(clippy::exhaustive_enums)]
pub enum ConsensusVerifiabilityError {
    /// Insufficient trusted signers
    #[error("consensus not signed by enough authorities")]
    InsufficientTrustedSigners,
    /// Insufficient trusted signers because we are missing authcerts
    #[error("missing auth certs mean we could not verify enough consensus signatures (need at least {deficit} more, out of {} that are missing)", missing.len())]
    MissingAuthCerts {
        /// The number of additional useful authcerts that would be sufficient
        deficit: usize,
        /// All the authcerts that would be useful
        missing: HashSet<AuthCertKeyIds>,
    },
}
/// Error encountered while verifying a consensus
///
/// Thrown by
/// [`plain::NetworkStatusUnverified::verify`]
/// and
/// [`md::NetworkStatusUnverified::verify`].
///
/// Not used for problems with the validity period:
/// that's handled by `tor-checkable` and shows up as [`tor_checkable::TimeValidityError`].
///
/// Can be converted to a `VerifyFailed` (which, in effect, summarises the error).
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConsensusVerifyFailed {
    /// Certificates or signatures insufficient
    #[error("certs/sigs insufficient")]
    CertificationInsufficient(#[from] ConsensusVerifiabilityError),
    /// One or more signatures failed to verify
    #[error("invalid signature")]
    //
    // Not `#[from]` because we don't want to accidentally convert
    // ConsensusVerifiabilityError -> VerifyFailed -> ConsensusVerifyFailed
    // since that would give the wrong variant.
    InvalidSignature(#[source] VerifyFailed),
}
/// Context for verifying one or more votes intended for the same consensus period
///
/// Construct this from a set of trusted identities with [`VoteVerifier::new`]
/// and then call [`vote::NetworkStatusUnverified::verify`] for each vote.
///
/// Tracks which authorities' votes have already been verified, and throws
/// [`VoteVerifyFailed::DuplicateAuthority`] if one is repeated.
///
/// To verify a vote in isolation, use `vote.verify(&mut VoteVerifier::new(..))`,
/// but note that then any detection of duplicates in a set of votes is up to you.
pub struct VoteVerifier {
    /// The trusted authorites (including ones we've already seen).
    trusted: Vec<RsaIdentity>,
    /// The authorities whose votes we haven't yet verified, so we can still verify.
    remaining_good: HashSet<RsaIdentity>,
}
impl VoteVerifier {
    /// Start verifying votes: construct a new `VoteVerifier` from a set of trusted authorities
11
    pub fn new(trusted: impl IntoIterator<Item = RsaIdentity>) -> Self {
11
        let trusted = trusted.into_iter().collect_vec();
11
        let remaining_good = trusted.iter().copied().collect();
11
        VoteVerifier {
11
            trusted,
11
            remaining_good,
11
        }
11
    }
}
/// Error encountered while verifying a vote
///
/// Thrown by
/// [`vote::NetworkStatusUnverified::verify`].
///
/// Not used for problems with the validity period:
/// that's handled by `tor-checkable` and shows up as [`tor_checkable::TimeValidityError`].
///
/// Can be converted to a `VerifyFailed` (which, in effect, summarises the error).
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum VoteVerifyFailed {
    /// The document signature failed to verify
    #[error("invalid signature")]
    //
    // Not `#[from]` because we don't want to accidentally convert
    // VoteVerifyFailed::Something -> VerifyFailed -> VoteVerifyFailed
    // since that would give the wrong variant.
    InvalidSignature(#[source] VerifyFailed),
    /// Authcert couldn't be parsed
    #[error("unparseable authcert")]
    AuthCertParseError(#[source] parse2::ParseError),
    /// Authcert isn't valid for this vote's validity period
    #[error("authcert not valid for vote period")]
    AuthCertWrongValidity(#[source] tor_checkable::TimeValidityError),
    /// Authcert is for a different authority
    #[error("wrong authcert")]
    AuthCertWrongAuthority,
    /// Two or more votes from the same authority
    ///
    /// Often, this will be the result of a bug.
    #[error("duplicate authority {_0}")]
    DuplicateAuthority(RsaIdentity),
}
/// A shared random value produced by the directory authorities.
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] //
#[derive(derive_more::From, derive_more::Into, derive_more::AsRef)]
// (This doesn't need to use CtByteArray; we don't really need to compare these.)
pub struct SharedRandVal([u8; 32]);
/// A shared-random value produced by the directory authorities,
/// along with meta-information about that value.
#[derive(Debug, Clone, Deftly, Eq, PartialEq, Hash)]
#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
#[allow(clippy::exhaustive_structs)]
pub struct SharedRandStatus {
    /// How many authorities revealed shares that contributed to this value.
    #[deftly(constructor)]
    pub n_reveals: u8,
    /// The current random value.
    ///
    /// The properties of the secure shared-random system guarantee
    /// that this value isn't predictable before it first becomes
    /// live, and that a hostile party could not have forced it to
    /// have any more than a small number of possible random values.
    #[deftly(constructor)]
    pub value: SharedRandVal,
    /// The time when this SharedRandVal becomes (or became) the latest.
    ///
    /// (This is added per proposal 342, assuming that gets accepted.)
    pub timestamp: Option<Iso8601TimeNoSp>,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// The two shared random values, `shared-rand-*-value`
///
/// As found in the consensus preamble
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-current-value>
/// and a vote's authority section
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#authority-item-shared-rand-value>
#[derive(Debug, Clone, Default, Deftly)]
#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
#[allow(clippy::exhaustive_structs)]
pub struct SharedRandStatuses {
    /// Global shared-random value for the previous shared-random period.
    pub shared_rand_previous_value: Option<SharedRandStatus>,
    /// Global shared-random value for the current shared-random period.
    pub shared_rand_current_value: Option<SharedRandStatus>,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// Relay bandwidth information - `w` item in routerstatus in consensuses
///
/// This is a combination of two representations of (subsets of) the same information,
/// from an optional `w` in the document.
///
///  * [`effective`](RelayBandwidthItem::effective):
///
///    Always contains the effective bandwidth, as [`RelayBandwidth`].
///    This is what is used by clients.
///    It does not record whether a `w` line was actually present.
///
///  * [`params`](RelayBandwidthItem::params):
///
///    Can represent the presence and whole contents of the `w` line,
///    including all the known and unknown parameters.
///    This is within [`Unknown`], so it is only present with crate `feature = "retain-unknown"`,
///    and only some constructors/parsers record it.
///
/// # Parsing
///
/// Parsing is done with `NetdocParseableFields` rather than `ItemValueParseable`.
/// The `params` are [`Retained`](Unknown::Retained) if `retain_unknown_values` is
/// selected in [`parse2::ParseOptions`].
//
// We use NetdocParseableFields because the containing document, RouterStatus,
// contains `RelayBandwidthItem` rather than `Option<RelayBandwidthItem>`.
// The item parsing multiplicity machinery would see plain `RelayBandwidthItem` as a required item.
//
// This representation also means so that if retaining unknown information is compiled out
// (ie, in clients) each routerstatus entry stored in memory does not need to record
// whether `w` was present, merely what the implications were.
//
// We can't use ItemValueParseable with #[deftly(netdoc(default))]
// because `RelayBandwidthItem::default()` is a RelayBandwidthItem that definitively
// contains no pazrameters, ie with `Unknown::Retained`,
// and is therefore only conditionally available.
/// # Encoding
///
/// Encoding requires knowing whether a `w` line is to be included, and its contents,
/// so is implemented only with if `effective` is `Unknown::Retained`.
/// The encoding impl is only compiled in with `"retain-unknown"`,
/// and throws [`Bug`] if applied to a `RelayBandwidthItem` whose `params` are `Discarded`.
///
/// # Constructors
///
/// An "empty" `RelayBandwidthItem` can be constructed with [`RelayBandwidthItem::new_no_info`].
///
/// A `RelayBandwidthItem` containing only the effective `RelayBandwidth`
/// can be constructed using [`RelayBandwidthItem::from_effective`].
///
/// With `"retain-unknown"`:
/// a `RelayBandwidthItem` can be constructed from a [`ParamValues<u32>`] using `TryFrom`;
/// and, implements `Default`, which yields a `RelayBandwidthItem`
/// representing the (known) absence of a `w` line.
//
// Fields are private to maintain the invariant.
#[derive(Debug, Clone)]
pub struct RelayBandwidthItem {
    /// The effective relay bandwidth
    effective: RelayBandwidth,
    /// The complete parameter set, if available and `w` was present.
    params: Unknown<Option<ParamValues<u32>>>,
}
/// Relay bandwidth information - `w` item in routerstatus in votes
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(NetdocEncodableFields, NetdocParseableFields)]
#[allow(clippy::exhaustive_structs)] // this is always just this single item
pub struct VoteRelayBandwidthItem {
    /// The parameters, uninterpreted.
    pub w: Option<ParamValues<u32>>,
}
/// Recognized bandwidth fields on a single relay in a consensus
///
/// The part of a `w` item that we understand as a client.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum RelayBandwidth {
    /// An unmeasured bandwidth for a relay.
    Unmeasured(u32),
    /// An measured bandwidth for a relay.
    Measured(u32),
}
/// Error processing a `w` line's netparams into an effective relay bandwidth
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum InvalidRelayBandwidth {
    /// Invalid value for `Unmeasured`
    #[error("invalid value for Unmeasured")]
    InvalidUnmeasured,
}
/// Authority entry in a consensus - deprecated compatibility type alias
#[deprecated = "renamed to ConsensusAuthorityEntry"]
pub type ConsensusVoterInfo = ConsensusAuthorityEntry;
/// Authority entry in a plain consensus - type alias provided for consistency
pub type PlainAuthorityEntry = ConsensusAuthorityEntry;
/// Authority entry in an md consensus - type alias provided for consistency
pub type MdAuthorityEntry = ConsensusAuthorityEntry;
/// An authority entry as found in a consensus
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority-entry>
///
/// See also [`VoteAuthorityEntry`]
//
// We don't use the `each_variety` system for this because:
//  1. That avoids separating the two consensus authority entry types, which are identical
//  2. The only common fields are `dir-source` and `contact`, so there is little duplication
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
#[allow(clippy::exhaustive_structs)]
pub struct ConsensusAuthorityEntry {
    /// Contents of the `dir-source` line about an authority
    #[deftly(constructor)]
    pub dir_source: DirSource,
    /// Human-readable contact information about the authority
    //
    // If more non-intro fields get added that are the same in votes and cosensuses,
    // consider using each_variety.rs or breaking those fields out into
    // `AuthorityEntryCommon` implementing `NetdocParseableFields`, or something.
    #[deftly(constructor)]
    pub contact: ContactInfo,
    /// Digest of the vote that the authority cast to contribute to
    /// this consensus.
    ///
    /// This is not a fixed-length, fixed-algorithm field.
    /// Bizarrely, the algorithm is supposed to be inferred from the length!
    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-digest>
    #[deftly(netdoc(single_arg))]
    #[deftly(constructor)]
    pub vote_digest: B16U,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// An authority entry as found in a vote
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority-entry>
///
/// See also [`ConsensusAuthorityEntry`]
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
#[allow(clippy::exhaustive_structs)]
pub struct VoteAuthorityEntry {
    /// Contents of the `dir-source` line about an authority
    #[deftly(constructor)]
    pub dir_source: DirSource,
    /// Human-readable contact information about the authority
    #[deftly(constructor)]
    pub contact: ContactInfo,
    /// `legacy-dir-key` - superseded authority identity key
    ///
    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:legacy-dir-key>
    #[deftly(netdoc(single_arg))]
    pub legacy_dir_key: Option<Fingerprint>,
    /// `shared-rand-participate` - Indicate shared random participation
    ///
    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-participate>
    pub shared_rand_participate: Option<SharedRandParticipate>,
    /// `shared-rand-commit` - Shared random commitment
    ///
    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
    pub shared_rand_commit: Vec<SharedRandCommit>,
    /// Global shared-random values
    #[deftly(netdoc(flatten))]
    pub shared_rand: SharedRandStatuses,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// `shared-rand-participate` in a vote authority entry
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-participate>
//
// We could have done `shared_rand_participate: Option<()>` in VoteAuthorityEntry,
// but then we might end up with variables of type `&Option<()>` etc.
// whose meaning has been detached from its type.
//
// TODO DIRAUTH rework this according to the API design conclusion from !3977 when there is one
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
#[allow(clippy::exhaustive_structs)]
pub struct SharedRandParticipate {
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// `shared-rand-commit` in a vote authority entry
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
// If new protocols use this item with a different version, we'll call it an API break.
#[allow(clippy::exhaustive_enums)]
pub enum SharedRandCommit {
    /// Version 1, the only one supported
    V1(SharedRandCommitV1),
    /// Other versions.  Cannot be encoded.
    // It's not clear that future versions will use this version mechanism.  torspec#408.
    Unknown {},
}
/// `shared-rand-commit` in a vote authority entry
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
///
/// Version and hash are not explicitly represented.  See torspec#407.
///
/// `ItemValueEncodable` and `ItemValueParseable` impls do not include the fixed arguments;
/// in a netdoc, this type should be used within `SharedRandCommit::V1`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
#[allow(clippy::exhaustive_structs)]
pub struct SharedRandCommitV1 {
    /// Authority id key, recapitulated.
    // TODO this field shouldn't here at all torspec#407
    #[deftly(constructor)]
    h_kp_auth_id_rsa: Fingerprint,
    /// Commitment
    ///
    /// `TIMESTAMP || SHA3_256(REVEAL)`, as per
    /// <https://spec.torproject.org/srv-spec/specification.html#COMMITREVEAL>
    //
    // TOOD we would like to replace this with a type that separates out the pieces!
    // But that would need a FixedB64 generic over some tor-bytes trait, or something.
    #[deftly(constructor)]
    commit: FixedB64<40>,
    /// Reveal
    ///
    /// `TIMESTAMP || random number`, as per
    /// <https://spec.torproject.org/srv-spec/specification.html#COMMITREVEAL>
    reveal: Option<FixedB64<40>>,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
impl SharedRandCommitV1 {
    /// The fixed arguments that precede the actual value in `shared-rand-commit 1 ...`
    const FIXED_ARGUMENTS: &[&str] = &["1", "sha3-256"];
}
impl ItemValueEncodable for SharedRandCommit {
17
    fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
17
        match self {
            SharedRandCommit::V1(values) => {
17
                for fixed in SharedRandCommitV1::FIXED_ARGUMENTS {
34
                    out.args_raw_string(fixed);
                }
17
                values.write_item_value_onto(out)
            }
            SharedRandCommit::Unknown {} => Err(internal!("encoding SharedRandCommit::Unknown")),
        }
17
    }
}
impl ItemValueParseable for SharedRandCommit {
531
    fn from_unparsed(mut item: UnparsedItem<'_>) -> Result<Self, ErrorProblem> {
531
        let mut fixed = SharedRandCommitV1::FIXED_ARGUMENTS.iter().copied();
531
        let args = item.args_mut();
531
        let version = args
531
            .next()
            .ok_or_else(|| args.handle_error("version", ArgumentError::Missing))?;
531
        if version != fixed.next().expect("nonempty") {
            return Ok(SharedRandCommit::Unknown {});
531
        }
531
        for exp in fixed {
531
            let got = args
531
                .next()
                .ok_or_else(|| args.handle_error(exp, ArgumentError::Missing))?;
531
            if got != exp {
                Err(args.handle_error(exp, ArgumentError::Invalid))?;
531
            }
        }
531
        let values = SharedRandCommitV1::from_unparsed(item)?;
531
        Ok(SharedRandCommit::V1(values))
531
    }
}
// For `ConsensusAuthoritySection`, see `dir_source.rs`.
define_derive_deftly! {
    /// Ad-hoc derive, `impl NetdocParseable for VoteAuthoritySection`
    ///
    /// We can't derive from `VoteAuthoritySection` with the normal macros, because
    /// it's not a document, with its own intro item.  It's just a collection of sub-documents.
    /// The netdoc derive macros don't have support for that - and it would be a fairly
    /// confusing thing to support because you'd end up with nested multiplicities and a whole
    /// variety of "intro item keywords" that were keywords for arbitrary sub-documents.
    ///
    /// Instead, we do that ad-hoc here.  It's less confusing because we don't need to
    /// worry about multiplicity, and because we know what only the outer document is
    /// that will contain this.
    VoteAuthoritySection:
    ${defcond F_NORMAL not(fmeta(netdoc(skip)))}
    impl NetdocParseable for VoteAuthoritySection {
64
        fn doctype_for_error() -> &'static str {
            "vote.authority.section"
        }
11285
        fn is_intro_item_keyword(kw: KeywordRef<'_>) -> bool {
            VoteAuthorityEntry::is_intro_item_keyword(kw)
        }
427
        fn is_structural_keyword(kw: KeywordRef<'_>) -> Option<IsStructural> {
          $(
            ${when F_NORMAL}
            if let y @ Some(_) = $ftype::is_structural_keyword(kw) {
                return y;
            }
          )
            None
        }
64
        fn from_items<'s>(
64
            input: &mut ItemStream<'s>,
64
            stop_outer: stop_at!(),
64
        ) -> Result<Self, ErrorProblem> {
            let stop_inner = stop_outer
              $(
                ${when F_NORMAL}
                | StopAt($ftype::is_intro_item_keyword)
              )
            ;
            Ok(VoteAuthoritySection { $(
                ${when F_NORMAL}
                $fname: NetdocParseable::from_items(input, stop_inner)?,
            )
                __non_exhaustive: (),
            })
        }
    }
    impl NetdocEncodable for VoteAuthoritySection {
3
        fn encode_unsigned(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
          $(
            ${when F_NORMAL}
            self.$fname.encode_unsigned(out)?;
          )
          Ok(())
        }
    }
}
/// An authority section in a vote
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority>
//
// We have split this out to help encapsulate vote/consensus-specific
// information in a forthcoming overall network status document type.
#[derive(Deftly, Clone, Debug)]
#[derive_deftly(VoteAuthoritySection, Constructor)]
#[allow(clippy::exhaustive_structs)]
pub struct VoteAuthoritySection {
    /// Authority entry
    #[deftly(constructor)]
    pub authority: VoteAuthorityEntry,
    /// Authority key certificate
    #[deftly(constructor)]
    pub cert: EmbeddedCert<AuthCert, EncodedAuthCert>,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// Fields in the footer of a consensus
///
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:footer>
///
/// Not the whole footer, because it lacks the `directory-footer` item.
#[derive(Debug, Clone, Deftly)]
#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
#[allow(clippy::exhaustive_structs)]
pub struct ConsensusFooterFields {
    /// `bandwidth-weights`
    ///
    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:bandwidth-weights>
    #[deftly(netdoc(default))]
    pub bandwidth_weights: ParamValues<i32>,
    #[doc(hidden)]
    #[deftly(netdoc(skip))]
    pub __non_exhaustive: (),
}
/// A consensus document that lists relays along with their
/// microdescriptor documents.
pub type MdConsensus = md::Consensus;
/// An MdConsensus that has been parsed and checked for timeliness,
/// but not for signatures.
pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
/// An MdConsensus that has been parsed but not checked for signatures
/// and timeliness.
pub type UncheckedMdConsensus = md::UncheckedConsensus;
/// A consensus document that lists relays along with their
/// router descriptor documents.
pub type PlainConsensus = plain::Consensus;
/// An PlainConsensus that has been parsed and checked for timeliness,
/// but not for signatures.
pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
/// An PlainConsensus that has been parsed but not checked for signatures
/// and timeliness.
pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
decl_keyword! {
    /// Keywords that can be used in votes and consensuses.
    // TODO: This is public because otherwise we can't use it in the
    // ParseRouterStatus crate.  But I'd rather find a way to make it
    // private.
    #[non_exhaustive]
    #[allow(missing_docs)]
    pub NetstatusKwd {
        // Header
        "network-status-version" => NETWORK_STATUS_VERSION,
        "vote-status" => VOTE_STATUS,
        "consensus-methods" => CONSENSUS_METHODS,
        "consensus-method" => CONSENSUS_METHOD,
        "published" => PUBLISHED,
        "valid-after" => VALID_AFTER,
        "fresh-until" => FRESH_UNTIL,
        "valid-until" => VALID_UNTIL,
        "voting-delay" => VOTING_DELAY,
        "client-versions" => CLIENT_VERSIONS,
        "server-versions" => SERVER_VERSIONS,
        "known-flags" => KNOWN_FLAGS,
        "flag-thresholds" => FLAG_THRESHOLDS,
        "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
        "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
        "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
        "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
        "params" => PARAMS,
        "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
        "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
        // "package" is now ignored.
        // header in consensus, voter section in vote?
        "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
        "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
        // Voter section (both)
        "dir-source" => DIR_SOURCE,
        "contact" => CONTACT,
        // voter section (vote, but not consensus)
        "legacy-dir-key" => LEGACY_DIR_KEY,
        "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
        "shared-rand-commit" => SHARED_RAND_COMMIT,
        // voter section (consensus, but not vote)
        "vote-digest" => VOTE_DIGEST,
        // voter cert beginning (but only the beginning)
        "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
        // routerstatus
        "r" => RS_R,
        "a" => RS_A,
        "s" => RS_S,
        "v" => RS_V,
        "pr" => RS_PR,
        "w" => RS_W,
        "p" => RS_P,
        "m" => RS_M,
        "id" => RS_ID,
        // footer
        "directory-footer" => DIRECTORY_FOOTER,
        "bandwidth-weights" => BANDWIDTH_WEIGHTS,
        "directory-signature" => DIRECTORY_SIGNATURE,
    }
}
/// Shared parts of rules for all kinds of netstatus headers
1
static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
    use NetstatusKwd::*;
1
    let mut rules = SectionRules::builder();
1
    rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
1
    rules.add(VOTE_STATUS.rule().required().args(1..));
1
    rules.add(VALID_AFTER.rule().required());
1
    rules.add(FRESH_UNTIL.rule().required());
1
    rules.add(VALID_UNTIL.rule().required());
1
    rules.add(VOTING_DELAY.rule().args(2..));
1
    rules.add(CLIENT_VERSIONS.rule());
1
    rules.add(SERVER_VERSIONS.rule());
1
    rules.add(KNOWN_FLAGS.rule().required());
1
    rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
1
    rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
1
    rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
1
    rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
1
    rules.add(PARAMS.rule());
1
    rules
1
});
/// Rules for parsing the header of a consensus.
1
static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
    use NetstatusKwd::*;
1
    let mut rules = NS_HEADER_RULES_COMMON_.clone();
1
    rules.add(CONSENSUS_METHOD.rule().args(1..=1));
1
    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1
    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1
    rules.build()
1
});
/*
/// Rules for parsing the header of a vote.
static NS_HEADER_RULES_VOTE: SectionRules<NetstatusKwd> = {
    use NetstatusKwd::*;
    let mut rules = NS_HEADER_RULES_COMMON_.clone();
    rules.add(CONSENSUS_METHODS.rule().args(1..));
    rules.add(FLAG_THRESHOLDS.rule());
    rules.add(BANDWIDTH_FILE_HEADERS.rule());
    rules.add(BANDWIDTH_FILE_DIGEST.rule().args(1..));
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
    rules
};
/// Rules for parsing a single voter's information in a vote.
static NS_VOTERINFO_RULES_VOTE: SectionRules<NetstatusKwd> = {
    use NetstatusKwd::*;
    let mut rules = SectionRules::new();
    rules.add(DIR_SOURCE.rule().required().args(6..));
    rules.add(CONTACT.rule().required());
    rules.add(LEGACY_DIR_KEY.rule().args(1..));
    rules.add(SHARED_RAND_PARTICIPATE.rule().no_args());
    rules.add(SHARED_RAND_COMMIT.rule().may_repeat().args(4..));
    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
    // then comes an entire cert: When we implement vote parsing,
    // we should use the authcert code for handling that.
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
    rules
};
 */
/// Rules for parsing a single voter's information in a consensus
1
static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
    use NetstatusKwd::*;
1
    let mut rules = SectionRules::builder();
1
    rules.add(DIR_SOURCE.rule().required().args(6..));
1
    rules.add(CONTACT.rule().required());
1
    rules.add(VOTE_DIGEST.rule().required());
1
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1
    rules.build()
1
});
/// Shared rules for parsing a single routerstatus
static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
1
    LazyLock::new(|| {
        use NetstatusKwd::*;
1
        let mut rules = SectionRules::builder();
1
        rules.add(RS_A.rule().may_repeat().args(1..));
1
        rules.add(RS_S.rule().required());
1
        rules.add(RS_V.rule());
1
        rules.add(RS_PR.rule().required());
1
        rules.add(RS_W.rule());
1
        rules.add(RS_P.rule().args(2..));
1
        rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1
        rules
1
    });
/// Rules for parsing a single routerstatus in an NS consensus
1
static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
    use NetstatusKwd::*;
1
    let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1
    rules.add(RS_R.rule().required().args(8..));
1
    rules.build()
1
});
/*
/// Rules for parsing a single routerstatus in a vote
static NS_ROUTERSTATUS_RULES_VOTE: SectionRules<NetstatusKwd> = {
    use NetstatusKwd::*;
        let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
        rules.add(RS_R.rule().required().args(8..));
        rules.add(RS_M.rule().may_repeat().args(2..));
        rules.add(RS_ID.rule().may_repeat().args(2..)); // may-repeat?
        rules
    };
*/
/// Rules for parsing a single routerstatus in a microdesc consensus
1
static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
    use NetstatusKwd::*;
1
    let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1
    rules.add(RS_R.rule().required().args(6..));
1
    rules.add(RS_M.rule().required().args(1..));
1
    rules.build()
1
});
/// Rules for parsing consensus fields from a footer.
1
static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
    use NetstatusKwd::*;
1
    let mut rules = SectionRules::builder();
1
    rules.add(DIRECTORY_FOOTER.rule().required().no_args());
    // consensus only
1
    rules.add(BANDWIDTH_WEIGHTS.rule());
1
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1
    rules.build()
1
});
impl ProtoStatus {
    /// Construct a ProtoStatus from two chosen keywords in a section.
14
    fn from_section(
14
        sec: &Section<'_, NetstatusKwd>,
14
        recommend_token: NetstatusKwd,
14
        required_token: NetstatusKwd,
14
    ) -> crate::Result<ProtoStatus> {
        /// Helper: extract a Protocols entry from an item's arguments.
28
        fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> crate::Result<Protocols> {
28
            if let Some(item) = t {
28
                item.args_as_str()
28
                    .parse::<Protocols>()
                    .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
            } else {
                Ok(Protocols::new())
            }
28
        }
14
        let recommended = parse(sec.get(recommend_token))?;
14
        let required = parse(sec.get(required_token))?;
14
        Ok(ProtoStatus {
14
            recommended,
14
            required,
14
            __non_exhaustive: (),
14
        })
14
    }
    /// Return the protocols that are listed as "required" in this `ProtoStatus`.
    ///
    /// Implementations may assume that relays on the network implement all the
    /// protocols in the relays' required-protocols list.  Implementations should
    /// refuse to start if they do not implement all the protocols on their own
    /// (client or relay) required-protocols list.
2385
    pub fn required_protocols(&self) -> &Protocols {
2385
        &self.required
2385
    }
    /// Return the protocols that are listed as "recommended" in this `ProtoStatus`.
    ///
    /// Implementations should warn if they do not implement all the protocols
    /// on their own (client or relay) recommended-protocols list.
    pub fn recommended_protocols(&self) -> &Protocols {
        &self.recommended
    }
}
impl<T> std::str::FromStr for ParamValues<T>
where
    T: std::str::FromStr,
    T::Err: std::error::Error,
{
    type Err = Error;
695733
    fn from_str(s: &str) -> crate::Result<Self> {
        /// Helper: parse a single K=V pair.
1801438
        fn parse_pair<U>(p: &str) -> crate::Result<(String, U)>
1801438
        where
1801438
            U: std::str::FromStr,
1801438
            U::Err: std::error::Error,
        {
1801438
            let parts: Vec<_> = p.splitn(2, '=').collect();
1801438
            if parts.len() != 2 {
                return Err(EK::BadArgument
                    .at_pos(Pos::at(p))
                    .with_msg("Missing = in key=value list"));
1801438
            }
1801438
            let num = parts[1].parse::<U>().map_err(|e| {
4
                EK::BadArgument
4
                    .at_pos(Pos::at(parts[1]))
4
                    .with_msg(e.to_string())
4
            })?;
1801434
            Ok((parts[0].to_string(), num))
1801438
        }
695733
        let params = s
695733
            .split(' ')
1801444
            .filter(|p| !p.is_empty())
695733
            .map(parse_pair)
4
            .try_collect()?;
695729
        Ok(ParamValues { params })
695733
    }
}
impl FromStr for SharedRandVal {
    type Err = Error;
226
    fn from_str(s: &str) -> crate::Result<Self> {
226
        let val: B64 = s.parse()?;
226
        let val = SharedRandVal(val.into_array()?);
226
        Ok(val)
226
    }
}
impl Display for SharedRandVal {
6
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6
        Display::fmt(&B64::from(Vec::from(self.0)), f)
6
    }
}
impl NormalItemArgument for SharedRandVal {}
impl SharedRandStatus {
    /// Parse a current or previous shared rand value from a given
    /// SharedRandPreviousValue or SharedRandCurrentValue.
3
    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
3
        match item.kwd() {
2
            NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
            _ => {
1
                return Err(Error::from(internal!(
1
                    "wrong keyword {:?} on shared-random value",
1
                    item.kwd()
1
                ))
1
                .at_pos(item.pos()));
            }
        }
2
        let n_reveals: u8 = item.parse_arg(0)?;
2
        let value: SharedRandVal = item.parse_arg(1)?;
        // Added in proposal 342
2
        let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
2
        Ok(SharedRandStatus {
2
            n_reveals,
2
            value,
2
            timestamp,
2
            __non_exhaustive: (),
2
        })
3
    }
    /// Return the actual shared random value.
1272
    pub fn value(&self) -> &SharedRandVal {
1272
        &self.value
1272
    }
    /// Return the timestamp (if any) associated with this `SharedRandValue`.
3498
    pub fn timestamp(&self) -> Option<std::time::SystemTime> {
3498
        self.timestamp.map(|t| t.0)
3498
    }
}
impl DirSource {
    /// Parse a "dir-source" item
22
    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
22
        if item.kwd() != NetstatusKwd::DIR_SOURCE {
            return Err(
                Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
                    .at_pos(item.pos()),
            );
22
        }
22
        let nickname = item
22
            .required_arg(0)?
            .parse()
            .map_err(|e: InvalidNickname| {
                EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
            })?;
22
        let identity = item.parse_arg(1)?;
22
        let hostname = item
22
            .required_arg(2)?
            .parse()
            .map_err(|e: InvalidInternetHost| {
                EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
            })?;
22
        let ip = item.parse_arg(3)?;
22
        let dir_port = item.parse_arg(4)?;
22
        let or_port = item.parse_arg(5)?;
22
        Ok(DirSource {
22
            nickname,
22
            identity,
22
            hostname,
22
            ip,
22
            dir_port,
22
            or_port,
22
            __non_exhaustive: (),
22
        })
22
    }
}
impl ConsensusAuthorityEntry {
    /// Parse a single ConsensusAuthorityEntry from a voter info section.
22
    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusAuthorityEntry> {
        use NetstatusKwd::*;
        // this unwrap should be safe because if there is not at least one
        // token in the section, the section is unparsable.
        #[allow(clippy::unwrap_used)]
22
        let first = sec.first_item().unwrap();
22
        if first.kwd() != DIR_SOURCE {
            return Err(Error::from(internal!(
                "Wrong keyword {:?} at start of voter info",
                first.kwd()
            ))
            .at_pos(first.pos()));
22
        }
22
        let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
22
        let contact = sec.required(CONTACT)?;
        // Ideally we would parse_args_as_str but that requires us to
        // impl From<InvalidContactInfo> for crate::Error which is wrong
        // because many it's a footgun which lets you just write ? here
        // resulting in lack of position information.
        // (This is a general problem with the error handling in crate::parse.)
22
        let contact = contact
22
            .args_as_str()
22
            .parse()
            .map_err(|err: InvalidContactInfo| {
                EK::BadArgument
                    .with_msg(err.to_string())
                    .at_pos(contact.pos())
            })?;
22
        let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16U>(0)?;
22
        Ok(ConsensusAuthorityEntry {
22
            dir_source,
22
            contact,
22
            vote_digest,
22
            __non_exhaustive: (),
22
        })
22
    }
}
impl RelayBandwidthItem {
    /// Return a new `RelayBandwidthItem` containing no information
    ///
    /// As if parsed from a document with no `w` line, discarding unknown information.
1
    pub fn new_no_info() -> Self {
1
        RelayBandwidthItem {
1
            effective: RelayBandwidth::default(),
1
            params: Unknown::new_discard(),
1
        }
1
    }
    /// Return a new `RelayBandwidthItem` containing only the effective bandwidth
    pub fn from_effective(effective: RelayBandwidth) -> Self {
        RelayBandwidthItem {
            effective,
            params: Unknown::new_discard(),
        }
    }
    /// Get the effective relay bandwidth (bandwidth estimate) for path selection.
    ///
    /// Invariant: consistent with from [`params`](RelayBandwidthItem::params),
    /// if `parsed` isn't [`Discarded`](Unknown::Discarded).
    //
    // We open-code this rather than deriving it so we can provide better docs.
    pub fn effective(&self) -> RelayBandwidth {
        self.effective
    }
    /// Get the complete parameter set, if this information is available.
    ///
    /// After parsing, this is the parsed but not interpreted `w` item,
    /// or `None` if the document contained no `w` item.
    //
    // We open-code this rather than deriving it because we want to return
    // `Unknown<&...>` rather than `&Unknown<..>`, which the user would just have to .as_ref().
    pub fn params(&self) -> Unknown<&Option<ParamValues<u32>>> {
        self.params.as_ref()
    }
    /// Parse a routerbandwidth from a "w" line.
43
    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<RelayBandwidthItem> {
43
        if item.kwd() != NetstatusKwd::RS_W {
3
            return Err(
3
                Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
3
                    .at_pos(item.pos()),
3
            );
40
        }
40
        let params = item.args_as_str().parse()?;
        let effective =
39
            RelayBandwidth::from_param_values(&params).map_err(|e| e.at_pos(item.pos()))?;
39
        Ok(RelayBandwidthItem {
39
            effective,
39
            params: Unknown::new_discard(),
39
        })
43
    }
    /// The keyword for parsing and encoding
    const KEYWORD: &str = "w";
}
#[cfg(feature = "retain-unknown")]
impl Default for RelayBandwidthItem {
    fn default() -> Self {
        RelayBandwidthItem {
            effective: RelayBandwidth::default(),
            params: Unknown::Retained(None),
        }
    }
}
impl RelayBandwidth {
    /// Return the value, whether measured or not
24650
    pub fn value(&self) -> u32 {
24650
        match *self {
23904
            RelayBandwidth::Measured(v) => v,
746
            RelayBandwidth::Unmeasured(v) => v,
        }
24650
    }
    /// Return true if this bandwidth is the result of a successful measurement
26346
    pub fn is_measured(&self) -> bool {
26346
        matches!(self, RelayBandwidth::Measured(_))
26346
    }
    /// Return true if this bandwidth is nonzero
24650
    pub fn is_nonzero(&self) -> bool {
24650
        self.value() != 0
24650
    }
    /// Parse a routerbandwidth from partially-parsed `w` line in the form of a `NetParams`
    ///
    /// This function is the common part shared between `parse2` and `parse`.
39
    fn from_param_values(params: &ParamValues<u32>) -> crate::Result<RelayBandwidth> {
39
        params
39
            .try_into()
            .map_err(|e: InvalidRelayBandwidth| EK::BadArgument.with_msg(e.to_string()))
39
    }
}
impl Default for RelayBandwidth {
1
    fn default() -> RelayBandwidth {
1
        RelayBandwidth::Unmeasured(0)
1
    }
}
impl TryFrom<&ParamValues<u32>> for RelayBandwidth {
    type Error = InvalidRelayBandwidth;
597643
    fn try_from(params: &ParamValues<u32>) -> Result<RelayBandwidth, InvalidRelayBandwidth> {
597643
        let bw = params.params.get("Bandwidth");
597643
        let unmeas = params.params.get("Unmeasured");
597643
        let bw = match bw {
1
            None => return Ok(RelayBandwidth::Unmeasured(0)),
597642
            Some(b) => *b,
        };
597642
        match unmeas {
367991
            None | Some(0) => Ok(RelayBandwidth::Measured(bw)),
229651
            Some(1) => Ok(RelayBandwidth::Unmeasured(bw)),
            _ => Err(InvalidRelayBandwidth::InvalidUnmeasured),
        }
597643
    }
}
#[cfg(feature = "retain-unknown")]
impl TryFrom<ParamValues<u32>> for RelayBandwidthItem {
    type Error = InvalidRelayBandwidth;
7526
    fn try_from(params: ParamValues<u32>) -> Result<RelayBandwidthItem, InvalidRelayBandwidth> {
        Ok(RelayBandwidthItem {
7526
            effective: (&params).try_into()?,
7526
            params: Unknown::Retained(Some(params)),
        })
7526
    }
}
/// `parse2` impls for types in this modulea
///
/// Separate module for a separate namespace.
mod parse2_impls {
    use super::*;
    pub(super) use parse2::{
        ArgumentError as AE, ArgumentStream, ErrorProblem as EP, ItemArgumentParseable,
        ItemValueParseable, NetdocParseableFields,
    };
    use std::result::Result;
    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
    impl<T: FromStr + NormalItemArgument> ItemValueParseable for ParamValues<T>
    where
        T::Err: std::error::Error,
    {
681847
        fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
681847
            item.check_no_object()?;
681847
            item.args_copy()
681847
                .into_remaining()
681847
                .parse()
681847
                .map_err(item.invalid_argument_handler("parameters"))
681847
        }
    }
    impl ItemValueParseable for NetParams {
45334
        fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
45334
            let params = ParamValues::from_unparsed(item)?;
45334
            Ok(NetParams { params })
45334
        }
    }
    impl NetdocParseableFields for RelayBandwidthItem {
        type Accumulator = Option<ParamValues<u32>>;
590078
        fn is_item_keyword(kw: KeywordRef) -> bool {
590078
            kw == Self::KEYWORD
590078
        }
590078
        fn accumulate_item(acc: &mut Self::Accumulator, item: UnparsedItem) -> Result<(), EP> {
590078
            if acc.is_some() {
                return Err(EP::ItemRepeated);
590078
            }
590078
            item.check_no_object()?;
590078
            let params = ParamValues::from_unparsed(item)?;
590078
            *acc = Some(params);
590078
            Ok(())
590078
        }
590078
        fn finish(params: Self::Accumulator, items: &ItemStream) -> Result<Self, EP> {
590078
            let effective = params
590078
                .as_ref()
590078
                .map(TryFrom::try_from)
590078
                .transpose()
                .map_err(|_| EP::OtherBadDocument("invalid information in `w` item"))?
                .unwrap_or_default();
590078
            let params = items.parse_options().retain_unknown_values.map(|()| params);
590078
            Ok(RelayBandwidthItem { effective, params })
590078
        }
    }
    impl ItemValueParseable for rs::SoftwareVersion {
590475
        fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
590475
            item.check_no_object()?;
590475
            item.args_mut()
590475
                .into_remaining()
590475
                .parse()
590475
                .map_err(item.invalid_argument_handler("version"))
590475
        }
    }
    impl ItemArgumentParseable for IgnoredPublicationTimeSp {
590078
        fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
1180156
            let mut next_arg = || a.next().ok_or(AE::Missing);
590078
            let _: &str = next_arg()?;
590078
            let _: &str = next_arg()?;
590078
            Ok(IgnoredPublicationTimeSp)
590078
        }
    }
}
/// `encode` impls for types in this modulea
///
/// Separate module for a separate namespace.
mod encode_impls {
    use super::*;
    use std::result::Result;
    pub(crate) use {
        crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodableFields},
        tor_error::Bug,
    };
    impl NetdocEncodableFields for RelayBandwidthItem {
36
        fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
36
            if let Some(w) = self.params.as_ref().into_retained()? {
36
                w.write_item_value_onto(out.item(Self::KEYWORD))?;
            }
36
            Ok(())
36
        }
    }
    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
    impl<T: NormalItemArgument + Ord + Display> ItemValueEncodable for ParamValues<T> {
113
        fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
113
            for (k, v) in self.iter().collect::<BTreeSet<_>>() {
426
                if k.is_empty()
425
                    || k.chars()
4521
                        .any(|c| c.is_whitespace() || c.is_control() || c == '=')
                {
                    // TODO torspec#401 see TODO in ParamValues<T> definition
4
                    return Err(bad_api_usage!(
4
                        "tried to encode NetParms with unreasonable keyword {k:?}"
4
                    ));
422
                }
422
                out.args_raw_string(&format_args!("{k}={v}"));
            }
109
            Ok(())
113
        }
    }
    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
    impl ItemValueEncodable for NetParams {
7
        fn write_item_value_onto(&self, out: ItemEncoder) -> Result<(), Bug> {
7
            self.params.write_item_value_onto(out)
7
        }
    }
    impl ItemValueEncodable for rs::SoftwareVersion {
67
        fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
67
            out.args_raw_string(self);
67
            Ok(())
67
        }
    }
    impl ItemArgument for IgnoredPublicationTimeSp {
36
        fn write_arg_onto(&self, out: &mut ItemEncoder) -> Result<(), Bug> {
36
            out.args_raw_string(&"2000-01-01 00:00:01");
36
            Ok(())
36
        }
    }
}
impl ConsensusFooterFields {
    /// Parse a directory footer from a footer section.
3
    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
        use NetstatusKwd::*;
3
        sec.required(DIRECTORY_FOOTER)?;
3
        let bandwidth_weights = sec
3
            .maybe(BANDWIDTH_WEIGHTS)
3
            .args_as_str()
3
            .unwrap_or("")
3
            .parse()?;
2
        Ok(ConsensusFooterFields {
2
            bandwidth_weights,
2
            __non_exhaustive: (),
2
        })
3
    }
}
/// `ProtoStatuses` parsing and encoding
///
/// Separate module for separate namespace
mod proto_statuses_parse2_encode {
    use super::encode_impls::*;
    use super::parse2_impls::*;
    use super::*;
    use paste::paste;
    use std::result::Result;
    /// Implements `NetdocParseableFields` for `ProtoStatuses`
    ///
    /// We have this macro so that it's impossible to write things like
    /// ```text
    ///      ProtoStatuses {
    ///          client: ProtoStatus {
    ///              recommended: something something recommended_relay_versions something,
    /// ```
    ///
    /// (The structure of `ProtoStatuses` means the normal parse2 derive won't work for it.
    /// Note the bug above: the recommended *relay* version info is put in the *client* field.
    /// Preventing this bug must involve: avoiding writing twice the field name elements,
    /// such as `relay` and `client`, during this kind of construction/conversion.)
    macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
        #[derive(Deftly)]
        #[derive_deftly(NetdocParseableFields)]
        // Only ProtoStatusesParseNetdocParseAccumulator is exposed.
        #[allow(unreachable_pub)]
        pub struct ProtoStatusesParseHelper {
            $(
                #[deftly(netdoc(default))]
                [<$rr _ $cr _protocols>]: Protocols,
            )*
        }
        /// Partially parsed `ProtoStatuses`
        pub use ProtoStatusesParseHelperNetdocParseAccumulator
            as ProtoStatusesNetdocParseAccumulator;
        impl NetdocParseableFields for ProtoStatuses {
            type Accumulator = ProtoStatusesNetdocParseAccumulator;
366054
            fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
366054
                ProtoStatusesParseHelper::is_item_keyword(kw)
366054
            }
182820
            fn accumulate_item(
182820
                acc: &mut Self::Accumulator,
182820
                item: UnparsedItem<'_>,
182820
            ) -> Result<(), EP> {
182820
                ProtoStatusesParseHelper::accumulate_item(acc, item)
182820
            }
45705
            fn finish(acc: Self::Accumulator, items: &ItemStream<'_>) -> Result<Self, EP> {
45705
                let parse = ProtoStatusesParseHelper::finish(acc, items)?;
45705
                let mut out = ProtoStatuses::default();
                $(
45705
                    out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
                )*
45705
                Ok(out)
45705
            }
        }
        impl NetdocEncodableFields for ProtoStatuses {
7
            fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
              $(
7
                self.$cr.$rr.write_item_value_onto(
7
                    out.item(concat!(stringify!($rr), "-", stringify!($cr), "-protocols"))
7
                )?;
              )*
7
                Ok(())
7
            }
        }
    } } }
    impl_proto_statuses! {
        recommended client;
        recommended relay;
        required client;
        required relay;
    }
}
impl Signature {
    /// Parse a Signature from a directory-signature section
7
    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Signature> {
7
        if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
            return Err(Error::from(internal!(
                "Wrong keyword {:?} for directory signature",
                item.kwd()
            ))
            .at_pos(item.pos()));
7
        }
7
        let (digest_algo, id_fp, sk_fp) = if item.n_args() > 2 {
            (
3
                item.required_arg(0)?,
3
                item.required_arg(1)?,
3
                item.required_arg(2)?,
            )
        } else {
            // TODO #2530 digest_algo needs to depend on whether SHA1 was stated
4
            ("sha1", item.required_arg(0)?, item.required_arg(1)?)
        };
7
        let digest_algo = digest_algo.to_string().parse().void_unwrap();
7
        let digest_algo = DigestAlgoInSignature(Some(digest_algo));
7
        let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
7
        let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
7
        let key_ids = AuthCertKeyIds {
7
            id_fingerprint,
7
            sk_fingerprint,
7
        };
7
        let signature = item.obj("SIGNATURE")?;
7
        Ok(Signature {
7
            digest_algo,
7
            key_ids,
7
            signature,
7
            __non_exhaustive: (),
7
        })
7
    }
    /// Return true if this signature has the identity key and signing key
    /// that match a given cert.
4877
    fn matches_cert(&self, cert: &AuthCert) -> bool {
4877
        cert.key_ids() == self.key_ids
4877
    }
    /// If possible, find the right certificate for checking this signature
    /// from among a slice of certificates.
3177
    fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
4877
        certs.iter().find(|&c| self.matches_cert(c))
3177
    }
    /// Find the certificate and assemble the pieces ready for verification
    ///
    /// `None` means precisely that we're missing the authcert.
3158
    fn signature_to_verify<'r>(
3158
        &'r self,
3158
        signed_digest: &'r [u8],
3158
        certs: &'r [AuthCert],
3158
    ) -> Option<ConsensusSignatureToVerify> {
3158
        let cert = self.find_cert(certs)?;
2031
        let key = cert.signing_key();
2031
        Some(ConsensusSignatureToVerify {
2031
            key,
2031
            signed_digest,
2031
            signature: &self.signature,
2031
        })
3158
    }
}
impl EncodeOrd for Signature {
22
    fn encode_cmp(&self, other: &Self) -> std::cmp::Ordering {
44
        let k: for<'s> fn(&'_ Signature) -> (&'_ _, &'_ _) = |s| (&s.key_ids, &s.signature);
22
        Ord::cmp(&k(self), &k(other))
22
    }
}
/// Signature information in a consensus, to be verified
///
/// Used by callers of [`SignatureGroup::verify_general`],
/// to allow verification to be suppressed if all we wanted to know was
/// whether we have enough signatures and enough authcerts.
#[derive(Debug, Clone, Copy)]
struct ConsensusSignatureToVerify<'r> {
    /// KP_auth_sign_rsa
    key: &'r ll::pk::rsa::PublicKey,
    /// The digest (actual RSA signature payload, before PKCS#11 padding)
    signed_digest: &'r [u8],
    /// The RSA signature value
    signature: &'r [u8],
}
/// Token indicating that signature verification has been done, if required
///
/// Prevents accidentally passing an unintended no-op function as
/// `do_verify` to [`SignatureGroup::verify_general`].
///
/// Write `SignatureVerifiedIfIntended {}` to construct this,
/// only in code which has actually done the verification,
/// or code which is deliberately not verifying at all.
pub(crate) struct SignatureVerifiedIfIntended {}
impl<'r> ConsensusSignatureToVerify<'r> {
    /// Verify this signature
    ///
1424
    fn verify(self) -> Result<SignatureVerifiedIfIntended, VerifyFailed> {
1424
        self.key.verify(self.signed_digest, self.signature)?;
1419
        Ok(SignatureVerifiedIfIntended {})
1424
    }
}
/// How `verify_general` should decide who is a trusted authority
///
/// Don't use this for other purposes
#[derive(Debug, Clone, Copy)]
pub(crate) enum VerifyGeneralTrustedAuthorities<'r> {
    /// Trust these authorities.
    TrustThese {
        /// The HKP_auth_id_rsa
        trusted: &'r [RsaIdentity],
    },
    /// Document is a a vote, so OK if signed by any one of the listed authorities
    AnyOneOfThese {
        /// The HKP_auth_id_rsa
        trusted: &'r [RsaIdentity],
    },
    /// For the benefit of `SignatureGroup::validate`, used by the old parser, only
    ///
    /// Every `AuthCert` passed to `verify_general` is a real authority (!)
    /// (But not necessarily a different one!)
    HazardouslyAssumeAllAuthCertsAreReal {
        /// Total number of authorities that we trust
        ///
        /// Used only to calculate the threshold
        n_authorities: usize,
    },
}
/// Return the minimum number of authorities that we need signatures from
///
/// Enough is strictly more than half.
///
/// The returned value is a [`RangeFrom`](std::ops::RangeFrom), ie an inclusive range.
/// Its `start` value is the minimum acceptable number of authorities
/// from whom we have good signatures.
///
/// Should usually be followed by
/// [`.contains`](std::ops::RangeFrom::contains)`(&actual_number)`.
///
/// # Example
///
/// ```
/// use tor_netdoc::{doc::netstatus::consensus_threshold, parse2::VerifyFailed};
/// # fn main() -> Result<(), VerifyFailed> {
///
/// let n_trusted_authorities = 3;
/// let n_good_signatures_from_different_authorities = 2;
///
/// if consensus_threshold(n_trusted_authorities)
///      .contains(&n_good_signatures_from_different_authorities)
/// {
///     Ok(())
/// } else {
///     Err(VerifyFailed::InsufficientTrustedSigners)
/// }
/// # }
/// ```
1102
pub fn consensus_threshold(n_authorities: usize) -> std::ops::RangeFrom<usize> {
1102
    (n_authorities / 2) + 1 // strict majority
1102
        ..
1102
}
impl SignatureGroup {
    // TODO: these functions are pretty similar and could probably stand to be
    // refactored a lot.
    /// Helper: Return a pair of the number of possible authorities'
    /// signatures in this object for which we _could_ find certs, and
    /// a list of the signatures we couldn't find certificates for.
6
    fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
6
        let mut ok: HashSet<RsaIdentity> = HashSet::new();
6
        let mut missing = Vec::new();
6
        for sig in &self.signatures {
19
            let id_fingerprint = &sig.key_ids.id_fingerprint;
19
            if ok.contains(id_fingerprint) {
                continue;
19
            }
19
            if sig.find_cert(certs).is_some() {
12
                ok.insert(*id_fingerprint);
12
                continue;
7
            }
7
            missing.push(sig);
        }
6
        (ok.len(), missing)
6
    }
    /// Given a list of authority identity key fingerprints, return true if
    /// this signature group is _potentially_ well-signed according to those
    /// authorities.
5
    fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
5
        let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
5
        for sig in &self.signatures {
17
            let id_fp = &sig.key_ids.id_fingerprint;
17
            if signed_by.contains(id_fp) {
                // Already found this in the list.
                continue;
17
            }
17
            if authorities.contains(&id_fp) {
9
                signed_by.insert(*id_fp);
8
            }
        }
5
        consensus_threshold(authorities.len()).contains(&signed_by.len())
5
    }
    /// Return true if the signature group defines a valid signature.
    ///
    /// A signature is valid if it signed by more than half of the
    /// authorities.  This API requires that `n_authorities` is the number of
    /// authorities we believe in, and that every cert in `certs` belongs
    /// to a real authority.
3
    fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> Result<(), VerifyFailed> {
        // TODO we ought to take the set of trusted authorities as an argument,
        // rather than use VGTA::HazardouslyAssumeAllAuthCertsAreReal.
3
        self.verify_general(
3
            VerifyGeneralTrustedAuthorities::HazardouslyAssumeAllAuthCertsAreReal { n_authorities },
3
            certs,
8
            |tv| tv.verify(),
        )
3
    }
    /// Check signatures (maybe), but not timeliness
    ///
    /// Examines the signatures and collates them with authcerts.
    /// Performs the necessary consensus signature verifications, via `do_verify`.
    ///
    /// If there are not enough authcerts or not enough signatures,
    /// throws a `ConsensusVerifiabilityError`.
    ///
    /// Differs from [`SignatureGroup::validate`]:
    ///
    ///  * Intended also for use with types from parse2.
    ///
    ///  * Yields information about missing authcerts directly in the return value,
    ///    and can be used without actually doing the verification,
    ///    so there's no need for a separate "which certs are we missing" function.
    ///
    ///  * Threshold is passed as a parameter (wanted for votes).
    ///
    ///  * Ability to check authority identities, by passing `trusted_authorities`.
    ///    (done with `authorities_are_correct` in old parser,
    ///    apparently with no engineered safeguard against consensus user omitting to do so).
    ///
    ///    **If `trusted_authorities` is None, all authorities in `certs` are treated as trusted**.
    ///
    ///  * Returns `Result`, not a boolean
    ///
    ///  * We prefer the term `verify` to `validate`.  All this does is signature verification.
    ///
1091
    fn verify_general<E>(
1091
        &self,
1091
        trusted_authorities: VerifyGeneralTrustedAuthorities,
1091
        certs: &[AuthCert],
1091
        do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
1091
    ) -> Result<(), E>
1091
    where
1091
        ConsensusVerifiabilityError: Into<E>,
    {
        use VerifyGeneralTrustedAuthorities as TA;
        // A set of the authorities (by identity) who have have signed
        // this document.  We use a set here in case `certs` has more
        // than one certificate for a single authority.
1091
        let mut ok: HashSet<RsaIdentity> = HashSet::new();
1091
        let mut missing = HashSet::new();
1091
        let mut verify_failed = Ok(());
1091
        for sig in &self.signatures {
            // Exhaustive pattern makes it hard to accidentally ignore a field.
            let Signature {
                digest_algo,
                key_ids:
                    AuthCertKeyIds {
                        id_fingerprint,
                        // h_kp_auth_sign_rsa, which Signature::check_signature
                        // checks against the authcert.
                        sk_fingerprint: _,
                    },
                // Used by Signature::check_signature
                signature: _,
                __non_exhaustive: (),
3908
            } = sig;
3908
            match trusted_authorities {
                TA::TrustThese { trusted } | TA::AnyOneOfThese { trusted } => {
3898
                    if !trusted.contains(id_fingerprint) {
750
                        continue;
3148
                    }
                }
10
                TA::HazardouslyAssumeAllAuthCertsAreReal { .. } => {
10
                    // OK then!
10
                }
            }
3158
            if ok.contains(id_fingerprint) {
                // We already checked at least one signature using this
                // authority's identity fingerprint.
                continue;
3158
            }
3158
            let Some(d) = self.hashes.hash_slice(digest_algo) else {
                // We don't support this kind of digest for this kind
                // of document.
                continue;
            };
3158
            let Some(tv) = sig.signature_to_verify(d, certs) else {
1127
                missing.insert(sig.key_ids);
1127
                continue;
            };
2031
            match do_verify(tv) {
                Ok::<SignatureVerifiedIfIntended, _>(_) => {
2026
                    ok.insert(*id_fingerprint);
                }
                Err(e) => {
5
                    verify_failed = Err(e);
                }
            }
        }
1091
        let n_authorities = match trusted_authorities {
1082
            TA::TrustThese { trusted } => trusted.len(),
3
            TA::HazardouslyAssumeAllAuthCertsAreReal { n_authorities: n } => n,
            TA::AnyOneOfThese { .. } => {
                // strict majority of 1 is 1, so n_authorites being 1 leads to threshold of 1
                // (doing it this way avoids having both thresholds and authority counts
                // in the same code area, which might lead to confusing one with the other.
6
                1
            }
        };
1091
        let threshold = consensus_threshold(n_authorities);
1091
        if threshold.contains(&ok.len()) {
545
            Ok(())
        } else {
            // Throw the verification error if any of the verifications failed
546
            verify_failed?;
            // Otherwise report that we're missing certs and/or signers
543
            Err(if missing.is_empty() {
114
                ConsensusVerifiabilityError::InsufficientTrustedSigners
            } else {
429
                let deficit = threshold.start - ok.len();
429
                ConsensusVerifiabilityError::MissingAuthCerts { missing, deficit }
            }
            .into())
        }
1091
    }
}
impl From<ConsensusVerifiabilityError> for VerifyFailed {
1
    fn from(cve: ConsensusVerifiabilityError) -> VerifyFailed {
        use ConsensusVerifiabilityError as CVE;
        use VerifyFailed as VF;
1
        match cve {
            CVE::InsufficientTrustedSigners => VF::InsufficientTrustedSigners,
1
            CVE::MissingAuthCerts { .. } => VF::InsufficientTrustedSigners,
        }
1
    }
}
impl From<ConsensusVerifyFailed> for VerifyFailed {
53
    fn from(cvf: ConsensusVerifyFailed) -> VerifyFailed {
        use ConsensusVerifyFailed as CVF;
        use VerifyFailed as VF;
53
        match cvf {
53
            CVF::CertificationInsufficient { .. } => VF::InsufficientTrustedSigners,
            CVF::InvalidSignature { .. } => VF::VerifyFailed,
        }
53
    }
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;
    use crate::doc::authcert::AuthCertUnverified;
    use crate::encode::{NetdocEncodable, NetdocEncodableFields};
    use crate::parse2::{ParseInput, parse_netdoc, parse_netdoc_multiple};
    use crate::test_support::{raw_find_item_rhs, regsub};
    use anyhow::Context as _;
    use assert_matches::assert_matches;
    use hex_literal::hex;
    use humantime::parse_rfc3339;
    use std::fmt::Debug;
    use std::fs;
    use std::time::Duration;
    use tor_checkable::TimeBound;
    const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
    const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
    const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
    const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
    fn read_bad(fname: &str) -> String {
        use std::fs;
        use std::path::PathBuf;
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("testdata");
        path.push("bad-mdconsensus");
        path.push(fname);
        fs::read_to_string(path).unwrap()
    }
    #[test]
    fn parse_and_validate_md() -> crate::Result<()> {
        use std::net::SocketAddr;
        use tor_checkable::{SelfSigned, TimeBound};
        let mut certs = Vec::new();
        for cert in AuthCert::parse_multiple(CERTS)? {
            let cert = cert?.check_signature()?.dangerously_assume_timely();
            certs.push(cert);
        }
        let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
        assert_eq!(certs.len(), 3);
        let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
        let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
        // The set of authorities we know _could_ validate this cert.
        assert!(consensus.authorities_are_correct(&auth_ids));
        // A subset would also work.
        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
        {
            // If we only believe in an authority that isn't listed,
            // that won't work.
            let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
            assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
        }
        let missing = consensus.key_is_correct(&[]).err().unwrap();
        assert_eq!(3, missing.len());
        assert!(consensus.key_is_correct(&certs).is_ok());
        let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
        assert_eq!(2, missing.len());
        // here is a trick that had better not work.
        let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
        let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
        assert_eq!(2, missing.len());
        assert!(consensus.is_well_signed(&same_three_times).is_err());
        assert!(consensus.key_is_correct(&certs).is_ok());
        let consensus = consensus.check_signature(&certs)?;
        assert_eq!(6, consensus.relays().len());
        let r0 = &consensus.relays()[0];
        assert_eq!(
            r0.md_digest(),
            &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
        );
        assert_eq!(
            r0.rsa_identity().as_bytes(),
            &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
        );
        assert!(!r0.bandwidth().is_measured());
        assert!(!r0.bandwidth().is_nonzero());
        let pv = &r0.protovers();
        assert!(pv.supports_subver("HSDir", 2));
        assert!(!pv.supports_subver("HSDir", 3));
        let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
        let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
        assert!(r0.addrs().any(|a| a == ip4));
        assert!(r0.addrs().any(|a| a == ip6));
        Ok(())
    }
    #[test]
    fn parse_and_validate_ns() -> crate::Result<()> {
        use tor_checkable::{SelfSigned, TimeBound};
        let mut certs = Vec::new();
        for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
            let cert = cert?.check_signature()?.dangerously_assume_timely();
            certs.push(cert);
        }
        let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
        assert_eq!(certs.len(), 4);
        let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
        let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
        // The set of authorities we know _could_ validate this cert.
        assert!(consensus.authorities_are_correct(&auth_ids));
        // A subset would also work.
        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
        assert!(consensus.key_is_correct(&certs).is_ok());
        let _consensus = consensus.check_signature(&certs)?;
        Ok(())
    }
    #[test]
    fn test_bad() {
        use crate::Pos;
        fn check(fname: &str, e: &Error) {
            let content = read_bad(fname);
            let res = MdConsensus::parse(&content);
            assert!(res.is_err());
            assert_eq!(&res.err().unwrap(), e);
        }
        check(
            "bad-flags",
            &EK::BadArgument
                .at_pos(Pos::from_line(27, 1))
                .with_msg("Flags out of order"),
        );
        check(
            "bad-md-digest",
            &EK::BadArgument
                .at_pos(Pos::from_line(40, 3))
                .with_msg("Invalid base64"),
        );
        check(
            "bad-weight",
            &EK::BadArgument
                .at_pos(Pos::from_line(67, 141))
                .with_msg("invalid digit found in string"),
        );
        check(
            "bad-weights",
            &EK::BadArgument
                .at_pos(Pos::from_line(51, 13))
                .with_msg("invalid digit found in string"),
        );
        check(
            "wrong-order",
            &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
        );
        check(
            "wrong-start",
            &EK::UnexpectedToken
                .with_msg("vote-status")
                .at_pos(Pos::from_line(1, 1)),
        );
        check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
    }
    fn gettok(s: &str) -> crate::Result<Item<'_, NetstatusKwd>> {
        let mut reader = NetDocReader::new(s)?;
        let tok = reader.next().unwrap();
        assert!(reader.next().is_none());
        tok
    }
    #[test]
    fn test_weight() {
        let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
        let w = RelayBandwidthItem::from_item(&w).unwrap();
        assert!(!w.effective.is_measured());
        assert!(w.effective.is_nonzero());
        let w = gettok("w Bandwidth=10\n").unwrap();
        let w = RelayBandwidthItem::from_item(&w).unwrap();
        assert!(w.effective.is_measured());
        assert!(w.effective.is_nonzero());
        let w = RelayBandwidthItem::new_no_info();
        assert!(!w.effective.is_measured());
        assert!(!w.effective.is_nonzero());
        let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
        let w = RelayBandwidthItem::from_item(&w).unwrap();
        assert!(!w.effective.is_measured());
        assert!(!w.effective.is_nonzero());
        let w = gettok("r foo\n").unwrap();
        let w = RelayBandwidthItem::from_item(&w);
        assert!(w.is_err());
        let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
        let w = RelayBandwidthItem::from_item(&w);
        assert!(w.is_err());
        let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
        let w = RelayBandwidthItem::from_item(&w);
        assert!(w.is_err());
    }
    #[test]
    fn test_netparam() {
        let p = "Hello=600 Goodbye=5 Fred=7"
            .parse::<ParamValues<u32>>()
            .unwrap();
        assert_eq!(p.get("Hello"), Some(&600_u32));
        let p = "Hello=Goodbye=5 Fred=7".parse::<ParamValues<u32>>();
        assert!(p.is_err());
        let p = "Hello=Goodbye Fred=7".parse::<ParamValues<u32>>();
        assert!(p.is_err());
        for bad_kw in ["What=The", "", "\n", "\0"] {
            let p = [(bad_kw, 42)].into_iter().collect::<ParamValues<i32>>();
            let mut d = NetdocEncoder::new();
            let d = (|| {
                let i = d.item("bad-psrams");
                p.write_item_value_onto(i)?;
                d.finish()
            })();
            let _: tor_error::Bug = d.expect_err(bad_kw);
        }
    }
    #[test]
    fn test_sharedrand() {
        let sr =
            gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
                .unwrap();
        let sr = SharedRandStatus::from_item(&sr).unwrap();
        assert_eq!(sr.n_reveals, 9);
        assert_eq!(
            sr.value.0,
            hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
        );
        assert!(sr.timestamp.is_none());
        let sr2 = gettok(
            "shared-rand-current-value 9 \
                    5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
        )
        .unwrap();
        let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
        assert_eq!(sr2.n_reveals, sr.n_reveals);
        assert_eq!(sr2.value.0, sr.value.0);
        assert_eq!(
            sr2.timestamp.unwrap().0,
            humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
        );
        let sr = gettok("foo bar\n").unwrap();
        let sr = SharedRandStatus::from_item(&sr);
        assert!(sr.is_err());
    }
    #[test]
    fn test_protostatus() {
        let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
        let outcome = ProtoStatus {
            recommended: "Link=7".parse().unwrap(),
            required: "Desc=5".parse().unwrap(),
            __non_exhaustive: (),
        }
        .check_protocols(&my_protocols);
        assert!(outcome.is_ok());
        let outcome = ProtoStatus {
            recommended: "Microdesc=4 Link=7".parse().unwrap(),
            required: "Desc=5".parse().unwrap(),
            __non_exhaustive: (),
        }
        .check_protocols(&my_protocols);
        assert_eq!(
            outcome,
            Err(ProtocolSupportError::MissingRecommended(
                "Microdesc=4".parse().unwrap()
            ))
        );
        let outcome = ProtoStatus {
            recommended: "Microdesc=4 Link=7".parse().unwrap(),
            required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
            __non_exhaustive: (),
        }
        .check_protocols(&my_protocols);
        assert_eq!(
            outcome,
            Err(ProtocolSupportError::MissingRequired(
                "Cons=6-12 Wombat=15".parse().unwrap()
            ))
        );
    }
    #[test]
    fn serialize_protostatus() {
        let ps = ProtoStatuses {
            client: ProtoStatus {
                recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
                required: "Link=5 LinkAuth=3".parse().unwrap(),
                __non_exhaustive: (),
            },
            relay: ProtoStatus {
                recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
                required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
                __non_exhaustive: (),
            },
            __non_exhaustive: (),
        };
        let json = serde_json::to_string(&ps).unwrap();
        let ps2 = serde_json::from_str(json.as_str()).unwrap();
        assert_eq!(ps, ps2);
        let ps3: ProtoStatuses = serde_json::from_str(
            r#"{
            "client":{
                "required":"Link=5 LinkAuth=3",
                "recommended":"Link=1-5 LinkAuth=2-5"
            },
            "relay":{
                "required":"Wombat=20-22 Knish=25-27",
                "recommended":"Wombat=20-30 Knish=20-30"
            }
        }"#,
        )
        .unwrap();
        assert_eq!(ps, ps3);
    }
    // consensuses are done in each_flavor.rs: see verify_error_netstatus
    #[test]
    fn verify_error_netstatus_vote() -> Result<(), anyhow::Error> {
        use VerifyFailed as VF;
        use VoteVerifyFailed as VVF;
        use vote::NetworkStatusUnverified as UV;
        let file = "testdata2/v3-status-votes--1";
        let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
        let input = ParseInput::new(&text, file);
        let doc: UV = parse_netdoc(&input)?;
        let trusted = || VoteVerifier::new([doc.peek_alleged_authority()]);
        let edit_body = |f: &dyn Fn(&mut _)| {
            let (mut body, sigs) = doc.clone().unwrap_unverified();
            f(&mut body);
            UV::from_parts(body, sigs)
        };
        // sabotage the overall signature
        {
            let mut doc = doc.clone();
            doc.sigs.sigs.directory_signature.signature.fill(0xff);
            assert_matches!(
                doc.verify(&mut trusted()),
                Err(VVF::InvalidSignature(VF::VerifyFailed))
            );
        }
        // wrong authority
        {
            let doc = doc.clone();
            assert_matches!(
                doc.verify(&mut VoteVerifier::new([[0x55; _].into()])),
                Err(VVF::InvalidSignature(VF::InsufficientTrustedSigners))
            );
        }
        // authcert is for a different authority
        {
            let doc = edit_body(&|body| {
                body.authority.authority.dir_source.identity.0 = [0x55; _].into();
            });
            assert_matches!(
                //
                doc.verify(&mut trusted()),
                Err(VVF::AuthCertWrongAuthority)
            );
        }
        // authcert is from a different time
        let with_mutated_lifetime = |f: &dyn Fn(&mut Lifetime)| {
            let doc = edit_body(&|body| f(&mut body.preamble.lifetime));
            assert_matches!(
                //
                doc.verify(&mut trusted()),
                Err(VVF::AuthCertWrongValidity(_))
            );
        };
        let t_past = parse_rfc3339("1990-01-01T00:02:25Z")?;
        let t_future = parse_rfc3339("2010-01-01T00:02:25Z")?;
        with_mutated_lifetime(&|lifetime| lifetime.valid_after.0 = t_future);
        with_mutated_lifetime(&|lifetime| lifetime.fresh_until.0 = t_past);
        with_mutated_lifetime(&|lifetime| lifetime.valid_until.0 = t_past);
        // syntactically invalid authcert
        {
            let mut text = text.clone();
            regsub(&mut text, "^dir-key-expires ", "dir-key-expires-SABOTAGED ");
            let input = ParseInput::new(&text, file);
            let doc: UV = parse_netdoc(&input)?;
            assert_matches!(
                //
                doc.verify(&mut trusted()),
                Err(VVF::AuthCertParseError(..))
            );
        }
        // duplicate authorities
        {
            let mut trusted = trusted();
            assert_matches!(
                //
                doc.clone().verify(&mut trusted),
                Ok(_)
            );
            assert_matches!(
                doc.clone().verify(&mut trusted),
                Err(VVF::DuplicateAuthority(_))
            );
        }
        Ok(())
    }
    #[cfg(feature = "retain-unknown")]
    #[allow(clippy::type_complexity)]
    pub(super) fn prep_netstatus_verify<UV: NetdocParseable>(
        file: &str,
    ) -> anyhow::Result<(UV, String, Vec<AuthCert>, Vec<RsaIdentity>, SystemTime)> {
        let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
        let now = *raw_find_item_rhs(
            include_str!("../../testdata2/cached-microdesc-consensus"),
            "valid-after",
        )
        .parse::<Iso8601TimeSp>()
        .unwrap()
            + Duration::from_secs(1);
        let input = ParseInput::new(&text, file).retain_unknown_values();
        let doc: UV = parse_netdoc(&input)?;
        let certs = {
            let file = "testdata2/cached-certs";
            let text = fs::read_to_string(file)?;
            let input = ParseInput::new(&text, file);
            let certs: Vec<AuthCertUnverified> = parse_netdoc_multiple(&input)?;
            certs
                .into_iter()
                .map(|cert| cert.verify_selfcert(now))
                .collect::<Result<Vec<AuthCert>, _>>()?
        };
        let authorities = certs.iter().map(|cert| *cert.fingerprint).collect_vec();
        Ok((doc, text, certs, authorities, now))
    }
    /// Check that a network document can be parsed and regenerated, mostly identically
    ///
    /// The regenerated encoded form doesn't need to be 100% identical:
    /// it is compared with a *munged* version of the the original input file,
    /// to cope with differences between C Tor and Arti.
    ///
    /// The mungings are:
    ///
    ///  * Some fields' syntax are adjusted, where C Tor and Arti disagree
    ///    in all kinds of network document.
    ///
    ///  * Document-specific, [`MungeForRoundtrip::adjust_exp`]
    #[cfg(feature = "retain-unknown")]
    fn roundtrip_netstatus<UV, V, VE>(
        // TODO DIRAUTH use include_str!, so, at call sites
        // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4121#note_3428675
        file: &str,
        verify: impl FnOnce(UV, &[RsaIdentity], &[AuthCert]) -> Result<TimeRangeBound<V>, VE>,
        adjust_now: Duration,
    ) -> anyhow::Result<()>
    where
        UV: NetdocParseable + NetdocParseableUnverified + MungeForRoundtrip,
        UV::Signatures: Clone + Debug + NetdocEncodableFields,
        VE: Debug + std::error::Error + Send + Sync + 'static,
        V: Debug + NetdocEncodable,
    {
        let (doc, text, certs, authorities, now) = prep_netstatus_verify::<UV>(file)?;
        let now = now + adjust_now;
        let sigs = doc.inspect_unverified().1.sigs.clone();
        let doc = verify(doc, &authorities, &certs)?.if_valid_at(&now)?;
        println!("{doc:#?}");
        let mut enc = NetdocEncoder::new();
        doc.encode_unsigned(&mut enc)?;
        sigs.encode_fields(&mut enc)?;
        let enc = enc.finish()?;
        let mut exp: String = text.clone();
        // TODO DIRAUTH torspec!507 C Tor emits padded base64 in shared-rand-* items.
        regsub(
            //
            &mut exp,
            r#"^(shared-rand-.*)$"#,
            |c: &regex::Captures| {
                let mut s = c[1].to_owned();
                regsub(&mut s, r#"="#, "");
                s
            },
        );
        // We don't manage proper numerical sorting of version numbers.
        // Doing so is awkward.  See the (2nd) TODO on RecommendedTorVersions.
        regsub(
            //
            &mut exp,
            r#"^(client|server)-versions (.+)$"#,
            |c: &regex::Captures| -> String {
                format!(
                    "{}-versions {}",
                    &c[1],
                    iter_join(",", c[2].split(',').sorted()),
                )
            },
        );
        let mut regsub = |re, repl| regsub(&mut exp, re, repl);
        // C Tor writes empty versions lines with trailing space
        regsub(
            //
            r#"^((?:client|server)-versions) $"#,
            "$1",
        );
        // C Tor sometimes writes `shared-rand-commit` with trailing space
        regsub(
            //
            r#"^(shared-rand-commit .*) $"#,
            "$1",
        );
        // C Tor emits `m` in varying places: after `a` in votes,
        // and at the end of each routerstatus in md consensuses.
        // We emit it at the start of each routerstatus, right after `r`.
        regsub(
            r#"(?x)
                   ( ^    r\ .* \n     )  #  ( r  )  $1, part before where we want to put m's
                   ( (?:     .* \n )*? )  #  (.*? )  $2, the rest, before the m's
                   ( (?:  m\ .* \n )+  )  #  ( m+ )  $3, one or more m's
            "#,
            r#"$1$3$2"#,
        );
        UV::adjust_exp(&mut exp);
        assert_eq_or_diff!(&exp, &enc);
        Ok(())
    }
    trait MungeForRoundtrip {
        /// Munge `s` so that it resembles the output of C Tor
        fn adjust_exp(exp: &mut String);
    }
    /// Test that we can re-encode the consensus we parsed, and that we get the same thing back.
    ///
    /// Well, roughly the same thing.
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn roundtrip_netstatus_plain() -> anyhow::Result<()> {
        roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
            "testdata2/cached-consensus",
            plain::NetworkStatusUnverified::verify,
            Duration::ZERO,
        )
    }
    impl MungeForRoundtrip for plain::NetworkStatusUnverified {
        fn adjust_exp(exp: &mut String) {
            let mut regsub = |re, repl| regsub(exp, re, repl);
            // We emit the optional `ns`
            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:network-status-version
            regsub(
                r#"^network-status-version 3$"#,
                "network-status-version 3 ns",
            );
            // C Tor writes nontrivial values for `publication` in rs `r` items,
            // but we use a fixed string.
            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:r
            regsub(
                r#"^(r \S+ \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
                "$1 2000-01-01 00:00:01",
            );
        }
    }
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn roundtrip_netstatus_md() -> anyhow::Result<()> {
        roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
            "testdata2/cached-microdesc-consensus",
            md::NetworkStatusUnverified::verify,
            Duration::ZERO,
        )
    }
    impl MungeForRoundtrip for md::NetworkStatusUnverified {
        fn adjust_exp(exp: &mut String) {
            let mut regsub = |re, repl| regsub(exp, re, repl);
            // C Tor writes nontrivial values for `publication` in rs `r` items,
            // but we use a fixed string.
            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:r
            //
            // Not the same as in plain consensus: one fewer fields!
            regsub(
                r#"^(r \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
                "$1 2000-01-01 00:00:01",
            );
        }
    }
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn roundtrip_netstatus_vote() -> anyhow::Result<()> {
        roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
            "testdata2/v3-status-votes--1",
            |doc, trusted, _| {
                vote::NetworkStatusUnverified::verify(
                    doc,
                    &mut VoteVerifier::new(trusted.iter().copied()),
                )
            },
            Duration::from_secs(20),
        )
    }
    impl MungeForRoundtrip for vote::NetworkStatusUnverified {
        fn adjust_exp(exp: &mut String) {
            // C Tor writes items in consensuses a different order to in votes!
            // C Tor writes different stats items with different floating point formats!
            let stats_massage_entry = |e: &str| {
                let mut e = e.to_owned();
                if e.contains('.') {
                    regsub(
                        &mut e,
                        // strip trailing 0's and then trailing `.`
                        r#"(?x)^ ( (?:wfu) = [0-9.]*? )( \.? 0+ ) $"#,
                        "$1",
                    );
                }
                e
            };
            // C Tor writes stats items in votes in an apparently arbitrarily chosen order
            regsub(exp, r#"^stats (.+)$"#, |c: &regex::Captures| -> String {
                format!(
                    "stats {}",
                    iter_join(" ", c[1].split(' ').sorted().map(stats_massage_entry)),
                )
            });
            let mut regsub = |re: &_, repl| regsub(exp, re, repl);
            // C Tor writes *-protocols in an apparently arbitrarily chosen order
            regsub(
                r#"(?x)
                       ^ (recommended-relay-protocols\ .*)  \n
                         (recommended-client-protocols\ .*) \n
                         (required-relay-protocols\ .*)     \n
                         (required-client-protocols\ .*)    \n
                         (known-flags .*)$                  \n
                    "#,
                r#"$5
$2
$1
$4
$3
"#,
            );
            // C Tor emits empty `client-versions` in consensuses, but not in votes.
            // (See also the fixup in `roundtrip_netstatus`, which relates to the *syntax*)
            //
            // Some of our inputs (eg the testdata2 votes) don't contain meaningful
            // info, so to make the C Tor output match our output, add them.
            regsub(
                r#"(?x) ^ (voting-delay\ .*) \n
                          (known-flags\ .*) \n"#,
                "$1
client-versions
server-versions
$2
",
            );
            //#                         (?:  a\ .* \n )?    )   #    a? )           we want to put m's
            for missing_field in [
                "bandwidth-file-headers", // TODO DIRAUTH implement
                "bandwidth-file-digest",  // TODO DIRAUTH implement
                "flag-thresholds",        // TODO DIRAUTH implement
            ] {
                regsub(&format!(r#"^{missing_field} .*\n"#), "");
            }
        }
    }
    fn testdata_live(f: &str) -> String {
        // We implement an overrideable *prefix* rather than suffix, here,
        // so that we can access the files in a totally different directory.
        // (This is helpful with nailing-cargo, amongst other things.)
        let var = "TOR_NETDOC_TESTDATA_LIVE_PREFIX";
        let prefix = std::env::var_os(var)
            .map(|s| s.into_string().expect(var))
            .unwrap_or_else(|| "testdata-live/".into());
        format!("{prefix}{f}")
    }
    #[allow(clippy::unnecessary_wraps)] // signature needs to match for roundtrip_netstatus
    fn unwrap_unverified_for_test<UV: NetdocParseableUnverified>(
        uv: UV,
        _ids: &[RsaIdentity],
        _certs: &[AuthCert],
    ) -> Result<TimeRangeBound<UV::Body>, std::convert::Infallible> {
        Ok(TimeRangeBound::new(uv.unwrap_unverified().0, ..))
    }
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn roundtrip_live_plain() -> anyhow::Result<()> {
        roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
            &testdata_live("consensus"),
            unwrap_unverified_for_test,
            Duration::ZERO,
        )
    }
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn roundtrip_live_md() -> anyhow::Result<()> {
        roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
            &testdata_live("consensus-microdesc"),
            unwrap_unverified_for_test,
            Duration::ZERO,
        )
    }
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn roundtrip_live_vote() -> anyhow::Result<()> {
        roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
            &testdata_live("authority"),
            unwrap_unverified_for_test,
            Duration::ZERO,
        )
    }
    #[cfg(feature = "retain-unknown")]
    #[test]
    fn sign_vote() -> anyhow::Result<()> {
        use crate::{
            encode::{encode_netdoc_fields, encode_netdoc_unsigned},
            test_support, testdata2,
        };
        use tor_llcrypto::pk::rsa;
        let authcert = parse_netdoc::<AuthCertUnverified>(
            &ParseInput::new(testdata2::keys::AUTHORITY_CERTIFICATE, "authcert")
                .retain_unknown_values(),
        )?;
        let authcert = authcert.unwrap_unverified().0;
        let authority_id = authcert.fingerprint;
        let doc = test_support::find_vote_by_authority_id(
            &ParseInput::new(testdata2::V3_STATUS_VOTES, "v3-status-votes").retain_unknown_values(),
            *authority_id,
        )
        .0
        .unwrap_unverified()
        .0;
        let body = encode_netdoc_unsigned([&doc])?;
        let sk =
            rsa::KeyPair::from_der(pem::parse(testdata2::keys::AUTHORITY_SIGNING_KEY)?.contents())
                .unwrap();
        for hash_algo in [
            DirectorySignatureHashAlgo::Sha1,
            DirectorySignatureHashAlgo::Sha256,
        ] {
            let directory_signature =
                Signature::sign_text(&sk, &body, hash_algo, authcert.key_ids())?;
            let sig = encode_netdoc_fields(&vote::NetworkStatusSignatures {
                directory_signature,
                __non_exhaustive: (),
            })?;
            let signed = body.clone() + &sig;
            let _: vote::NetworkStatus = parse_netdoc::<vote::NetworkStatusUnverified>(
                &ParseInput::new(&signed, "<signed>"),
            )?
            .verify(&mut VoteVerifier::new([*authority_id]))?
            .dangerously_assume_timely();
        }
        Ok(())
    }
}