1
//! Calculate consensus preamble
2

            
3
use super::*;
4

            
5
impl ConsensusesFromVotes<()> for netstatus::vote::Preamble {
6
    type PlainOutput = netstatus::plain::Preamble;
7
    type MdOutput = netstatus::md::Preamble;
8

            
9
17
    fn consensuses<'i>(
10
17
        context: ConsensusContextRefs<()>,
11
17
        inputs: impl Iterator<Item = (VoterNum, &'i Self)> + Clone,
12
17
    ) -> Result<(Self::PlainOutput, Self::MdOutput), ConsensusError>
13
17
    where
14
17
        Self: 'i,
15
    {
16
17
        calc! { both.lifetime }
17
17
        calc! { both.consensus_method = ((*context.method).into(),) }
18
17
        calc! { both.consensus_methods = NotPresent }
19
17
        calc! { both.published = NotPresent }
20
17
        calc! { both.proto_statuses }
21
17
        calc! { md,plain .known_flags <+ doc_relay_flags_union }
22
17
        calc! { md,plain .params <+ netparams_preamble_aggregate }
23

            
24
        // shared-rand-* in output come from:
25
        //   - lifetime and therefore timing, as determined for this vote
26
        //   - netparams, as determined for this vote
27
        //   - authority section's shared-rand-*, in votes
28
        let plain_shared_rand;
29
        let md_shared_rand;
30
        {
31
17
            let computed = SrvAC {
32
17
                lifetime: &plain_lifetime,
33
17
                params: &plain_params,
34
17
            };
35
17
            let context = context.with_computed(&computed);
36
17
            let inputs = context
37
17
                .votes
38
17
                .iter_enumerated()
39
364
                .map(|(vnum, v)| (vnum, &v.authority.authority));
40
17
            calc_assign! { both.shared_rand }
41
        };
42

            
43
17
        calc! { both.voting_delay }
44
17
        calc! { both.client_versions }
45
17
        calc! { both.server_versions }
46

            
47
17
        Ok(construct_both! {
48
17
            netstatus::plain::Preamble, netstatus::md::Preamble {
49
17
                both. lifetime, consensus_method, consensus_methods, published;
50
17
                both. known_flags, params, proto_statuses, voting_delay;
51
17
            } {
52
17
                both. client_versions, server_versions, shared_rand;
53
17
            }
54
17
        })
55
17
    }
56
}
57

            
58
impl<AC> Aggregate<AC> for netstatus::Lifetime {
59
    type Output = Self;
60

            
61
34
    fn aggregate<'i>(
62
34
        context: ConsensusContextRefs<AC>,
63
34
        inputs: impl ComponentInVotes<&'i Self>,
64
34
    ) -> Result<Self, ConsensusError>
65
34
    where
66
34
        Self: 'i,
67
    {
68
34
        calc! { out.valid_after <+ functions::low_median }
69
34
        calc! { out.fresh_until <+ functions::low_median }
70
34
        calc! { out.valid_until <+ functions::low_median }
71

            
72
        // We want these to be in increasing order, or the resulting consensus is nonsensical.
73
        // This could only be violated if some of the inputs votes didn't have them in
74
        // increasing order.   TODO arti#2786
75

            
76
34
        Ok(construct! {
77
34
            netstatus::Lifetime {
78
34
                out. valid_after, fresh_until, valid_until;
79
34
            } {
80
34
            }
81
34
        })
82
34
    }
83
}
84

            
85
impl<AC> Aggregate<AC> for netstatus::VotingDelay {
86
    type Output = Self;
87

            
88
34
    fn aggregate<'i>(
89
34
        context: ConsensusContextRefs<AC>,
90
34
        inputs: impl ComponentInVotes<&'i Self>,
91
34
    ) -> Result<Self, ConsensusError>
92
34
    where
93
34
        Self: 'i,
94
    {
95
        // Spec just says "median".  Low median will do; it's in seconds.
96
34
        calc! { out.vote_seconds <+ functions::low_median }
97
34
        calc! { out.dist_seconds <+ functions::low_median  }
98
34
        Ok(construct! {
99
34
            netstatus::VotingDelay {
100
34
                out. vote_seconds, dist_seconds;
101
34
            } {
102
34
            }
103
34
        })
104
34
    }
105
}
106

            
107
/// Calculate the union of two `DocRelayFlags`z
108
34
pub(super) fn doc_relay_flags_union<'i>(
109
34
    _context: ConsensusContextRefs<()>,
110
34
    inputs: impl ComponentInVotes<&'i DocRelayFlags>,
