1
//! consensus document builders - 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
ns_use_this_variety! {
14
    use [crate::doc::netstatus::rs::build]::?::{RouterStatusBuilder};
15
    use [crate::doc::netstatus::rs]::?::{RouterStatus};
16
}
17
#[cfg(not(doc))]
18
ns_use_this_variety! {
19
    use [crate::doc::netstatus]::?::{Consensus, Preamble};
20
}
21
#[cfg(doc)]
22
ns_use_this_variety! {
23
    pub use [crate::doc::netstatus]::?::{Consensus, Preamble};
24
}
25

            
26
use super::*;
27

            
28
/// A builder object used to construct a consensus.
29
///
30
/// Create one of these with the [`Consensus::builder`] method.
31
///
32
/// This facility is only enabled when the crate is built with
33
/// the `build_docs` feature.
34
#[cfg_attr(docsrs, doc(cfg(feature = "build_docs")))]
35
pub struct ConsensusBuilder {
36
    /// See [`Consensus::flavor`]
37
    flavor: ConsensusFlavor,
38
    /// See [`Preamble::lifetime`]
39
    lifetime: Option<Lifetime>,
40
    /// See [`Preamble::client_versions`]
41
    client_versions: Vec<String>,
42
    /// See [`Preamble::server_versions`]
43
    server_versions: Vec<String>,
44
    /// See [`Preamble::proto_statuses`]
45
    client_protos: ProtoStatus,
46
    /// See [`Preamble::proto_statuses`]
47
    relay_protos: ProtoStatus,
48
    /// See [`Preamble::params`]
49
    params: NetParamValues,
50
    /// See [`Preamble::voting_delay`]
51
    voting_delay: Option<(u32, u32)>,
52
    /// See [`Preamble::consensus_method`]
53
    consensus_method: Option<u32>,
54
    /// See [`SharedRandStatuses::shared_rand_previous_value`]
55
    shared_rand_previous_value: Option<SharedRandStatus>,
56
    /// See [`SharedRandStatuses::shared_rand_current_value`]
57
    shared_rand_current_value: Option<SharedRandStatus>,
58
    /// See [`Consensus::voters`]
59
    voters: Vec<ConsensusAuthorityEntry>,
60
    /// See [`Consensus::relays`]
61
    relays: Vec<RouterStatus>,
62
    /// See [`ConsensusFooterFields::bandwidth_weights`]
63
    weights: ParamValues<i32>,
64
}
65

            
66
impl ConsensusBuilder {
67
    /// Construct a new ConsensusBuilder object.
68
2
    pub(crate) fn new(flavor: ConsensusFlavor) -> ConsensusBuilder {
69
2
        ConsensusBuilder {
70
2
            flavor,
71
2
            lifetime: None,
72
2
            client_versions: Vec::new(),
73
2
            server_versions: Vec::new(),
74
2
            client_protos: ProtoStatus::default(),
75
2
            relay_protos: ProtoStatus::default(),
76
2
            params: ParamValues::new(),
77
2
            voting_delay: None,
78
2
            consensus_method: None,
79
2
            shared_rand_previous_value: None,
80
2
            shared_rand_current_value: None,
81
2
            voters: Vec::new(),
82
2
            relays: Vec::new(),
83
2
            weights: ParamValues::new(),
84
2
        }
85
2
    }
86

            
87
    /// Set the lifetime of this consensus.
88
    ///
89
    /// This value is required.
90
2
    pub fn lifetime(&mut self, lifetime: Lifetime) -> &mut Self {
91
2
        self.lifetime = Some(lifetime);
92
2
        self
93
2
    }
94

            
95
    /// Add a single recommended Tor client version to this consensus.
96
    ///
97
    /// These values are optional for testing.
98
2
    pub fn add_client_version(&mut self, ver: String) -> &mut Self {
99
2
        self.client_versions.push(ver);
100
2
        self
101
2
    }
102
    /// Add a single recommended Tor relay version to this consensus.
103
    ///
104
    /// These values are optional for testing.
105
2
    pub fn add_relay_version(&mut self, ver: String) -> &mut Self {
106
2
        self.server_versions.push(ver);
107
2
        self
108
2
    }
109
    /// Set the required client protocol versions for this consensus.
110
    ///
111
    /// This value defaults to "no protocol versions required."
112
2
    pub fn required_client_protos(&mut self, protos: Protocols) -> &mut Self {
113
2
        self.client_protos.required = protos;
114
2
        self
115
2
    }
116
    /// Set the recommended client protocol versions for this consensus.
117
    ///
118
    /// This value defaults to "no protocol versions recommended."
119
2
    pub fn recommended_client_protos(&mut self, protos: Protocols) -> &mut Self {
120
2
        self.client_protos.recommended = protos;
121
2
        self
122
2
    }
123
    /// Set the required relay protocol versions for this consensus.
124
    ///
125
    /// This value defaults to "no protocol versions required."
126
2
    pub fn required_relay_protos(&mut self, protos: Protocols) -> &mut Self {
127
2
        self.relay_protos.required = protos;
128
2
        self
129
2
    }
130
    /// Set the recommended client protocol versions for this consensus.
131
    ///
132
    /// This value defaults to "no protocol versions recommended."
133
2
    pub fn recommended_relay_protos(&mut self, protos: Protocols) -> &mut Self {
134
2
        self.relay_protos.recommended = protos;
135
2
        self
136
2
    }
137
    /// Set the value for a given consensus parameter by name.
138
4
    pub fn param<S>(&mut self, param: S, val: i32) -> &mut Self
139
4
    where
140
4
        S: Into<String>,
141
    {
142
4
        self.params.set(param.into(), val);
143
4
        self
144
4
    }
145
    /// Set the voting delays (in seconds) for this consensus.
146
2
    pub fn voting_delay(&mut self, vote_delay: u32, signature_delay: u32) -> &mut Self {
147
2
        self.voting_delay = Some((vote_delay, signature_delay));
148
2
        self
149
2
    }
150
    /// Set the declared consensus method for this consensus.
151
    ///
152
    /// This value is required.
153
2
    pub fn consensus_method(&mut self, consensus_method: u32) -> &mut Self {
154
2
        self.consensus_method = Some(consensus_method);
155
2
        self
156
2
    }
157
    /// Set the previous day's shared-random value for this consensus.
158
    ///
159
    /// This value is optional.
160
2
    pub fn shared_rand_prev(
161
2
        &mut self,
162
2
        n_reveals: u8,
163
2
        value: SharedRandVal,
164
2
        timestamp: Option<SystemTime>,
165
2
    ) -> &mut Self {
166
2
        self.shared_rand_previous_value = Some(SharedRandStatus {
167
2
            n_reveals,
168
2
            value,
169
2
            timestamp: timestamp.map(Iso8601TimeNoSp),
170
2
            __non_exhaustive: (),
171
2
        });
172
2
        self
173
2
    }
174
    /// Set the current day's shared-random value for this consensus.
175
    ///
176
    /// This value is optional.
177
2
    pub fn shared_rand_cur(
178
2
        &mut self,
179
2
        n_reveals: u8,
180
2
        value: SharedRandVal,
181
2
        timestamp: Option<SystemTime>,
182
2
    ) -> &mut Self {
183
2
        self.shared_rand_current_value = Some(SharedRandStatus {
184
2
            n_reveals,
185
2
            value,
186
2
            timestamp: timestamp.map(Iso8601TimeNoSp),
187
2
            __non_exhaustive: (),
188
2
        });
189
2
        self
190
2
    }
191
    /// Set a named weight parameter for this consensus.
192
4
    pub fn weight<S>(&mut self, param: S, val: i32) -> &mut Self
193
4
    where
194
4
        S: Into<String>,
195
    {
196
4
        self.weights.set(param.into(), val);
197
4
        self
198
4
    }
199
    /// Replace all weight parameters for this consensus.
200
    pub fn weights(&mut self, weights: ParamValues<i32>) -> &mut Self {
201
        self.weights = weights;
202
        self
203
    }
204
    /// Create a VoterInfoBuilder to add a voter to this builder.
205
    ///
206
    /// In theory these are required, but nothing asks for them.
207
2
    pub fn voter(&self) -> VoterInfoBuilder {
208
2
        VoterInfoBuilder::new()
209
2
    }
210

            
211
    /// Insert a single routerstatus into this builder.
212
2
    pub(crate) fn add_rs(&mut self, rs: RouterStatus) -> &mut Self {
213
2
        self.relays.push(rs);
214
2
        self
215
2
    }
216
}
217

            
218
impl ConsensusBuilder {
219
    /// Create a RouterStatusBuilder to add a RouterStatus to this builder.
220
    ///
221
    /// You can make a consensus with no RouterStatus entries, but it
222
    /// won't actually be good for anything.
223
2
    pub fn rs(&self) -> RouterStatusBuilder {
224
2
        RouterStatusBuilder::new()
225
2
    }
226

            
227
    /// Try to create a consensus object from this builder.
228
    ///
229
    /// This object might not have all of the data that a valid
230
    /// consensus would have. Therefore, it should only be used for
231
    /// testing.
232
2
    pub fn testing_consensus(&self) -> Result<Consensus> {
233
2
        let lifetime = self
234
2
            .lifetime
235
2
            .as_ref()
236
2
            .ok_or(Error::CannotBuild("Missing lifetime."))?
237
            .clone();
238

            
239
2
        let proto_statuses = Arc::new(ProtoStatuses {
240
2
            client: self.client_protos.clone(),
241
2
            relay: self.relay_protos.clone(),
242
2
            __non_exhaustive: (),
243
2
        });
244

            
245
2
        let consensus_method = self
246
2
            .consensus_method
247
2
            .ok_or(Error::CannotBuild("Missing consensus method."))?;
248

            
249
2
        let shared_rand = SharedRandStatuses {
250
2
            shared_rand_previous_value: self.shared_rand_previous_value.clone(),
251
2
            shared_rand_current_value: self.shared_rand_current_value.clone(),
252
2
            __non_exhaustive: (),
253
2
        };
254

            
255
4
        let mk_versions = |v: &[String]| {
256
4
            crate::doc::netstatus::RecommendedTorVersions::from_iter(v.iter())
257
                .map_err(|_| crate::NetdocErrorKind::BadApiUsage.err())
258
4
        };
259

            
260
2
        let (vote_seconds, dist_seconds) = self
261
2
            .voting_delay
262
2
            .unwrap_or(
263
2
                // This is wrong.  voting-delay is mandatory, and we shouldn't emit
264
2
                // `voting-delay 0 0` in a network status document.
265
2
                //
266
2
                // But, this is the old, deprecated, way to build a consensus document.
267
2
                // We retain compatibility with callers who don't specify a voting-delay
268
2
                // to avoid breaking existing test cases, which are hopefully the only
269
2
                // callers of this whole module.
270
2
                (0, 0)
271
2
            );
272
2
        let voting_delay = VotingDelayConstructor {
273
2
            vote_seconds,
274
2
            dist_seconds,
275
2
        }.construct();
276

            
277
        let preamble = Preamble {
278
2
            lifetime,
279
2
            client_versions: mk_versions(&self.client_versions)?,
280
2
            server_versions: mk_versions(&self.server_versions)?,
281
2
            proto_statuses,
282
2
            params: self.params.clone().into(),
283
2
            voting_delay,
284
2
            consensus_method: (consensus_method,),
285
2
            consensus_methods: NotPresent,
286
2
            published: NotPresent,
287
2
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
288
2
            shared_rand,
289
2
            __non_exhaustive: (),
290
        };
291

            
292
2
        let footer = ConsensusFooterFields {
293
2
            bandwidth_weights: self.weights.clone(),
294
2
            __non_exhaustive: (),
295
2
        };
296

            
297
2
        let mut relays = self.relays.clone();
298
2
        relays.sort_by_key(|r| *r.rsa_identity());
299
        // TODO: check for duplicates?
300

            
301
2
        Ok(Consensus {
302
2
            flavor: self.flavor,
303
2
            preamble,
304
2
            voters: self.voters.clone(),
305
2
            relays,
306
2
            footer,
307
2
        })
308
2
    }
309
}
310

            
311
/// Builder object for constructing a [`ConsensusAuthorityEntry`]
312
pub struct VoterInfoBuilder {
313
    /// See [`DirSource::nickname`]
314
    nickname: Option<String>,
315
    /// See [`DirSource::identity`]
316
    identity: Option<RsaIdentity>,
317
    /// See [`DirSource::ip`]
318
    ip: Option<IpAddr>,
319
    /// See [`ConsensusAuthorityEntry::contact`]
320
    contact: Option<String>,
321
    /// See [`ConsensusAuthorityEntry::vote_digest`]
322
    vote_digest: Vec<u8>,
323
    /// See [`DirSource::or_port`]
324
    or_port: u16,
325
    /// See [`DirSource::dir_port`]
326
    dir_port: u16,
327
}
328

            
329
impl VoterInfoBuilder {
330
    /// Construct a new VoterInfoBuilder.
331
2
    pub(crate) fn new() -> Self {
332
2
        VoterInfoBuilder {
333
2
            nickname: None,
334
2
            identity: None,
335
2
            ip: None,
336
2
            contact: None,
337
2
            vote_digest: Vec::new(),
338
2
            or_port: 0,
339
2
            dir_port: 0,
340
2
        }
341
2
    }
342

            
343
    /// Set a nickname.
344
    ///
345
    /// This value is required.
346
2
    pub fn nickname(&mut self, nickname: String) -> &mut Self {
347
2
        self.nickname = Some(nickname);
348
2
        self
349
2
    }
350

            
351
    /// Set an RSA identity.
352
    ///
353
    /// This value is required.
354
2
    pub fn identity(&mut self, identity: RsaIdentity) -> &mut Self {
355
2
        self.identity = Some(identity);
356
2
        self
357
2
    }
358

            
359
    /// Set a IP-valued address.
360
    ///
361
    /// This value is required.
362
2
    pub fn ip(&mut self, ip: IpAddr) -> &mut Self {
363
2
        self.ip = Some(ip);
364
2
        self
365
2
    }
366

            
367
    /// Set a contact line for this voter.
368
    ///
369
    /// This value is optional.
370
2
    pub fn contact(&mut self, contact: String) -> &mut Self {
371
2
        self.contact = Some(contact);
372
2
        self
373
2
    }
374

            
375
    /// Set the declared vote digest for this voter within a consensus.
376
    ///
377
    /// This value is required.
378
2
    pub fn vote_digest(&mut self, vote_digest: Vec<u8>) -> &mut Self {
379
2
        self.vote_digest = vote_digest;
380
2
        self
381
2
    }
382

            
383
    /// Set the declared OrPort for this voter.
384
2
    pub fn or_port(&mut self, or_port: u16) -> &mut Self {
385
2
        self.or_port = or_port;
386
2
        self
387
2
    }
388

            
389
    /// Set the declared DirPort for this voter.
390
2
    pub fn dir_port(&mut self, dir_port: u16) -> &mut Self {
391
2
        self.dir_port = dir_port;
392
2
        self
393
2
    }
394

            
395
    /// Add the voter that we've been building into the in-progress
396
    /// consensus of `builder`.
397
2
    pub fn build(&self, builder: &mut ConsensusBuilder) -> Result<()> {
398
2
        let nickname = self
399
2
            .nickname
400
2
            .as_ref()
401
2
            .ok_or(Error::CannotBuild("Missing nickname"))?
402
            .parse()
403
            .map_err(|_| Error::CannotBuild("Invalid nickname"))?;
404
2
        let identity = self
405
2
            .identity
406
2
            .ok_or(Error::CannotBuild("Missing identity"))?
407
            .into();
408
2
        let ip = self.ip.ok_or(Error::CannotBuild("Missing IP"))?;
409
2
        let contact = self
410
2
            .contact
411
2
            .as_ref()
412
2
            .ok_or(Error::CannotBuild("Missing contact"))?
413
            .parse()
414
            .map_err(|_| Error::CannotBuild("Invalid contact"))?;
415
2
        if self.vote_digest.is_empty() {
416
            return Err(Error::CannotBuild("Missing vote digest"));
417
2
        }
418
2
        let dir_source = DirSource {
419
2
            nickname,
420
2
            identity,
421
2
            hostname: "deprecated-builder.invalid".parse().expect("statically valid"),
422
2
            ip,
423
2
            dir_port: self.dir_port,
424
2
            or_port: self.or_port,
425
2
            __non_exhaustive: (),
426
2
        };
427

            
428
2
        let info = ConsensusAuthorityEntry {
429
2
            dir_source,
430
2
            contact,
431
2
            vote_digest: self.vote_digest.clone().into(),
432
2
            __non_exhaustive: (),
433
2
        };
434
2
        builder.voters.push(info);
435
2
        Ok(())
436
2
    }
437
}
438

            
439
#[cfg(test)]
440
mod test {
441
    // @@ begin test lint list maintained by maint/add_warning @@
442
    #![allow(clippy::bool_assert_comparison)]
443
    #![allow(clippy::clone_on_copy)]
444
    #![allow(clippy::dbg_macro)]
445
    #![allow(clippy::mixed_attributes_style)]
446
    #![allow(clippy::print_stderr)]
447
    #![allow(clippy::print_stdout)]
448
    #![allow(clippy::single_char_pattern)]
449
    #![allow(clippy::unwrap_used)]
450
    #![allow(clippy::unchecked_time_subtraction)]
451
    #![allow(clippy::useless_vec)]
452
    #![allow(clippy::needless_pass_by_value)]
453
    #![allow(clippy::string_slice)] // See arti#2571
454
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
455
    use super::*;
456
    use crate::types::relay_flags::RelayFlag;
457

            
458
    use std::net::SocketAddr;
459
    use web_time_compat::{Duration, SystemTime, SystemTimeExt};
460

            
461
    #[test]
462
    fn consensus() {
463
        let now = SystemTime::get();
464
        let one_hour = Duration::new(3600, 0);
465

            
466
        let mut builder = crate::doc::netstatus::MdConsensus::builder();
467
        builder
468
            .lifetime(Lifetime::new(now, now + one_hour, now + 2 * one_hour).unwrap())
469
            .add_client_version("0.4.5.8".into())
470
            .add_relay_version("0.4.5.9".into())
471
            .required_client_protos("DirCache=2 LinkAuth=3".parse().unwrap())
472
            .required_relay_protos("DirCache=1".parse().unwrap())
473
            .recommended_client_protos("DirCache=6".parse().unwrap())
474
            .recommended_relay_protos("DirCache=5".parse().unwrap())
475
            .param("wombat", 7)
476
            .param("knish", 1212)
477
            .voting_delay(7, 8)
478
            .consensus_method(32)
479
            .shared_rand_prev(1, SharedRandVal([b'x'; 32]), None)
480
            .shared_rand_cur(1, SharedRandVal([b'y'; 32]), None)
481
            .weight("Wxy", 303)
482
            .weight("Wow", 999);
483

            
484
        builder
485
            .voter()
486
            .nickname("Fuzzy".into())
487
            .identity([15; 20].into())
488
            .ip("10.0.0.200".parse().unwrap())
489
            .contact("admin@fuzzy.example.com".into())
490
            .vote_digest((*b"1234").into())
491
            .or_port(9001)
492
            .dir_port(9101)
493
            .build(&mut builder)
494
            .unwrap();
495

            
496
        builder
497
            .rs()
498
            .nickname("Fred".into())
499
            .identity([155; 20].into())
500
            .add_or_port(SocketAddr::from(([10, 0, 0, 60], 9100)))
501
            .add_or_port("[f00f::1]:9200".parse().unwrap())
502
            .doc_digest([99; 32])
503
            .set_flags(RelayFlag::Fast)
504
            .add_flags(RelayFlag::Stable | RelayFlag::V2Dir)
505
            .version("Arti 0.0.0".into())
506
            .protos("DirCache=7".parse().unwrap())
507
            .build_into(&mut builder)
508
            .unwrap();
509

            
510
        let _cons = builder.testing_consensus().unwrap();
511

            
512
        // TODO: Check actual members of `cons` above.
513
    }
514
}