1
//! Calculate consensus preamble
2

            
3
use super::*;
4

            
5
/// One vote input to `compute_consensus_from_votes`
6
#[allow(clippy::exhaustive_structs)] // this is an aggregation of a function input argument
7
pub struct VoteInput<'v> {
8
    /// The vote; signature must have been verified
9
    pub vote: &'v netstatus::vote::NetworkStatus,
10

            
11
    /// The voter nickname, used only for logging/reporting
12
    pub nickname: &'v Nickname,
13

            
14
    /// Signature hashes, from document parsing
15
    pub sig_hashes: &'v netstatus::DirectorySignaturesHashesAccu,
16
}
17

            
18
/// Outputs from consensus calculation
19
#[non_exhaustive]
20
pub struct Consensuses {
21
    /// plain consensus
22
    pub plain: netstatus::plain::NetworkStatus,
23
    /// md consensus
24
    pub md: netstatus::md::NetworkStatus,
25
}
26

            
27
impl ConsensusesFromVotes<()> for netstatus::vote::NetworkStatus {
28
    type PlainOutput = netstatus::plain::NetworkStatus;
29
    type MdOutput = netstatus::md::NetworkStatus;
30

            
31
16
    fn consensuses<'i>(
32
16
        context: ConsensusContextRefs<()>,
33
16
        inputs: impl Iterator<Item = (VoterNum, &'i Self)> + Clone,
34
16
    ) -> Result<(Self::PlainOutput, Self::MdOutput), ConsensusError>
35
16
    where
36
16
        Self: 'i,
37
    {
38
16
        calc! { both.preamble }
39

            
40
16
        let context = context.with_computed(&plain_preamble);
41

            
42
16
        calc! { both.routers }
43
16
        calc! { both.authority }
44

            
45
16
        let computed = FooterAC {
46
16
            preamble: &plain_preamble,
47
16
            routers: &plain_routers,
48
16
        };
49
16
        let context = context.with_computed(&computed);
50

            
51
16
        calc! { both.footer }
52

            
53
16
        Ok(construct_both! {
54
16
            netstatus::plain::NetworkStatus, netstatus::md::NetworkStatus {
55
16
                both. preamble, authority, footer;
56
16
            } {
57
16
                // `network_status_version` and `vote_status`: unit tokens, Default is fine
58
16
                both. routers;
59
16
            }
60
16
        })
61
16
    }
62
}
63

            
64
impl<AC> Aggregate<AC> for netstatus::VoteAuthoritySection {
65
    type Output = netstatus::ConsensusAuthoritySection;
66

            
67
32
    fn aggregate<'i>(
68
32
        context: ConsensusContextRefs<AC>,
69
32
        inputs: impl ComponentInVotes<&'i Self>,
70
32
    ) -> Result<Self::Output, ConsensusError>
71
32
    where
72
32
        Self: 'i,
