1
//! consensus documents - items that vary by consensus flavor
2
//!
3
//! **This file is reincluded multiple times**,
4
//! by the macros in [`crate::doc::ns_variety_definition_macros`],
5
//! once for votes, and once for each consensus flavour.
6
//! It is *not* a module `crate::doc::netstatus::rs::each_flavor`.
7
//!
8
//! Each time this file is included by one of the macros mentioned above,
9
//! the `ns_***` macros (such as `ns_const_name!`) may expand to different values.
10
//!
11
//! See [`crate::doc::ns_variety_definition_macros`].
12

            
13
use super::*;
14

            
15
ns_use_this_variety! {
16
    use [crate::doc::netstatus::rs]::?::{RouterStatus};
17
}
18
#[cfg(feature = "build_docs")]
19
ns_use_this_variety! {
20
    pub(crate) use [crate::doc::netstatus::build]::?::{ConsensusBuilder};
21
    pub use [crate::doc::netstatus::rs::build]::?::{RouterStatusBuilder};
22
}
23

            
24
/// A single consensus netstatus, as produced by the old parser.
25
#[derive(Debug, Clone)]
26
#[non_exhaustive]
27
pub struct Consensus {
28
    /// What kind of consensus document is this?  Absent in votes and
29
    /// in ns-flavored consensuses.
30
    pub flavor: ConsensusFlavor,
31
    /// The preamble, except for the intro item.
32
    pub preamble: Preamble,
33
    /// List of voters whose votes contributed to this consensus.
34
    pub voters: Vec<ConsensusAuthorityEntry>,
35
    /// A list of routerstatus entries for the relays on the network,
36
    /// with one entry per relay.
37
    ///
38
    /// These are currently ordered by the router's RSA identity, but this is not
39
    /// to be relied on, since we may want to even abolish RSA at some point!
40
    pub relays: Vec<RouterStatus>,
41
    /// Footer for the consensus object.
42
    pub footer: ConsensusFooterFields,
43
}
44

            
45
impl Consensus {
46
    /// Return the Lifetime for this consensus.
47
69825
    pub fn lifetime(&self) -> &Lifetime {
48
69825
        &self.preamble.lifetime
49
69825
    }
50

            
51
    /// Return a slice of all the routerstatus entries in this consensus.
52
68024009
    pub fn relays(&self) -> &[RouterStatus] {
53
68024009
        &self.relays[..]
54
68024009
    }
55

            
56
    /// Return a mapping from keywords to integers representing how
57
    /// to weight different kinds of relays in different path positions.
58
11172
    pub fn bandwidth_weights(&self) -> &NetParams<i32> {
59
11172
        &self.footer.bandwidth_weights
60
11172
    }
61

            
62
    /// Return the map of network parameters that this consensus advertises.
63
11221
    pub fn params(&self) -> &NetParams<i32> {
64
11221
        &self.preamble.params
65
11221
    }
66

            
67
    /// Return the latest shared random value, if the consensus
68
    /// contains one.
69
44639
    pub fn shared_rand_cur(&self) -> Option<&SharedRandStatus> {
70
44639
        self.preamble.shared_rand.shared_rand_current_value.as_ref()
71
44639
    }
72

            
73
    /// Return the previous shared random value, if the consensus
74
    /// contains one.
75
44639
    pub fn shared_rand_prev(&self) -> Option<&SharedRandStatus> {
76
44639
        self.preamble.shared_rand.shared_rand_previous_value.as_ref()
77
44639
    }
78

            
79
    /// Return a [`ProtoStatus`] that lists the network's current requirements and
80
    /// recommendations for the list of protocols that every relay must implement.  
81
2205
    pub fn relay_protocol_status(&self) -> &ProtoStatus {
82
2205
        &self.preamble.proto_statuses.relay
83
2205
    }
84

            
85
    /// Return a [`ProtoStatus`] that lists the network's current requirements and
86
    /// recommendations for the list of protocols that every client must implement.
87
98
    pub fn client_protocol_status(&self) -> &ProtoStatus {
88
98
        &self.preamble.proto_statuses.client
89
98
    }
90

            
91
    /// Return a set of all known [`ProtoStatus`] values.
92
49
    pub fn protocol_statuses(&self) -> &Arc<ProtoStatuses> {
93
49
        &self.preamble.proto_statuses
94
49
    }
95
}
96

            
97
impl Consensus {
98
    /// Return a new ConsensusBuilder for building test consensus objects.
99
    ///
100
    /// This function is only available when the `build_docs` feature has
101
    /// been enabled.
102
    #[cfg(feature = "build_docs")]
103
13773
    pub fn builder() -> ConsensusBuilder {
104
13773
        ConsensusBuilder::new(RouterStatus::flavor())
105
13773
    }
106

            
107
    /// Try to parse a single networkstatus document from a string.
108
410
    pub fn parse(s: &str) -> crate::Result<(&str, &str, UncheckedConsensus)> {
109
410
        let mut reader = NetDocReader::new(s)?;
110
421
        Self::parse_from_reader(&mut reader).map_err(|e| e.within(s))
111
410
    }
112
    /// Extract a voter-info section from the reader; return
113
    /// Ok(None) when we are out of voter-info sections.
114
1430
    fn take_voterinfo(
115
1430
        r: &mut NetDocReader<'_, NetstatusKwd>,
116
1430
    ) -> crate::Result<Option<ConsensusAuthorityEntry>> {
117
        use NetstatusKwd::*;
118

            
119
1430
        match r.peek() {
120
            None => return Ok(None),
121
1430
            Some(e) if e.is_ok_with_kwd_in(&[RS_R, DIRECTORY_FOOTER]) => return Ok(None),
122
1073
            _ => (),
123
        };
124

            
125
1073
        let mut first_dir_source = true;
126
        // TODO: Extract this pattern into a "pause at second"???
127
        // Pause at the first 'r', or the second 'dir-source'.
128
4587
        let mut p = r.pause_at(|i| match i {
129
            Err(_) => false,
130
4544
            Ok(item) => {
131
4544
                item.kwd() == RS_R
132
4166
                    || if item.kwd() == DIR_SOURCE {
133
1894
                        let was_first = first_dir_source;
134
1894
                        first_dir_source = false;
135
1894
                        !was_first
136
                    } else {
137
2272
                        false
138
                    }
139
            }
140
4544
        });
141

            
142
1073
        let voter_sec = NS_VOTERINFO_RULES_CONSENSUS.parse(&mut p)?;
143
1073
        let voter = ConsensusAuthorityEntry::from_section(&voter_sec)?;
144

            
145
1073
        Ok(Some(voter))
146
1430
    }
147

            
148
    /// Extract the footer (but not signatures) from the reader.
149
349
    fn take_footer(r: &mut NetDocReader<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
150
        use NetstatusKwd::*;
151
1120
        let mut p = r.pause_at(|i| i.is_ok_with_kwd_in(&[DIRECTORY_SIGNATURE]));
152
349
        let footer_sec = NS_FOOTER_RULES.parse(&mut p)?;
153
349
        let footer = ConsensusFooterFields::from_section(&footer_sec)?;
154
347
        Ok(footer)
155
349
    }
156

            
157
    /// Extract a routerstatus from the reader.  Return Ok(None) if we're
158
    /// out of routerstatus entries.
159
2275
    fn take_routerstatus(r: &mut NetDocReader<'_, NetstatusKwd>) -> crate::Result<Option<(Pos, RouterStatus)>> {
160
        use NetstatusKwd::*;
161
2275
        match r.peek() {
162
            None => return Ok(None),
163
2275
            Some(e) if e.is_ok_with_kwd_in(&[DIRECTORY_FOOTER]) => return Ok(None),
164
1926
            _ => (),
165
        };
166

            
167
1926
        let pos = r.pos();
168

            
169
1926
        let mut first_r = true;
170
15960
        let mut p = r.pause_at(|i| match i {
171
            Err(_) => false,
172
15890
            Ok(item) => {
173
15890
                item.kwd() == DIRECTORY_FOOTER
174
15518
                    || if item.kwd() == RS_R {
175
3708
                        let was_first = first_r;
176
3708
                        first_r = false;
177
3708
                        !was_first
178
                    } else {
179
11810
                        false
180
                    }
181
            }
182
15890
        });
183

            
184
1926
        let rules = match RouterStatus::flavor() {
185
1912
            ConsensusFlavor::Microdesc => &NS_ROUTERSTATUS_RULES_MDCON,
186
14
            ConsensusFlavor::Plain => &NS_ROUTERSTATUS_RULES_PLAIN,
187
        };
188

            
189
1926
        let rs_sec = rules.parse(&mut p)?;
190
1926
        let rs = RouterStatus::from_section(&rs_sec)?;
191
1920
        Ok(Some((pos, rs)))
192
2275
    }
193

            
194
    /// Extract an entire UncheckedConsensus from a reader.
195
    ///
196
    /// Returns the signed portion of the string, the remainder of the
197
    /// string, and an UncheckedConsensus.
198
410
    fn parse_from_reader<'a>(
199
410
        r: &mut NetDocReader<'a, NetstatusKwd>,
200
410
    ) -> crate::Result<(&'a str, &'a str, UncheckedConsensus)> {
201
        use NetstatusKwd::*;
202
357
        let ((flavor, preamble), start_pos) = {
203
5801
            let mut h = r.pause_at(|i| i.is_ok_with_kwd_in(&[DIR_SOURCE]));
204
410
            let preamble_sec = NS_HEADER_RULES_CONSENSUS.parse(&mut h)?;
205
            // Unwrapping should be safe because above `.parse` would have
206
            // returned an Error
207
            #[allow(clippy::unwrap_used)]
208
361
            let pos = preamble_sec.first_item().unwrap().offset_in(r.str()).unwrap();
209
361
            (Preamble::from_section(&preamble_sec)?, pos)
210
        };
211
357
        if RouterStatus::flavor() != flavor {
212
            return Err(EK::BadDocumentType.with_msg(format!(
213
                "Expected {:?}, got {:?}",
214
                RouterStatus::flavor(),
215
                flavor
216
            )));
217
357
        }
218

            
219
357
        let mut voters = Vec::new();
220

            
221
1430
        while let Some(voter) = Self::take_voterinfo(r)? {
222
1073
            voters.push(voter);
223
1073
        }
224

            
225
357
        let mut relays: Vec<RouterStatus> = Vec::new();
226
2275
        while let Some((pos, routerstatus)) = Self::take_routerstatus(r)? {
227
1920
            if let Some(prev) = relays.last() {
228
1565
                if prev.rsa_identity() >= routerstatus.rsa_identity() {
229
2
                    return Err(EK::WrongSortOrder.at_pos(pos));
230
1563
                }
231
355
            }
232
1918
            relays.push(routerstatus);
233
        }
234
349
        relays.shrink_to_fit();
235

            
236
349
        let footer = Self::take_footer(r)?;
237

            
238
347
        let consensus = Consensus {
239
347
            flavor,
240
347
            preamble,
241
347
            voters,
242
347
            relays,
243
347
            footer,
244
347
        };
245

            
246
        // Find the signatures.
247
347
        let mut first_sig: Option<Item<'_, NetstatusKwd>> = None;
248
347
        let mut signatures = Vec::new();
249
1043
        for item in &mut *r {
250
1043
            let item = item?;
251
1043
            if item.kwd() != DIRECTORY_SIGNATURE {
252
                return Err(EK::UnexpectedToken
253
                    .with_msg(item.kwd().to_str())
254
                    .at_pos(item.pos()));
255
1043
            }
256

            
257
1043
            let sig = Signature::from_item(&item)?;
258
1043
            if first_sig.is_none() {
259
347
                first_sig = Some(item);
260
696
            }
261
1043
            signatures.push(sig);
262
        }
263

            
264
347
        let end_pos = match first_sig {
265
            None => return Err(EK::MissingToken.with_msg("directory-signature")),
266
            // Unwrap should be safe because `first_sig` was parsed from `r`
267
            #[allow(clippy::unwrap_used)]
268
347
            Some(sig) => sig.offset_in(r.str()).unwrap() + "directory-signature ".len(),
269
        };
270

            
271
        // Find the appropriate digest.
272
347
        let signed_str = r.str().get(start_pos..end_pos).ok_or(internal!("chopped utf8"))?;
273
347
        let remainder = r.str().get(end_pos..).ok_or(internal!("chopped utf8"))?;
274
347
        let (sha256, sha1) = match RouterStatus::flavor() {
275
2
            ConsensusFlavor::Plain => (
276
2
                None,
277
2
                Some(ll::d::Sha1::digest(signed_str.as_bytes()).into()),
278
2
            ),
279
345
            ConsensusFlavor::Microdesc => (
280
345
                Some(ll::d::Sha256::digest(signed_str.as_bytes()).into()),
281
345
                None,
282
345
            ),
283
        };
284
347
        let hashes = DirectorySignaturesHashesAccu {
285
347
            sha256,
286
347
            sha1,
287
347
            // TODO #2530 This is wrong.  There isn't one hash, there's two.
288
347
            sha1_unnamed: sha1,
289
347
        };
290
347
        let siggroup = SignatureGroup {
291
347
            hashes,
292
347
            signatures,
293
347
        };
294

            
295
347
        let unval = UnvalidatedConsensus {
296
347
            consensus,
297
347
            siggroup,
298
347
            n_authorities: None,
299
347
        };
300
347
        let timebound_range = unval.consensus.preamble.validity_time_range();
301
347
        let timebound = TimerangeBound::new(unval, timebound_range);
302
347
        Ok((signed_str, remainder, timebound))
303
410
    }
