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 [`Preamble::shared_rand_previous_value`]
55
    shared_rand_previous_value: Option<SharedRandStatus>,
56
    /// See [`Preamble::shared_rand_current_value`]
57
    shared_rand_current_value: Option<SharedRandStatus>,
58
    /// See [`Consensus::voters`]
59
    voters: Vec<ConsensusVoterInfo>,
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
13204
    pub(crate) fn new(flavor: ConsensusFlavor) -> ConsensusBuilder {
69
13204
        ConsensusBuilder {
70
13204
            flavor,
71
13204
            lifetime: None,
72
13204
            client_versions: Vec::new(),
73
13204
            server_versions: Vec::new(),
74
13204
            client_protos: ProtoStatus::default(),
75
13204
            relay_protos: ProtoStatus::default(),
76
13204
            params: NetParams::new(),
77
13204
            voting_delay: None,
78
13204
            consensus_method: None,
79
13204
            shared_rand_previous_value: None,
80
13204
            shared_rand_current_value: None,
81
13204
            voters: Vec::new(),
82
13204
            relays: Vec::new(),
83
13204
            weights: NetParams::new(),
84
13204
        }
85
13204
    }
86

            
87
    /// Set the lifetime of this consensus.
88
    ///
89
    /// This value is required.
90
10996
    pub fn lifetime(&mut self, lifetime: Lifetime) -> &mut Self {
91
10996
        self.lifetime = Some(lifetime);
92
10996
        self
93
10996
    }
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
9705
    pub fn param<S>(&mut self, param: S, val: i32) -> &mut Self
139
9705
    where
140
9705
        S: Into<String>,
141
    {
142
9705
        self.params.set(param.into(), val);
143
9705
        self
144
9705
    }
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
10996
    pub fn consensus_method(&mut self, consensus_method: u32) -> &mut Self {
154
10996
        self.consensus_method = Some(consensus_method);
155
10996
        self
156
10996
    }
157
    /// Set the previous day's shared-random value for this consensus.
158
    ///
159
    /// This value is optional.
160
15892
    pub fn shared_rand_prev(
161
15892
        &mut self,
162
15892
        n_reveals: u8,
163
15892
        value: SharedRandVal,
164
15892
        timestamp: Option<SystemTime>,
165
15892
    ) -> &mut Self {
166
15892
        self.shared_rand_previous_value = Some(SharedRandStatus {
167
15892
            n_reveals,
168
15892
            value,
169
15892
            timestamp: timestamp.map(Iso8601TimeNoSp),
170
15892
        });
171
15892
        self
172
15892
    }
173
    /// Set the current day's shared-random value for this consensus.
174
    ///
175
    /// This value is optional.
176
532
    pub fn shared_rand_cur(
177
532
        &mut self,
178
532
        n_reveals: u8,
179
532
        value: SharedRandVal,
180
532
        timestamp: Option<SystemTime>,
181
532
    ) -> &mut Self {
182
532
        self.shared_rand_current_value = Some(SharedRandStatus {
183
532
            n_reveals,
184
532
            value,
185
532
            timestamp: timestamp.map(Iso8601TimeNoSp),
186
532
        });
187
532
        self
188
532
    }
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
10992
    pub fn weights(&mut self, weights: NetParams<i32>) -> &mut Self {
199
10992
        self.weights = weights;
200
10992
        self
201
10992
    }
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
409492
    pub(crate) fn add_rs(&mut self, rs: RouterStatus) -> &mut Self {
211
409492
        self.relays.push(rs);
212
409492
        self
213
409492
    }
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
426532
    pub fn rs(&self) -> RouterStatusBuilder {
222
426532
        RouterStatusBuilder::new()
223
426532
    }
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
10996
    pub fn testing_consensus(&self) -> Result<Consensus> {
231
10996
        let lifetime = self
232
10996
            .lifetime
233
10996
            .as_ref()
234
10996
            .ok_or(Error::CannotBuild("Missing lifetime."))?
235
10996
            .clone();
236

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

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

            
246
10996
        let preamble = Preamble {
247
10996
            lifetime,
248
10996
            client_versions: self.client_versions.clone(),
249
10996
            server_versions: self.server_versions.clone(),
250
10996
            proto_statuses,
251
10996
            params: self.params.clone(),
252
10996
            voting_delay: self.voting_delay,
253
10996
            consensus_method,
254
10996
            consensus_methods: NotPresent,
255
10996
            published: NotPresent,
256
10996
            shared_rand_previous_value: self.shared_rand_previous_value.clone(),
257
10996
            shared_rand_current_value: self.shared_rand_current_value.clone(),
258
10996
        };
259

            
260
10996
        let footer = Footer {
261
10996
            weights: self.weights.clone(),
262
10996
        };
263

            
264
10996
        let mut relays = self.relays.clone();
265
832841
        relays.sort_by_key(|r| *r.rsa_identity());
266
        // TODO: check for duplicates?
267

            
268
10996
        Ok(Consensus {
269
10996
            flavor: self.flavor,
270
10996
            preamble,
271
10996
            voters: self.voters.clone(),
272
10996
            relays,
273
10996
            footer,
274
10996
        })
275
10996
    }