111
34
) -> Result<DocRelayFlags, ConsensusError> {
112
34
    Ok(inputs
113
34
        .votes()
114
182
        .map(|flags| flags.iter_incl_unknown())
115
        .flatten_ok()
116
34
        .process_results(|flag_iters| flag_iters.unique().collect())?)
117
34
}
118

            
119
/// Calculate the `params` line in a consensus
120
//
121
// Not `impl Aggregate` because NetParams is a very general type used in all sorts of
122
// places, and we don't want them to get this impl by mistake.
123
34
pub(super) fn netparams_preamble_aggregate<'i>(
124
34
    context: ConsensusContextRefs<()>,
125
34
    inputs: impl ComponentInVotes<&'i NetParams>,
126
34
) -> Result<NetParams, ConsensusError> {
127
34
    Ok(inputs
128
34
        .votes()
129
182
        .flat_map(|i| i.without_defaults().iter().map(|(k, _v)| k))
130
        .unique()
131
1538
        .filter_map(|k| {
132
            // "every keyword on which a majority of authorities (total
133
            // authorities, not just those participating in this vote) voted
134
            // on, or if at least three authorities voted for that parameter.
135
            const MIN_THRESH: usize = 3;
136

            
137
1538
            let opinions = inputs
138
1538
                .votes()
139
16476
                .filter_map(|i| i.without_defaults().get(k))
140
                .copied();
141
1538
            let n_opinions = opinions.clone().count();
142
1538
            let want = context.is_enough_of_all_auths::<MoreThanHalf>(n_opinions)
143
90
                || n_opinions >= MIN_THRESH;
144
1538
            if !want {
145
                return None;
146
1538
            }
147

            
148
            const_assert!(MIN_THRESH > 0);
149
1538
            let out = functions::low_median_raw(opinions)
150
1538
                .expect("more than half is always >0, and so is MIN_THRESH");
151
1538
            Some((String::from(k), out))
152
1538
        })
153
        .collect::<NetParamValues>()
154
        .into())
155
34
}
156

            
157
impl<AC> Aggregate<AC> for netstatus::RecommendedTorVersions {
158
    type Output = Self;
159

            
160
68
    fn aggregate<'i>(
161
68
        _context: ConsensusContextRefs<AC>,
162
68
        inputs: impl ComponentInVotes<&'i Self>,
163
68
    ) -> Result<Self, ConsensusError>
164
68
    where
165
68
        Self: 'i,
166
    {
167
3276
        let inputs = inputs.votes().filter(|i| i.is_known());
168

            
169
68
        Ok(inputs
170
68
            .clone()
171
364
            .flat_map(|i| i.iter())
172
            .unique()
173
544
            .try_filter(|k| {
174
544
                MoreThanHalf::is_true_for_enough_of(
175
                    //
176
544
                    inputs.clone(),
177
2912
                    |i| Ok::<_, Bug>(i.contains(&**k)),
178
                )
179
544
            })
180
68
            .process_results(|ks| netstatus::RecommendedTorVersions::from_iter(ks))?
181
68
            .map_err(into_internal!(
182
                "passed through software version was invalid"
183
            ))?)
184
68
    }
185
}
186

            
187
impl Aggregate<()> for Arc<netstatus::ProtoStatuses> {
188
    type Output = Self;
189

            
190
34
    fn aggregate<'i>(
191
34
        context: ConsensusContextRefs<()>,
192
34
        inputs: impl ComponentInVotes<&'i Self>,
193
34
    ) -> Result<Self, ConsensusError>
194
34
    where
195
34
        Self: 'i,
196
    {
197
34
        calc! { out.client <+ protostatus_preamble_aggregate }
198
34
        calc! { out.relay <+ protostatus_preamble_aggregate }
199
34
        Ok(construct! {
200
34
            netstatus::ProtoStatuses {
201
34
            } {
202
34
                out. client, relay;
203
34
            }
204
34
        }
205
34
        .into())
206
34
    }
207
}
208

            
209
/// Calculate the `{recommended,required}-*-protocols` items in a consensus
210
///
211
/// Has the signature of [`Aggregate::aggregate`] for [`netstatus::ProtoStatus`].
212
/// Not `impl Aggregate` because `ProtoStatus` wants to be
213
/// handled quite differently in a routerstatus.
214
68
fn protostatus_preamble_aggregate<'i>(
215
68
    context: ConsensusContextRefs<()>,
216
68
    inputs: impl ComponentInVotes<&'i netstatus::ProtoStatus>,