73
    {
74
        use netstatus::{
75
            ConsensusAuthorityEntry, ConsensusAuthorityEntryConstructor, ConsensusAuthoritySection,
76
            ConsensusAuthoritySectionConstructor, DirectorySignaturesHashesAccu,
77
            SupersededAuthorityKey, VoteAuthorityEntry,
78
        };
79

            
80
172
        fn vote2consensus(
81
172
            vae: &VoteAuthorityEntry,
82
172
            sig_hashes: &DirectorySignaturesHashesAccu,
83
172
        ) -> Result<(ConsensusAuthorityEntry, Option<SupersededAuthorityKey>), Bug> {
84
            macro_rules! copy_field { { $f:ident } => { let $f = vae.$f.clone(); } }
85
172
            copy_field! { dir_source }
86
172
            copy_field! { contact }
87

            
88
172
            let vote_digest = chain!(
89
172
                sig_hashes.sha256.as_ref().map(|h| &h[..]),
90
172
                sig_hashes.sha1.as_ref().map(|h| &h[..]),
91
            )
92
            .next()
93
            .ok_or_else(|| internal!("vote without any digest"))?
94
            .to_owned()
95
            .into();
96

            
97
172
            let superseded_authority_key = vae.legacy_dir_key.map(|fingerprint| {
98
                SupersededAuthorityKey::from_dir_source_and_key(
99
                    //
100
                    vae.dir_source.clone(),
101
                    fingerprint,
102
                )
103
            });
104

            
105
172
            Ok((
106
172
                ConsensusAuthorityEntry {
107
172
                    ..ConsensusAuthorityEntryConstructor {
108
172
                        dir_source,
109
172
                        contact,
110
172
                        vote_digest,
111
172
                    }
112
172
                    .construct()
113
172
                },
114
172
                superseded_authority_key,
115
172
            ))
116
172
        }
117

            
118
32
        let (authorities, superseded_keys) = inputs
119
172
            .map(|(vnum, vas)| {
120
172
                let (cae, lkey) = vote2consensus(&vas.authority, context.sig_hashes.vote(vnum)?)?;
121
172
                Ok::<_, Bug>((Some(cae), lkey))
122
172
            })
123
32
            .process_results(|i| i.filter_collect_unzip())?;
124

            
125
32
        Ok(ConsensusAuthoritySection {
126
32
            superseded_keys,
127
32
            ..ConsensusAuthoritySectionConstructor { authorities }.construct()
128
32
        })
129
32
    }
130
}
131

            
132
/// Computes a consensus from the input votes
133
///
134
/// ### Security
135
///
136
/// It is the caller's responsibility to check that each of the `votes`
137
/// came from a distinct recognised authority.
138
/// Normally this will be assured by the APIs in `tor-netdoc`,
139
/// particularly [`netstatus::vote::NetworkStatusUnverified::verify`].
140
pub fn compute_consensus_from_votes<'v>(
141
    n_authorities: usize,
142
    votes: impl Iterator<Item = VoteInput<'v>> + Clone,
143
) -> Result<Consensuses, ConsensusError> {
144
    let method = compute_method(votes.clone().map(|v| &v.vote.preamble.consensus_methods))?;
145
    compute_consensus_from_votes_method(method, n_authorities, votes)
146
}
147

            
148
/// Select the consensus method
149
///
150
/// <https://spec.torproject.org/dir-spec/computing-consensus.html#consensus-method-list>
151
5
fn compute_method<'v>(
152
5
    votes: impl Iterator<Item = &'v netstatus::ConsensusMethods> + Clone,
153
5
) -> Result<SupportedConsensusMethod, ConsensusError> {
154
    let all_methods: HashSet<ConsensusMethod> =
155
20
        votes.clone().flat_map(|s| s.iter().copied()).collect();
156

            
157
5
    Ok(all_methods
158
5
        .into_iter()
159
13
        .try_filter(|m| {
160
52
            StrictlyMoreThanTwoThirds::is_true_for_enough_of(votes.clone(), |v| {
161
52
                Ok::<_, Bug>(v.contains(m))
162
52
            })
163
13
        })
164
5
        .process_results(|candidates| candidates.max())?
165
1
        .unwrap_or_else(|| {
166
1
            let m: ConsensusMethod = SupportedConsensusMethod::MAX.into();
167
1
            warn!("no consensus method in common amongst >2/3 of authorities, using {m}!");
168
1
            m
169
1
        })
170
3
        .try_into()?)
171
5
}
172

            
173
/// Computes a consensus from the input votes, for a specific method
174
///
175
/// ### Security
176
///
177
/// See [`compute_consensus_from_votes`].
178
16
pub fn compute_consensus_from_votes_method<'v>(
179
16
    method: SupportedConsensusMethod,
180
16
    n_authorities: usize,
181
16
    votes: impl Iterator<Item = VoteInput<'v>>,