276
}
277

            
278
/// Builder object for constructing a [`ConsensusVoterInfo`]
279
pub struct VoterInfoBuilder {
280
    /// See [`DirSource::nickname`]
281
    nickname: Option<String>,
282
    /// See [`DirSource::identity`]
283
    identity: Option<RsaIdentity>,
284
    /// See [`DirSource::ip`]
285
    ip: Option<IpAddr>,
286
    /// See [`ConsensusVoterInfo::contact`]
287
    contact: Option<String>,
288
    /// See [`ConsensusVoterInfo::vote_digest`]
289
    vote_digest: Vec<u8>,
290
    /// See [`DirSource::or_port`]
291
    or_port: u16,
292
    /// See [`DirSource::dir_port`]
293
    dir_port: u16,
294
}
295

            
296
impl VoterInfoBuilder {
297
    /// Construct a new VoterInfoBuilder.
298
4
    pub(crate) fn new() -> Self {
299
4
        VoterInfoBuilder {
300
4
            nickname: None,
301
4
            identity: None,
302
4
            ip: None,
303
4
            contact: None,
304
4
            vote_digest: Vec::new(),
305
4
            or_port: 0,
306
4
            dir_port: 0,
307
4
        }
308
4
    }
309

            
310
    /// Set a nickname.
311
    ///
312
    /// This value is required.
313
4
    pub fn nickname(&mut self, nickname: String) -> &mut Self {
314
4
        self.nickname = Some(nickname);
315
4
        self
316
4
    }
317

            
318
    /// Set an RSA identity.
319
    ///
320
    /// This value is required.
321
4
    pub fn identity(&mut self, identity: RsaIdentity) -> &mut Self {
322
4
        self.identity = Some(identity);
323
4
        self
324
4
    }
325

            
326
    /// Set a IP-valued address.
327
    ///
328
    /// This value is required.
329
4
    pub fn ip(&mut self, ip: IpAddr) -> &mut Self {
330
4
        self.ip = Some(ip);
331
4
        self
332
4
    }
333

            
334
    /// Set a contact line for this voter.
335
    ///
336
    /// This value is optional.
337
4
    pub fn contact(&mut self, contact: String) -> &mut Self {
338
4
        self.contact = Some(contact);
339
4
        self
340
4
    }
341

            
342
    /// Set the declared vote digest for this voter within a consensus.
343
    ///
344
    /// This value is required.
345
4
    pub fn vote_digest(&mut self, vote_digest: Vec<u8>) -> &mut Self {
346
4
        self.vote_digest = vote_digest;
347
4
        self
348
4
    }
349

            
350
    /// Set the declared OrPort for this voter.
351
4
    pub fn or_port(&mut self, or_port: u16) -> &mut Self {
352
4
        self.or_port = or_port;
353
4
        self
354
4
    }
355

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

            
362
    /// Add the voter that we've been building into the in-progress
363
    /// consensus of `builder`.
364
4
    pub fn build(&self, builder: &mut ConsensusBuilder) -> Result<()> {
365
4
        let nickname = self
366
4
            .nickname
367
4
            .as_ref()
368
4
            .ok_or(Error::CannotBuild("Missing nickname"))?
369
4
            .clone();
370
4
        let identity = self
371
4
            .identity
372
4
            .ok_or(Error::CannotBuild("Missing identity"))?;
373
4
        let ip = self.ip.ok_or(Error::CannotBuild("Missing IP"))?;
374
4
        let contact = self
375
4
            .contact
376
4
            .as_ref()
377
4
            .ok_or(Error::CannotBuild("Missing contact"))?
378
4
            .clone();
379
4
        if self.vote_digest.is_empty() {
380
            return Err(Error::CannotBuild("Missing vote digest"));
381
4
        }
382
4
        let dir_source = DirSource {
383
4
            nickname,
384
4
            identity,
385
4
            ip,
386
4
            dir_port: self.dir_port,
387
4
            or_port: self.or_port,
388
4
        };
389

            
390
4
        let info = ConsensusVoterInfo {
391
4
            dir_source,
392
4
            contact,
393
4
            vote_digest: self.vote_digest.clone(),
394
4
        };
395
4
        builder.voters.push(info);
396
4
        Ok(())
397
4
    }
398
}
399

            
400
#[cfg(test)]
401
mod test {
402
    // @@ begin test lint list maintained by maint/add_warning @@
403
    #![allow(clippy::bool_assert_comparison)]
404
    #![allow(clippy::clone_on_copy)]
405
    #![allow(clippy::dbg_macro)]
406
    #![allow(clippy::mixed_attributes_style)]
407
    #![allow(clippy::print_stderr)]
408
    #![allow(clippy::print_stdout)]
409
    #![allow(clippy::single_char_pattern)]
410
    #![allow(clippy::unwrap_used)]
411
    #![allow(clippy::unchecked_time_subtraction)]
412
    #![allow(clippy::useless_vec)]
413
    #![allow(clippy::needless_pass_by_value)]
414
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
415
    use super::*;
416
    use crate::types::relay_flags::RelayFlag;
417

            
418
    use std::net::SocketAddr;
419
    use std::time::{Duration, SystemTime};
420

            
421
    #[test]
422
    fn consensus() {
423
        let now = SystemTime::now();
424
        let one_hour = Duration::new(3600, 0);
425

            
426
        let mut builder = crate::doc::netstatus::MdConsensus::builder();
427
        builder
428
            .lifetime(Lifetime::new(now, now + one_hour, now + 2 * one_hour).unwrap())
429
            .add_client_version("0.4.5.8".into())
430
            .add_relay_version("0.4.5.9".into())
431
            .required_client_protos("DirCache=2 LinkAuth=3".parse().unwrap())
432
            .required_relay_protos("DirCache=1".parse().unwrap())
433
            .recommended_client_protos("DirCache=6".parse().unwrap())
434
            .recommended_relay_protos("DirCache=5".parse().unwrap())
435
            .param("wombat", 7)
436
            .param("knish", 1212)
437
            .voting_delay(7, 8)
438
            .consensus_method(32)
439
            .shared_rand_prev(1, SharedRandVal([b'x'; 32]), None)
440
            .shared_rand_cur(1, SharedRandVal([b'y'; 32]), None)
441
            .weight("Wxy", 303)
442
            .weight("Wow", 999);
443

            
444
        builder
445
            .voter()
446
            .nickname("Fuzzy".into())
447
            .identity([15; 20].into())
448
            .ip("10.0.0.200".parse().unwrap())
449
            .contact("admin@fuzzy.example.com".into())
450
            .vote_digest((*b"1234").into())
451
            .or_port(9001)
452
            .dir_port(9101)
453
            .build(&mut builder)
454
            .unwrap();
455

            
456
        builder
457
            .rs()
458
            .nickname("Fred".into())
459
            .identity([155; 20].into())
460
            .add_or_port(SocketAddr::from(([10, 0, 0, 60], 9100)))
461
            .add_or_port("[f00f::1]:9200".parse().unwrap())
462
            .doc_digest([99; 32])
463
            .set_flags(RelayFlag::Fast)
464
            .add_flags(RelayFlag::Stable | RelayFlag::V2Dir)
465
            .version("Arti 0.0.0".into())
466
            .protos("DirCache=7".parse().unwrap())
467
            .build_into(&mut builder)
468
            .unwrap();
469

            
470
        let _cons = builder.testing_consensus().unwrap();
471

            
472
        // TODO: Check actual members of `cons` above.
473
    }
474
}