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: Footer,
43
}
44

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

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

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

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

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

            
73
    /// Return the previous shared random value, if the consensus
74
    /// contains one.
75
46155
    pub fn shared_rand_prev(&self) -> Option<&SharedRandStatus> {
76
46155
        self.preamble.shared_rand.shared_rand_previous_value.as_ref()
77
46155
    }
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
2295
    pub fn relay_protocol_status(&self) -> &ProtoStatus {
82
2295
        &self.preamble.proto_statuses.relay
83
2295
    }
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
102
    pub fn client_protocol_status(&self) -> &ProtoStatus {
88
102
        &self.preamble.proto_statuses.client
89
102
    }
90

            
91
    /// Return a set of all known [`ProtoStatus`] values.
92
51
    pub fn protocol_statuses(&self) -> &Arc<ProtoStatuses> {
93
51
        &self.preamble.proto_statuses
94
51
    }
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
14029
    pub fn builder() -> ConsensusBuilder {
104
14029
        ConsensusBuilder::new(RouterStatus::flavor())
105
14029
    }
106

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

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

            
125
1115
        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
4755
        let mut p = r.pause_at(|i| match i {
129
            Err(_) => false,
130
4712
            Ok(item) => {
131
4712
                item.kwd() == RS_R
132
4320
                    || if item.kwd() == DIR_SOURCE {
133
1964
                        let was_first = first_dir_source;
134
1964
                        first_dir_source = false;
135
1964
                        !was_first
136
                    } else {
137
2356
                        false
138
                    }
139
            }
140
4712
        });
141

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

            
145
1115
        Ok(Some(voter))
146
1486
    }
147

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

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

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

            
169
2002
        let mut first_r = true;
170
16552
        let mut p = r.pause_at(|i| match i {
171
            Err(_) => false,
172
16482
            Ok(item) => {
173
16482
                item.kwd() == DIRECTORY_FOOTER
174
16096
                    || if item.kwd() == RS_R {
175
3846
                        let was_first = first_r;
176
3846
                        first_r = false;
177
3846
                        !was_first
178
                    } else {
179
12250
                        false
180
                    }
181
            }
182
16482
        });
183

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

            
189
2002
        let rs_sec = rules.parse(&mut p)?;
190
2002
        let rs = RouterStatus::from_section(&rs_sec)?;
191
1996
        Ok(Some((pos, rs)))
192
2365
    }
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
426
    fn parse_from_reader<'a>(
199
426
        r: &mut NetDocReader<'a, NetstatusKwd>,
200
426
    ) -> Result<(&'a str, &'a str, UncheckedConsensus)> {
201
        use NetstatusKwd::*;
202
371
        let ((flavor, preamble), start_pos) = {
203
6013
            let mut h = r.pause_at(|i| i.is_ok_with_kwd_in(&[DIR_SOURCE]));
204
426
            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
375
            let pos = preamble_sec.first_item().unwrap().offset_in(r.str()).unwrap();
209
375
            (Preamble::from_section(&preamble_sec)?, pos)
210
        };
211
371
        if RouterStatus::flavor() != flavor {
212
            return Err(EK::BadDocumentType.with_msg(format!(
213
                "Expected {:?}, got {:?}",
214
                RouterStatus::flavor(),
215
                flavor
216
            )));
217
371
        }
218

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

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

            
225
371
        let mut relays: Vec<RouterStatus> = Vec::new();
226
2365
        while let Some((pos, routerstatus)) = Self::take_routerstatus(r)? {
227
1996
            if let Some(prev) = relays.last() {
228
1627
                if prev.rsa_identity() >= routerstatus.rsa_identity() {
229
2
                    return Err(EK::WrongSortOrder.at_pos(pos));
230
1625
                }
231
369
            }
232
1994
            relays.push(routerstatus);
233
        }
234
363
        relays.shrink_to_fit();
235

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

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

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

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

            
264
361
        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
361
            Some(sig) => sig.offset_in(r.str()).unwrap() + "directory-signature ".len(),
269
        };
