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: NetParams<i32>,
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 [`Footer::weights`]
63
    weights: NetParams<i32>,
64
}
65

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

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

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

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

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

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

            
237
11683
        let proto_statuses = Arc::new(ProtoStatuses {
238
11683
            client: self.client_protos.clone(),
239
11683
            relay: self.relay_protos.clone(),
240
11683
        });
241

            
242
11683
        let consensus_method = self
243
11683
            .consensus_method
244
11683
            .ok_or(Error::CannotBuild("Missing consensus method."))?;
245

            
246
11683
        let shared_rand = SharedRandStatuses {
247
11683
            shared_rand_previous_value: self.shared_rand_previous_value.clone(),
248
11683
            shared_rand_current_value: self.shared_rand_current_value.clone(),
249
11683
            __non_exhaustive: (),
250
11683
        };
251

            
252
11683
        let preamble = Preamble {
253
11683
            lifetime,
254
11683
            client_versions: self.client_versions.clone(),
255
11683
            server_versions: self.server_versions.clone(),
256
11683
            proto_statuses,
257
11683
            params: self.params.clone(),
258
11683
            voting_delay: self.voting_delay,
259
11683
            consensus_method: (consensus_method,),
260
11683
            consensus_methods: NotPresent,
261
11683
            published: NotPresent,
262
11683
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
263
11683
            shared_rand,
264
11683
            __non_exhaustive: (),
265
11683
        };
266

            
267
11683
        let footer = Footer {
268
11683
            weights: self.weights.clone(),
269
11683
        };
270

            
271
11683
        let mut relays = self.relays.clone();
272
917909
        relays.sort_by_key(|r| *r.rsa_identity());
273
        // TODO: check for duplicates?
274

            
275
11683
        Ok(Consensus {
276
11683
            flavor: self.flavor,
277
11683
            preamble,
278
11683
            voters: self.voters.clone(),
279
11683
            relays,
280
11683
            footer,
281
11683
        })
282
11683
    }