304
}
305

            
306
impl Preamble {
307
    /// Extract the CommonPreamble members from a single preamble section.
308
382
    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<(ConsensusFlavor, Preamble)> {
309
        use NetstatusKwd::*;
310

            
311
        {
312
            // this unwrap is safe because if there is not at least one
313
            // token in the section, the section is unparsable.
314
            #[allow(clippy::unwrap_used)]
315
382
            let first = sec.first_item().unwrap();
316
382
            if first.kwd() != NETWORK_STATUS_VERSION {
317
2
                return Err(EK::UnexpectedToken
318
2
                    .with_msg(first.kwd().to_str())
319
2
                    .at_pos(first.pos()));
320
380
            }
321
        }
322

            
323
380
        let ver_item = sec.required(NETWORK_STATUS_VERSION)?;
324

            
325
380
        let version: u32 = ver_item.parse_arg(0)?;
326
380
        if version != 3 {
327
2
            return Err(EK::BadDocumentVersion.with_msg(version.to_string()));
328
378
        }
329
378
        let flavor = ConsensusFlavor::from_opt_name(ver_item.arg(1))?;
330

            
331
378
        let valid_after = sec
332
378
            .required(VALID_AFTER)?
333
378
            .args_as_str()
334
378
            .parse::<Iso8601TimeSp>()?
335
378
            .into();
336
378
        let fresh_until = sec
337
378
            .required(FRESH_UNTIL)?
338
378
            .args_as_str()
339
378
            .parse::<Iso8601TimeSp>()?
340
378
            .into();
341
378
        let valid_until = sec
342
378
            .required(VALID_UNTIL)?
343
378
            .args_as_str()
344
378
            .parse::<Iso8601TimeSp>()?
345
378
            .into();
346
378
        let lifetime = Lifetime::new(valid_after, fresh_until, valid_until)?;
347

            
348
770
        let parse_rec_versions = |item| {
349
756
            let item = sec
350
756
                .maybe(item);
351
756
            let args = item
352
756
                .args_as_str()
353
756
                .unwrap_or("")
354
                // C Tor emits an item with trailing whitespace which we must ignore
355
756
                .trim();
356
            // We want only the first arg, according to the spec.
357
            // We could want to use MaybeItem::parse_arg, but it treats absence of the
358
            // argument as an error.  There is no parse_optional_arg on `MaybeItem`.
359
            // We could add that, but I am trying to avoid adding code to the old parser.
360
            // So instead we reimplement argument splitting (again).
361
756
            args
362
756
                .split_once(|c: char| c.is_ascii_whitespace()).map(|(l, _r)| l).unwrap_or(args)
363
756
                .parse()
364
756
                .map_err(|_e| EK::BadArgument.at_pos(item.pos()))
365
756
        };
366
378
        let client_versions = parse_rec_versions(CLIENT_VERSIONS)?;
367
378
        let server_versions = parse_rec_versions(SERVER_VERSIONS)?;
368

            
369
378
        let proto_statuses = {
370
378
            let client = ProtoStatus::from_section(
371
378
                sec,
372
378
                RECOMMENDED_CLIENT_PROTOCOLS,
373
378
                REQUIRED_CLIENT_PROTOCOLS,
374
            )?;
375
378
            let relay = ProtoStatus::from_section(
376
378
                sec,
377
378
                RECOMMENDED_RELAY_PROTOCOLS,
378
378
                REQUIRED_RELAY_PROTOCOLS,
379
            )?;
380
378
            Arc::new(ProtoStatuses { client, relay })
381
        };
382

            
383
378
        let params = sec.maybe(PARAMS).args_as_str().unwrap_or("").parse()?;
384

            
385
378
        let status: &str = sec.required(VOTE_STATUS)?.arg(0).unwrap_or("");
386
378
        if status != "consensus" {
387
            return Err(EK::BadDocumentType.err());
388
378
        }
389

            
390
        // We're ignoring KNOWN_FLAGS in the consensus.
391

            
392
378
        let consensus_method: u32 = sec.required(CONSENSUS_METHOD)?.parse_arg(0)?;
393

            
394
378
        let shared_rand_previous_value = sec
395
378
            .get(SHARED_RAND_PREVIOUS_VALUE)
396
378
            .map(SharedRandStatus::from_item)
397
378
            .transpose()?;
398

            
399
378
        let shared_rand_current_value = sec
400
378
            .get(SHARED_RAND_CURRENT_VALUE)
401
378
            .map(SharedRandStatus::from_item)
402
378
            .transpose()?;
403

            
404
378
        let voting_delay = if let Some(tok) = sec.get(VOTING_DELAY) {
405
378
            let n1 = tok.parse_arg(0)?;
406
378
            let n2 = tok.parse_arg(1)?;
407
378
            Some((n1, n2))
408
        } else {
409
            None
410
        };
411

            
412
378
        let shared_rand = SharedRandStatuses {
413
378
            shared_rand_previous_value,
414
378
            shared_rand_current_value,
415
378
            __non_exhaustive: (),
416
378
        };
417

            
418
378
        let preamble = Preamble {
419
378
            lifetime,
420
378
            client_versions,
421
378
            server_versions,
422
378
            proto_statuses,
423
378
            params,
424
378
            voting_delay,
425
378
            consensus_method: (consensus_method,),
426
378
            published: NotPresent,
427
378
            consensus_methods: NotPresent,
428
378
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
429
378
            shared_rand,
430
378
            __non_exhaustive: (),
431
378
        };
432

            
433
378
        Ok((flavor, preamble))
434
382
    }
435
}
436

            
437
/// A Microdesc consensus whose signatures have not yet been checked.
438
///
439
/// To validate this object, call set_n_authorities() on it, then call
440
/// check_signature() on that result with the set of certs that you
441
/// have.  Make sure only to provide authority certificates representing
442
/// real authorities!
443
#[derive(Debug, Clone)]
444
#[non_exhaustive]
445
pub struct UnvalidatedConsensus {
446
    /// The consensus object. We don't want to expose this until it's
447
    /// validated.
448
    pub consensus: Consensus,
449
    /// The signatures that need to be validated before we can call
450
    /// this consensus valid.
451
    pub siggroup: SignatureGroup,
452
    /// The total number of authorities that we believe in.  We need
453
    /// this information in order to validate the signatures, since it
454
    /// determines how many signatures we need to find valid in `siggroup`.
455
    pub n_authorities: Option<usize>,
456
}
457

            
458
impl UnvalidatedConsensus {
459
    /// Tell the unvalidated consensus how many authorities we believe in.
460
    ///
461
    /// Without knowing this number, we can't validate the signature.
462
    #[must_use]
463
249
    pub fn set_n_authorities(self, n_authorities: usize) -> Self {
464
249
        UnvalidatedConsensus {
465
249
            n_authorities: Some(n_authorities),
466
249
            ..self
467
249
        }
468
249
    }
469

            
470
    /// Return an iterator of all the certificate IDs that we might use
471
    /// to validate this consensus.
472
196
    pub fn signing_cert_ids(&self) -> impl Iterator<Item = AuthCertKeyIds> {
473
196
        match self.key_is_correct(&[]) {
474
            Ok(()) => Vec::new(),
475
196
            Err(missing) => missing,
476
        }
477
196
        .into_iter()
478
196
    }
479

            
480
    /// Return the lifetime of this unvalidated consensus
481
245
    pub fn peek_lifetime(&self) -> &Lifetime {
482
245
        self.consensus.lifetime()
483
245
    }
484

            
485
    /// Return true if a client who believes in exactly the provided
486
    /// set of authority IDs might consider this consensus to be
487
    /// well-signed.
488
    ///
489
    /// (This is the case if the consensus claims to be signed by more than
490
    /// half of the authorities in the list.)
491
255
    pub fn authorities_are_correct(&self, authorities: &[&RsaIdentity]) -> bool {
492
255
        self.siggroup.could_validate(authorities)
493
255
    }
494

            
495
    /// Return the number of relays in this unvalidated consensus.
496
    ///
497
    /// This function is unstable. It is only enabled if the crate was
498
    /// built with the `experimental-api` feature.
499
    #[cfg(feature = "experimental-api")]
500
    pub fn n_relays(&self) -> usize {
501
        self.consensus.relays.len()
502
    }
503

            
504
    /// Modify the list of relays in this unvalidated consensus.
505
    ///
506
    /// A use case for this is long-lasting custom directories. To ensure Arti can still quickly
507
    /// build circuits when the directory gets old, a tiny churn file can be regularly obtained,
508
    /// listing no longer available Tor nodes, which can then be removed from the consensus.
509
    ///
510
    /// This function is unstable. It is only enabled if the crate was
511
    /// built with the `experimental-api` feature.
512
    #[cfg(feature = "experimental-api")]
513
    pub fn modify_relays<F>(&mut self, func: F)
514
    where
515
        F: FnOnce(&mut Vec<RouterStatus>),
516
    {
517
        func(&mut self.consensus.relays);
518
    }
519
}
520

            
521
impl ExternallySigned<Consensus> for UnvalidatedConsensus {
522
    type Key = [AuthCert];
523
    type KeyHint = Vec<AuthCertKeyIds>;
524
    type Error = Error;
525

            
526
306
    fn key_is_correct(&self, k: &Self::Key) -> result::Result<(), Self::KeyHint> {
527
306
        let (n_ok, missing) = self.siggroup.list_missing(k);
528
306
        match self.n_authorities {
529
306
            Some(n) if consensus_threshold(n).contains(&n_ok) => Ok(()),
530
251
            _ => Err(missing.iter().map(|cert| cert.key_ids).collect()),
531
        }
532
306
    }
533
55
    fn is_well_signed(&self, k: &Self::Key) -> result::Result<(), Self::Error> {
534
55
        match self.n_authorities {
535
            None => Err(Error::from(internal!(
536
                "Didn't set authorities on consensus"
537
            ))),
538
55
            Some(authority) => {
539
55
                self.siggroup.validate(authority, k)
540
56
                    .map_err(|_: VerifyFailed| EK::BadSignature.err())
541
            }
542
        }
543
55
    }
544
151
    fn dangerously_assume_wellsigned(self) -> Consensus {
545
151
        self.consensus
546
151
    }
547
}
548

            
549
/// A Consensus object that has been parsed, but not checked for
550
/// signatures and timeliness.
551
pub type UncheckedConsensus = TimerangeBound<UnvalidatedConsensus>;
552

            
553
#[cfg(feature = "incomplete")] // untested
554
impl NetworkStatusUnverified {
555
    /// Could we verify this consensus or do we need more authcerts?
556
    ///
557
    /// `Ok` means that we have enough authcerts to verify the signature.
558
    ///
559
    /// `Err` means that we have not enough authcerts,
560
    /// or the consensus has not enough signatures.
561
    /// The [`ConsensusVerifiabilityError`] error gives the details.
562
    pub fn can_verify(
563
        &self,
564
        trusted_authorities: &[RsaIdentity],
565
        certs_already: &[AuthCert],
566
    ) -> Result<(), ConsensusVerifiabilityError> {
567
        let sigs = self.inspect_unverified().1;
568
        Self::verify_general(
569
            sigs,
570
            trusted_authorities,
571
            certs_already,
572
            |_signature| {
573
                // indeed, we don't actuaally verify, so this is a no-op
574
                Ok(SignatureVerifiedIfIntended {})
575
            },
576
        )?;
577
        Ok(())
578
    }
579

            
580
    /// Verify the signatures
581
    ///
582
    /// Doesn't check the validity period:
583
    /// the document is wrapped in [`TimerangeBound`],
584
    /// ensuring that the caller does that check.
585
4
    pub fn verify(
586
4
        self,
587
4
        trusted_authorities: &[RsaIdentity],
588
4
        certs: &[AuthCert],
589
4
    ) -> Result<TimerangeBound<NetworkStatus>, ConsensusVerifyFailed> {
590
4
        let (body, sigs) = self.unwrap_unverified();
591

            
592
4
        Self::verify_general(
593
4
            &sigs,
594
4
            trusted_authorities,
595
4
            certs,
596
16
            |tv| tv.verify().map_err(ConsensusVerifyFailed::InvalidSignature),
597
        )?;
598

            
599
4
        let time_range = body.preamble.validity_time_range();
600
4
        Ok(TimerangeBound::new(
601
4
            body,
602
4
            time_range,
603
4
        ))
604
4
    }
605

            
606
    /// Glue to call `SignatureGroup::verify_general` given our `SignaturesData`
607
    ///
608
    /// [`SignatureGroup::verify_general`] contains the actual verification code,
609
    /// shared between the old parser and the new.
610
4
    fn verify_general<E>(
611
4
        sigs: &parse2::SignaturesData<Self>,
612
4
        trusted: &[RsaIdentity],
613
4
        certs: &[AuthCert],
614
4
        do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
615
4
    ) -> Result<(), E>
616
4
    where ConsensusVerifiabilityError: Into<E>,
617
    {
618
4
        SignatureGroup {
619
4
            hashes: sigs.hashes,
620
4
            signatures: sigs.sigs.directory_signature.clone(),
621
4
        }.verify_general(
622
4
            VerifyGeneralTrustedAuthorities::TrustThese { trusted },
623
4
            certs,
624
4
            do_verify,
625
        )
626
4
    }
627
}