270

            
271
        // Find the appropriate digest.
272
361
        let signed_str = &r.str()[start_pos..end_pos];
273
361
        let remainder = &r.str()[end_pos..];
274
361
        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
359
            ConsensusFlavor::Microdesc => (
280
359
                Some(ll::d::Sha256::digest(signed_str.as_bytes()).into()),
281
359
                None,
282
359
            ),
283
        };
284
361
        let siggroup = SignatureGroup {
285
361
            sha256,
286
361
            sha1,
287
361
            signatures,
288
361
        };
289

            
290
361
        let unval = UnvalidatedConsensus {
291
361
            consensus,
292
361
            siggroup,
293
361
            n_authorities: None,
294
361
        };
295
361
        let lifetime = unval.consensus.preamble.lifetime.clone();
296
361
        let delay = unval.consensus.preamble.voting_delay.unwrap_or((0, 0));
297
361
        let dist_interval = time::Duration::from_secs(delay.1.into());
298
361
        let starting_time = *lifetime.valid_after - dist_interval;
299
361
        let timebound = TimerangeBound::new(unval, starting_time..*lifetime.valid_until);
300
361
        Ok((signed_str, remainder, timebound))
301
426
    }
302
}
303

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

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

            
321
373
        let ver_item = sec.required(NETWORK_STATUS_VERSION)?;
322

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

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

            
346
371
        let client_versions = sec
347
371
            .maybe(CLIENT_VERSIONS)
348
371
            .args_as_str()
349
371
            .unwrap_or("")
350
371
            .split(',')
351
371
            .map(str::to_string)
352
371
            .collect();
353
371
        let server_versions = sec
354
371
            .maybe(SERVER_VERSIONS)
355
371
            .args_as_str()
356
371
            .unwrap_or("")
357
371
            .split(',')
358
371
            .map(str::to_string)
359
371
            .collect();
360

            
361
371
        let proto_statuses = {
362
371
            let client = ProtoStatus::from_section(
363
371
                sec,
364
371
                RECOMMENDED_CLIENT_PROTOCOLS,
365
371
                REQUIRED_CLIENT_PROTOCOLS,
366
            )?;
367
371
            let relay = ProtoStatus::from_section(
368
371
                sec,
369
371
                RECOMMENDED_RELAY_PROTOCOLS,
370
371
                REQUIRED_RELAY_PROTOCOLS,
371
            )?;
372
371
            Arc::new(ProtoStatuses { client, relay })
373
        };
374

            
375
371
        let params = sec.maybe(PARAMS).args_as_str().unwrap_or("").parse()?;
376

            
377
371
        let status: &str = sec.required(VOTE_STATUS)?.arg(0).unwrap_or("");
378
371
        if status != "consensus" {
379
            return Err(EK::BadDocumentType.err());
380
371
        }
381

            
382
        // We're ignoring KNOWN_FLAGS in the consensus.
383

            
384
371
        let consensus_method: u32 = sec.required(CONSENSUS_METHOD)?.parse_arg(0)?;
385

            
386
371
        let shared_rand_previous_value = sec
387
371
            .get(SHARED_RAND_PREVIOUS_VALUE)
388
371
            .map(SharedRandStatus::from_item)
389
371
            .transpose()?;
390

            
391
371
        let shared_rand_current_value = sec
392
371
            .get(SHARED_RAND_CURRENT_VALUE)
393
371
            .map(SharedRandStatus::from_item)
394
371
            .transpose()?;
395

            
396
371
        let voting_delay = if let Some(tok) = sec.get(VOTING_DELAY) {
397
371
            let n1 = tok.parse_arg(0)?;
398
371
            let n2 = tok.parse_arg(1)?;
399
371
            Some((n1, n2))
400
        } else {
401
            None
402
        };
403

            
404
371
        let shared_rand = SharedRandStatuses {
405
371
            shared_rand_previous_value,
406
371
            shared_rand_current_value,
407
371
            __non_exhaustive: (),
408
371
        };