283
}
284

            
285
/// Builder object for constructing a [`ConsensusAuthorityEntry`]
286
pub struct VoterInfoBuilder {
287
    /// See [`DirSource::nickname`]
288
    nickname: Option<String>,
289
    /// See [`DirSource::identity`]
290
    identity: Option<RsaIdentity>,
291
    /// See [`DirSource::ip`]
292
    ip: Option<IpAddr>,
293
    /// See [`ConsensusAuthorityEntry::contact`]
294
    contact: Option<String>,
295
    /// See [`ConsensusAuthorityEntry::vote_digest`]
296
    vote_digest: Vec<u8>,
297
    /// See [`DirSource::or_port`]
298
    or_port: u16,
299
    /// See [`DirSource::dir_port`]
300
    dir_port: u16,
301
}
302

            
303
impl VoterInfoBuilder {
304
    /// Construct a new VoterInfoBuilder.
305
4
    pub(crate) fn new() -> Self {
306
4
        VoterInfoBuilder {
307
4
            nickname: None,
308
4
            identity: None,
309
4
            ip: None,
310
4
            contact: None,
311
4
            vote_digest: Vec::new(),
312
4
            or_port: 0,
313
4
            dir_port: 0,
314
4
        }
315
4
    }
316

            
317
    /// Set a nickname.
318
    ///
319
    /// This value is required.
320
4
    pub fn nickname(&mut self, nickname: String) -> &mut Self {
321
4
        self.nickname = Some(nickname);
322
4
        self
323
4
    }
324

            
325
    /// Set an RSA identity.
326
    ///
327
    /// This value is required.
328
4
    pub fn identity(&mut self, identity: RsaIdentity) -> &mut Self {
329
4
        self.identity = Some(identity);
330
4
        self
331
4
    }
332

            
333
    /// Set a IP-valued address.
334
    ///
335
    /// This value is required.
336
4
    pub fn ip(&mut self, ip: IpAddr) -> &mut Self {
337
4
        self.ip = Some(ip);
338
4
        self
339
4
    }
340

            
341
    /// Set a contact line for this voter.
342
    ///
343
    /// This value is optional.
344
4
    pub fn contact(&mut self, contact: String) -> &mut Self {
345
4
        self.contact = Some(contact);
346
4
        self
347
4
    }
348

            
349
    /// Set the declared vote digest for this voter within a consensus.
350
    ///
351
    /// This value is required.
352
4
    pub fn vote_digest(&mut self, vote_digest: Vec<u8>) -> &mut Self {
353
4
        self.vote_digest = vote_digest;
354
4
        self
355
4
    }
356

            
357
    /// Set the declared OrPort for this voter.
358
4
    pub fn or_port(&mut self, or_port: u16) -> &mut Self {
359
4
        self.or_port = or_port;
360
4
        self
361
4
    }
362

            
363
    /// Set the declared DirPort for this voter.
364
4
    pub fn dir_port(&mut self, dir_port: u16) -> &mut Self {
365
4
        self.dir_port = dir_port;
366
4
        self
367
4
    }
368

            
369
    /// Add the voter that we've been building into the in-progress
370
    /// consensus of `builder`.
371
4
    pub fn build(&self, builder: &mut ConsensusBuilder) -> Result<()> {
372
4
        let nickname = self
373
4
            .nickname
374
4
            .as_ref()
375
4
            .ok_or(Error::CannotBuild("Missing nickname"))?
376
4
            .parse()
377
4
            .map_err(|_| Error::CannotBuild("Invalid nickname"))?;
378
4
        let identity = self
379
4
            .identity
380
4
            .ok_or(Error::CannotBuild("Missing identity"))?
381
4
            .into();
382
4
        let ip = self.ip.ok_or(Error::CannotBuild("Missing IP"))?;
383
4
        let contact = self
384
4
            .contact
385
4
            .as_ref()
386
4
            .ok_or(Error::CannotBuild("Missing contact"))?
387
4
            .parse()
388
4
            .map_err(|_| Error::CannotBuild("Invalid contact"))?;
389
4
        if self.vote_digest.is_empty() {
390
            return Err(Error::CannotBuild("Missing vote digest"));
391
4
        }
392
4
        let dir_source = DirSource {
393
4
            nickname,
394
4
            identity,
395
4
            hostname: "deprecated-builder.invalid".parse().expect("statically valid"),
396
4
            ip,
397
4
            dir_port: self.dir_port,
398
4
            or_port: self.or_port,
399
4
            __non_exhaustive: (),
400
4
        };
401

            
402
4
        let info = ConsensusAuthorityEntry {
403
4
            dir_source,
404
4
            contact,
405
4
            vote_digest: self.vote_digest.clone().into(),
406
4
            __non_exhaustive: (),
407
4
        };
408
4
        builder.voters.push(info);
409
4
        Ok(())
410
4
    }
411
}
412

            
413
#[cfg(test)]
414
mod test {
415
    // @@ begin test lint list maintained by maint/add_warning @@
416
    #![allow(clippy::bool_assert_comparison)]
417
    #![allow(clippy::clone_on_copy)]
418
    #![allow(clippy::dbg_macro)]
419
    #![allow(clippy::mixed_attributes_style)]
420
    #![allow(clippy::print_stderr)]
421
    #![allow(clippy::print_stdout)]
422
    #![allow(clippy::single_char_pattern)]
423
    #![allow(clippy::unwrap_used)]
424
    #![allow(clippy::unchecked_time_subtraction)]
425
    #![allow(clippy::useless_vec)]
426
    #![allow(clippy::needless_pass_by_value)]
427
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
428
    use super::*;
429
    use crate::types::relay_flags::RelayFlag;
430

            
431
    use std::net::SocketAddr;
432
    use web_time_compat::{Duration, SystemTime, SystemTimeExt};
433

            
434
    #[test]
435
    fn consensus() {
436
        let now = SystemTime::get();
437
        let one_hour = Duration::new(3600, 0);
438

            
439
        let mut builder = crate::doc::netstatus::MdConsensus::builder();
440
        builder
441
            .lifetime(Lifetime::new(now, now + one_hour, now + 2 * one_hour).unwrap())
442
            .add_client_version("0.4.5.8".into())
443
            .add_relay_version("0.4.5.9".into())
444
            .required_client_protos("DirCache=2 LinkAuth=3".parse().unwrap())
445
            .required_relay_protos("DirCache=1".parse().unwrap())
446
            .recommended_client_protos("DirCache=6".parse().unwrap())
447
            .recommended_relay_protos("DirCache=5".parse().unwrap())
448
            .param("wombat", 7)
449
            .param("knish", 1212)
450
            .voting_delay(7, 8)
451
            .consensus_method(32)
452
            .shared_rand_prev(1, SharedRandVal([b'x'; 32]), None)
453
            .shared_rand_cur(1, SharedRandVal([b'y'; 32]), None)
454
            .weight("Wxy", 303)
455
            .weight("Wow", 999);
456

            
457
        builder
458
            .voter()
459
            .nickname("Fuzzy".into())
460
            .identity([15; 20].into())
461
            .ip("10.0.0.200".parse().unwrap())
462
            .contact("admin@fuzzy.example.com".into())
463
            .vote_digest((*b"1234").into())
464
            .or_port(9001)
465
            .dir_port(9101)
466
            .build(&mut builder)
467
            .unwrap();
468

            
469
        builder
470
            .rs()
471
            .nickname("Fred".into())
472
            .identity([155; 20].into())
473
            .add_or_port(SocketAddr::from(([10, 0, 0, 60], 9100)))
474
            .add_or_port("[f00f::1]:9200".parse().unwrap())
475
            .doc_digest([99; 32])
476
            .set_flags(RelayFlag::Fast)
477
            .add_flags(RelayFlag::Stable | RelayFlag::V2Dir)
478
            .version("Arti 0.0.0".into())
479
            .protos("DirCache=7".parse().unwrap())
480
            .build_into(&mut builder)
481
            .unwrap();
482

            
483
        let _cons = builder.testing_consensus().unwrap();
484

            
485
        // TODO: Check actual members of `cons` above.
486
    }
487
}