182
16
) -> Result<Consensuses, ConsensusError> {
183
16
    let (votes, nicknames, sig_hashes) = votes
184
86
        .map(|vi| (vi.vote, vi.nickname, vi.sig_hashes))
185
        .collect();
186
16
    let context = ConsensusCommonContext {
187
16
        method,
188
16
        n_authorities,
189
16
        votes,
190
16
        nicknames,
191
16
        sig_hashes,
192
16
    };
193
16
    let context = ConsensusContextRefs {
194
16
        context: &context,
195
16
        computed: &(),
196
16
    };
197
16
    let (plain, md) = <netstatus::vote::NetworkStatus as ConsensusesFromVotes<()>>::consensuses(
198
16
        context,
199
16
        context
200
16
            .votes
201
16
            .iter_enumerated()
202
20908
            .map(|(vnum, vote)| (vnum, *vote)),
203
    )?;
204
16
    Ok(Consensuses { plain, md })
205
16
}
206

            
207
#[cfg(test)]
208
pub(crate) mod test {
209
    // @@ begin test lint list maintained by maint/add_warning @@
210
    #![allow(clippy::bool_assert_comparison)]
211
    #![allow(clippy::clone_on_copy)]
212
    #![allow(clippy::dbg_macro)]
213
    #![allow(clippy::mixed_attributes_style)]
214
    #![allow(clippy::print_stderr)]
215
    #![allow(clippy::print_stdout)]
216
    #![allow(clippy::single_char_pattern)]
217
    #![allow(clippy::unwrap_used)]
218
    #![allow(clippy::unchecked_time_subtraction)]
219
    #![allow(clippy::useless_vec)]
220
    #![allow(clippy::needless_pass_by_value)]
221
    #![allow(clippy::string_slice)] // See arti#2571
222
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
223
    use super::*;
224
    use std::collections::BTreeSet;
225
    use tor_netdoc::parse2::NetdocParseableUnverified;
226

            
227
    /// Ensure that every rs that has an md digest, has one for `method`
228
    ///
229
    /// Needed because sometimes the test data (which is from the live network)
230
    /// will have votes none of which advertise (and thus, contain md hashes for)
231
    /// our selected consensus method (usually, the maximum *we* support).
232
    ///
233
    /// Fudge every rs in the vote, copying the digest(s) from the maximum supported.
234
    ///
235
    /// Of course the resulting digests might be lies, since the actual new method might
236
    /// involve generating *different* mds.  But that doesn't matter here
237
    /// in the consensus calculation, where we sees only md digests, not actual mds.
238
    /// And, discrepancies due to different voters voting different methods
239
    /// and thus different digests, are impossible with for `compute-test`,
240
    /// since tht bases all the test votes on the same input vote.
241
    fn populate_md_digests_for_method(
242
        our_method: SupportedConsensusMethod,
243
        vote: &mut netstatus::vote::NetworkStatus,
244
    ) {
245
        let vote_max_method = vote
246
            .preamble
247
            .consensus_methods
248
            .iter()
249
            .copied()
250
            .max()
251
            .expect("no methods in vote");
252
        for rs in &mut vote.routers {
253
            // `IdentifiedDigest`s in this rs for consensus method `needle`
254
            let for_method = |needle| {
255
                netstatus::RouterStatusMdDigestsVote::iter_cross_product_digests(&rs.m)
256
                    .filter(move |(m, _)| *m == needle)
257
                    .map(|(_, d)| d)
258
            };
259

            
260
            if for_method(*our_method).next().is_some() {
261
                continue;
262
            }
263
            let add_consensus_methods = [*our_method].into_iter().collect::<BTreeSet<_>>().into();
264

            
265
            let add_digests = for_method(vote_max_method).collect_vec();
266
            if add_digests.is_empty() {
267
                continue;
268
            };
269

            
270
            rs.m.push(construct! {
271
                netstatus::RouterStatusMdDigestsVote {
272
                    add. consensus_methods, digests;
273
                } {
274
                }
275
            });
276
        }
277
    }
278

            
279
    /// Compute a consensus from votes, allowing mutation of test data and bespoke checks
280
    ///
281
    /// Can be used for testing individual consensus elements:
282
    ///
283
    ///  * Use `edit_votes` to install test data into vote fields.
284
    ///  * Use `check_output` to check the output field is as expected.
285
    ///
286
    /// `edit_vote` gets the vote index (within `0..n_votes`),
287
    /// (as a `usize` rather than `VoterNum`, for test cases' convenience.)
288
    ///
289
    /// The basis votes are all the same: the vote from `testata-live`.
290
    pub(crate) fn compute_test(
291
        n_votes: usize,
292
        n_authorities: usize,
293
        mut edit_vote: impl FnMut(usize, &mut netstatus::vote::NetworkStatus) -> anyhow::Result<()>,
294
        check_output: impl FnOnce(Consensuses) -> anyhow::Result<()>,
295
    ) {
296
        assert!(n_votes <= n_authorities);
297
        let method = SupportedConsensusMethod::MAX;
298

            
299
        let (vote_base, sigs) =
300
            tor_netdoc::testdata_live::netstatus_vote_unverified().inspect_unverified();
301
        let sig_hashes = &sigs.hashes;
302

            
303
        #[allow(clippy::useless_conversion)]
304
        let votes = (0..n_votes)
305
            .into_iter()
306
            .map(move |vnum| {
307
                let mut vote = vote_base.clone();
308
                populate_md_digests_for_method(method, &mut vote);
309
                edit_vote(vnum, &mut vote).expect("vote edit failed");
310
                let nick: Nickname = format!("A{vnum}").parse().unwrap();
311
                (vote, nick)
312
            })
313
            .collect_vec();
314
        let output = compute_consensus_from_votes_method(
315
            method,
316
            n_authorities,
317
            votes.iter().map(|(vote, nickname)| VoteInput {
318
                vote,
319
                nickname,
320
                sig_hashes,
321
            }),
322
        )
323
        .expect("compute consensus");
324

            
325
        check_output(output).expect("check output");
326
    }
327

            
328
    #[test]
329
    #[traced_test]
330
    fn compute_for_test_vanilla() {
331
        compute_test(
332
            3,
333
            4,
334
            |_, _| Ok(()),
335
            |Consensuses { plain, md }| {
336
                dbg!(&plain);
337
                dbg!(&md);
338
                Ok(())
339
            },
340
        );
341
    }
342

            
343
    #[test]
344
    #[traced_test]
345
    fn select_method() {
346
        const N_VOTES: usize = 4;
347
        let max: u32 = SupportedConsensusMethod::MAX.0;
348

            
349
        fn check(exp: Result<u32, u32>, methods_and_counts: &[(u32, usize)]) {
350
            let votes = (0..N_VOTES)
351
                .map(|vnum| {
352
                    let methods = methods_and_counts
353
                        .iter()
354
                        .filter_map(|&(method, count)| {
355
                            (vnum < count).then_some(ConsensusMethod(method))
356
                        })
357
                        .collect();
358
                    netstatus::ConsensusMethods { methods }
359
                })
360
                .collect_vec();
361

            
362
            println!("votes = {votes:#?}");
363

            
364
            let exp = exp
365
                .map(|n| SupportedConsensusMethod::try_from(ConsensusMethod(n)).unwrap())
366
                .map_err(|n| SupportedConsensusMethod::try_from(ConsensusMethod(n)).unwrap_err());
367

            
368
            let got = compute_method(votes.iter()).map_err(|e| match e {
369
                ConsensusError::UnsupportedMethodChosen(u) => u,
370
                other => panic!("unexpected error {other:?}"),
371
            });
372

            
373
            assert_eq!(got, exp);
374
        }
375

            
376
        check(Err(10), &[(10, 4)]);
377
        check(Err(20), &[(10, 4), (20, 3), (max, 1)]);
378
        check(Err(20), &[(10, 4), (20, 3), (max, 2)]);
379
        check(Ok(max), &[(10, 4), (20, 3), (max, 3)]);
380
        check(Ok(max), &[(10, 2), (20, 2), (max, 2)]);
381
    }
382
}