409

            
410
371
        let preamble = Preamble {
411
371
            lifetime,
412
371
            client_versions,
413
371
            server_versions,
414
371
            proto_statuses,
415
371
            params,
416
371
            voting_delay,
417
371
            consensus_method: (consensus_method,),
418
371
            published: NotPresent,
419
371
            consensus_methods: NotPresent,
420
371
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
421
371
            shared_rand,
422
371
            __non_exhaustive: (),
423
371
        };
424

            
425
371
        Ok((flavor, preamble))
426
375
    }
427
}
428

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

            
450
impl UnvalidatedConsensus {
451
    /// Tell the unvalidated consensus how many authorities we believe in.
452
    ///
453
    /// Without knowing this number, we can't validate the signature.
454
    #[must_use]
455
259
    pub fn set_n_authorities(self, n_authorities: usize) -> Self {
456
259
        UnvalidatedConsensus {
457
259
            n_authorities: Some(n_authorities),
458
259
            ..self
459
259
        }
460
259
    }
461

            
462
    /// Return an iterator of all the certificate IDs that we might use
463
    /// to validate this consensus.
464
204
    pub fn signing_cert_ids(&self) -> impl Iterator<Item = AuthCertKeyIds> {
465
204
        match self.key_is_correct(&[]) {
466
            Ok(()) => Vec::new(),
467
204
            Err(missing) => missing,
468
        }
469
204
        .into_iter()
470
204
    }
471

            
472
    /// Return the lifetime of this unvalidated consensus
473
255
    pub fn peek_lifetime(&self) -> &Lifetime {
474
255
        self.consensus.lifetime()
475
255
    }
476

            
477
    /// Return true if a client who believes in exactly the provided
478
    /// set of authority IDs might consider this consensus to be
479
    /// well-signed.
480
    ///
481
    /// (This is the case if the consensus claims to be signed by more than
482
    /// half of the authorities in the list.)
483
265
    pub fn authorities_are_correct(&self, authorities: &[&RsaIdentity]) -> bool {
484
265
        self.siggroup.could_validate(authorities)
485
265
    }
486

            
487
    /// Return the number of relays in this unvalidated consensus.
488
    ///
489
    /// This function is unstable. It is only enabled if the crate was
490
    /// built with the `experimental-api` feature.
491
    #[cfg(feature = "experimental-api")]
492
    pub fn n_relays(&self) -> usize {
493
        self.consensus.relays.len()
494
    }
495

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

            
513
impl ExternallySigned<Consensus> for UnvalidatedConsensus {
514
    type Key = [AuthCert];
515
    type KeyHint = Vec<AuthCertKeyIds>;
516
    type Error = Error;
517

            
518
318
    fn key_is_correct(&self, k: &Self::Key) -> result::Result<(), Self::KeyHint> {
519
318
        let (n_ok, missing) = self.siggroup.list_missing(k);
520
318
        match self.n_authorities {
521
318
            Some(n) if n_ok > (n / 2) => Ok(()),
522
261
            _ => Err(missing.iter().map(|cert| cert.key_ids).collect()),
523
        }
524
318
    }
525
57
    fn is_well_signed(&self, k: &Self::Key) -> result::Result<(), Self::Error> {
526
57
        match self.n_authorities {
527
            None => Err(Error::from(internal!(
528
                "Didn't set authorities on consensus"
529
            ))),
530
57
            Some(authority) => {
531
57
                if self.siggroup.validate(authority, k) {
532
55
                    Ok(())
533
                } else {
534
2
                    Err(EK::BadSignature.err())
535
                }
536
            }
537
        }
538
57
    }
539
157
    fn dangerously_assume_wellsigned(self) -> Consensus {
540
157
        self.consensus
541
157
    }
542
}
543

            
544
/// A Consensus object that has been parsed, but not checked for
545
/// signatures and timeliness.
546
pub type UncheckedConsensus = TimerangeBound<UnvalidatedConsensus>;
547