217
68
) -> Result<netstatus::ProtoStatus, ConsensusError> {
218
136
    fn aggregate_by_threshold<'i, 'r>(
219
136
        context: ConsensusContextRefs<'r, ()>,
220
136
        inputs: impl ComponentInVotes<&'i tor_protover::Protocols>,
221
136
        threshold: impl Fn(&ConsensusCommonContext<'r>, usize) -> bool,
222
136
    ) -> Result<tor_protover::Protocols, ConsensusError> {
223
        // Uncompress the inputs into sets of `(Protocol, Value)`.
224
        //
225
        // This is kind of flabby, especially in allocations, but it has the virtue
226
        // of making the output calculation very obvious.
227
        //
228
        // Worst case total allocations (and number of cpu operations) is
229
        //   O( unknown_keyword_length * n_keywords * n_authorities * 64 )
230
        // or alternatively
231
        //   O( total_length_of_all_input_doc_items * 64 )
232
        // and the constant factor is 3 or 4 words.  See the comments for `Preotocols::iter_all`.
233
        //
234
        // We could save a factor of up to 64 in the worst case by using a bitmask representation
235
        // but tor-protover does not currently expose that in a suitable form,
236
        // and it would make the calculation less obvious.
237
        //
238
        let inputs: Vec<HashSet<(tor_protover::Protocol, tor_protover::Value)>> =
239
728
            inputs.votes().map(|i| i.iter_all().collect()).collect_vec();
240

            
241
136
        Ok(inputs
242
136
            .iter()
243
136
            .flatten()
244
136
            .unique()
245
1744
            .filter(|k| {
246
9320
                let n_y = inputs.iter().filter(|i| i.contains(k)).count();
247
1744
                threshold(&context, n_y)
248
1744
            })
249
            .cloned()
250
            .collect())
251
136
    }
252

            
253
68
    calc! {
254
68
        out.recommended <+ aggregate_by_threshold;
255
68
        , ConsensusCommonContext::is_enough_of_all_auths::<MoreThanHalf>
256
    }
257
68
    calc! {
258
68
        out.required <+ aggregate_by_threshold;
259
68
        , ConsensusCommonContext::is_enough_of_all_auths::<AtLeastTwoThirds>
260
    }
261

            
262
68
    Ok(construct! {
263
68
        netstatus::ProtoStatus {
264
68
        } {
265
68
            out. recommended, required;
266
68
        }
267
68
    })
268
68
}
269

            
270
#[cfg(test)]
271
mod test {
272
    // @@ begin test lint list maintained by maint/add_warning @@
273
    #![allow(clippy::bool_assert_comparison)]
274
    #![allow(clippy::clone_on_copy)]
275
    #![allow(clippy::dbg_macro)]
276
    #![allow(clippy::mixed_attributes_style)]
277
    #![allow(clippy::print_stderr)]
278
    #![allow(clippy::print_stdout)]
279
    #![allow(clippy::single_char_pattern)]
280
    #![allow(clippy::unwrap_used)]
281
    #![allow(clippy::unchecked_time_subtraction)]
282
    #![allow(clippy::useless_vec)]
283
    #![allow(clippy::needless_pass_by_value)]
284
    #![allow(clippy::string_slice)] // See arti#2571
285
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
286
    use super::*;
287
    use crate::consensus::test::compute_test;
288

            
289
    #[test]
290
    fn protocols() {
291
        use tor_protover::Protocols;
292

            
293
        let p = |s| Protocols::from_str_c_compatible(s).unwrap();
294

            
295
        let inputs = [
296
            // 6 voters
297
            //
298
            // For capabilities `counting=K-6`, value K is voted for by K voters.
299
            p("Link=1 counting=1-6"),
300
            p("Link=1 counting=2-6 req=1 rec=1 neither=1"),
301
            p("Link=1 counting=3-6 req=1 rec=1 neither=1"),
302
            p("Link=1 counting=4-6 req=1 rec=1 neither=1"),
303
            p("Link=1 counting=5-6 req=1 rec=1"),
304
            p("Link=1 counting=6 req=1"),
305
        ];
306

            
307
        let (exp_recommended, exp_required) = (
308
            p("Link=1 counting=4-6 req=1 rec=1"),
309
            p("Link=1 counting=5-6 req=1"),
310
        );
311

            
312
        macro_rules! field { { $cs:ident, $field:ident } => { paste! {
313

            
314
            compute_test(
315
                inputs.len(),
316
                7,
317
                |vnum, vote| {
318
                    let mut ps = (*vote.preamble.proto_statuses).clone();
319
                    ps.$cs.$field = inputs[vnum].clone();
320
                    vote.preamble.proto_statuses = ps.into();
321
                    Ok(())
322
                },
323
                |Consensuses { plain, md: _ }| {
324
                    let got = &plain.preamble.proto_statuses.$cs.$field;
325
                    let exp = &[< exp_ $field >];
326
                    assert_eq!(
327
                        got,
328
                        exp,
329
                        "{}\n got={}\n exp={}",
330
                        stringify!($cs $field),
331
                        got.to_string(),
332
                        exp.to_string(),
333
                    );
334
                    Ok(())
335
                },
336
            );
337

            
338
        } } }
339

            
340
        field! { client, recommended }
341
        field! { client, required }
342
        field! { relay, recommended }
343
        field! { relay, required }
344
    }
345
}