1
//! Traits and common types for for calculating consensuses from votes
2

            
3
use super::*;
4

            
5
/// Report a problem with a vote.
6
//
7
// TODO DIRAUTH this should be rate limited or something maybe?
8
// TODO DIRAUTH arguably this is more serious than debug, but what about compatibility?
9
macro_rules! bad_vote { { $context:expr, $vnum:expr, $($msg:tt)* } => { {
10
    let vnum: VoterNum = $vnum;
11
    debug!(
12
        "bad vote from {}: {}",
13
        $context.nicknames.get(vnum)
14
1
            .map(|n| n as &dyn Display)
15
            .unwrap_or(&format_args!("{vnum:?}")),
16
        format_args!($($msg)*),
17
    );
18
} } }
19

            
20
/// Voter number
21
///
22
/// Valid only within a particular consensus calculation round.
23
/// Corresponds to the index in `ConsensusesContext.votes`.
24
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] //
25
#[derive(derive_more::From, derive_more::Into)]
26
pub(super) struct VoterNum(pub usize);
27

            
28
/// A set of voters
29
pub(super) type VoterSet = HashSet<VoterNum>;
30

            
31
/// Components within a vote (trait alias)
32
///
33
/// Input to [`ConsensusesFromVotes::consensuses`] and [`Aggregate::aggregate`].
34
///
35
/// Do not implement this trait manually.
36
//
37
// Normally it is a better API to take `IntoIterator` than `Iterator`, since that is
38
// more convenient to use.
39
//
40
// Here, that might be `IntoIterator + Copy`: our iterators typically yield references to
41
// component pieces, generated by field projection on votes.
42
//
43
// But: that merely replaces `.iter()` at call sites of this trait with `.into_iter()`,
44
// and when we make a `ComponentInVotes` it's typically already an `Iterator` anyway,
45
// so there's no convenience benefit.
46
//
47
// Worse, we don't want to insist on `Copy` iterators
48
// since there might be cases where the iterator would be only `Clone`;
49
// and, `IntoIterator + Clone` would mean writing `.clone().into_iter()` or some such.
50
pub(super) trait ComponentInVotes<T>: Iterator<Item = (VoterNum, T)> + Clone {
51
    /// Iterate over the inputs - return a clone of the input iterator
52
    ///
53
    /// Convenience method so that we can write `.iter()` rather than `.clone()`,
54
    /// which latter feels a bit weird.
55
    ///
56
    /// `Iterator` itself doesn't have a `.iter()` method and we generally work with
57
    /// `impl ComponentInVotes`, so there is no resulting method resolution ambiguity.
58
2677
    fn iter(&self) -> Self {
59
2677
        self.clone()
60
2677
    }
61

            
62
    /// Iterate over the voted values
63
    ///
64
    /// Convenience method equivalent to `.iter().map(|(_vnum, v)| v)`.
65
2829
    fn votes(&self) -> impl Iterator<Item = T> + Clone {
66
2829
        self.clone().map(|(_vnum, v)| v)
67
2829
    }
68
}
69
impl<I, T> ComponentInVotes<T> for I where I: Iterator<Item = (VoterNum, T)> + Clone {}
70

            
71
/// Actual context for computing a field: global context, plus already-computed values
72
///
73
/// Shared references, so `Copy`.
74
#[derive(Debug, Educe, derive_more::Deref)]
75
#[educe(Clone, Copy)]
76
pub(super) struct ConsensusContextRefs<'r, AlreadyComputed> {
77
    /// The `ConsensusContext`, the same for all parts of the computation
78
    ///
79
    /// This is usually the part of the context that's wanted, so
80
    /// for convenience, `ContextAndComputed` derefs to this.
81
    #[deref]
82
    pub context: &'r ConsensusCommonContext<'r>,
83

            
84
    /// Stuff we computed earlier
85
    ///
86
    /// This is needed because some parts of the consensus depend on other parts.
87
    /// For example, the `w` item in a routerstatus depends on network parameters
88
    /// (as found in the preamble of *this* consensus).
89
    ///
90
    /// impls that don't need any precomputed data should be blanket over `AlreadyComputed`.
91
    ///
92
    /// Generally, when this isn't `()`, we have both the plain and md flavours
93
    /// available, but they basically contain the same information.
94
    /// So in each case we pass only the plain flavour as the "already computed".
95
    //
96
    // The alternatives to this would be:
97
    //  a. Build the consensus in mutable variables.  But there are a lot of required
98
    //     fields, so that is quite awkward.
99
    //  b. Have some separate mutable variables in the context, and pass them mutably
100
    //     through all the calculations.
101
    //
102
    // Both a and b would make it easy to write the kind of "didn't assign to
103
    // this variable yet" ordering bugs which are common in languages and
104
    // progrms with mutable globals.
105
    //
106
    //  c. Do some kind of ad-hoc calculation beforehand, and put the answers in
107
    //     `context`.  The ad-hoc calculation couldn't use any of our infrastructure
108
    //     since that requires a `ConsensusContext` which we wouldn't have yet.
109
    //
110
    //  d. Put dummy data in the awkward fields, and fix it up later
111
    //     after the systematic calculation has produced a whole consensus.
112
    //     This makes it easy to accidentally use or emit uninitialised data,
113
    //     and is really a form of (a)/(b).
114
    //
115
    pub computed: &'r AlreadyComputed,
116
}
117

            
118
/// Component of a vote, from which a corresponding consensus component can be calculated
119
///
120
/// Implemented on the *input*, ie the vote or part of a vote.
121
///
122
/// Implement this trait directly when the different flavours need different outputs.
123
///
124
/// Implement [`Aggregate`] instead, if the flavour doesn't matter.
125
/// There is a blanket implementation of `ConsensusesFromVotes` for any [`Aggregate`].
126
pub(super) trait ConsensusesFromVotes<AlreadyComputed> {
127
    /// The plain-flavourconsensus component
128
    type PlainOutput: Sized;
129
    /// The microdescriptor consensus component
130
    type MdOutput: Sized;
131

            
132
    /// Calculate the consensus components corresponding to the `Self` in the votes
133
    ///
134
    /// Takes as input the vote components (one per vote), and
135
    /// returns the consensus components, as a pair, one for each flavour.
136
    ///
137
    /// `inputs` is an iterator of references to the relevant parts of each vote.
138
    fn consensuses<'i>(
139
        context: ConsensusContextRefs<AlreadyComputed>,
140
        inputs: impl ComponentInVotes<&'i Self>,
141
    ) -> Result<(Self::PlainOutput, Self::MdOutput), ConsensusError>
142
    where
143
        Self: 'i;
144
}
145

            
146
/// Component of a vote from which a flavour-independent consensus component can be calculated
147
///
148
/// Implemented on the *input*, ie the vote or part of a vote.
149
///
150
/// Use `[ConsensusesFromVotes`] when flavour is relevant.
151
pub(super) trait Aggregate<AC>: Sized {
152
    /// The output (consensus) component type.  Often `Self`.
153
    type Output: Sized;
154

            
155
    /// Calculate the consensus component corresponding to the `Self` in the votes
156
    ///
157
    /// Takes as input the vote components (one per vote), and
158
    /// returns the corresponding consensus components.
159
    ///
160
    /// `inputs` is an iterator of references to the relevant parts of each vote.
161
    fn aggregate<'i>(
162
        context: ConsensusContextRefs<AC>,
163
        inputs: impl ComponentInVotes<&'i Self>,
164
    ) -> Result<Self::Output, ConsensusError>
165
    where
166
        Self: 'i;
167
}
168

            
169
impl<AC, V: Aggregate<AC>> ConsensusesFromVotes<AC> for V {
170
    type PlainOutput = V::Output;
171
    type MdOutput = V::Output;
172

            
173
260
    fn consensuses<'i>(
174
260
        context: ConsensusContextRefs<AC>,
175
260
        inputs: impl ComponentInVotes<&'i Self>,
176
260
    ) -> Result<(Self::PlainOutput, Self::MdOutput), ConsensusError>
177
260
    where
178
260
        Self: 'i,
179
    {
180
        Ok((
181
260
            V::aggregate(context, inputs.iter())?,
182
260
            V::aggregate(context, inputs)?,
183
        ))
184
260
    }
185
}
186

            
187
impl<'r> ConsensusCommonContext<'r> {
188
    /// Construct a `ConsensusContextRefs` with a particular "already computed" value
189
    ///
190
    /// (Also available on `ConsensusContextRefs` via deref.)
191
193
    pub(super) fn with_computed<AC>(&'r self, ac: &'r AC) -> ConsensusContextRefs<'r, AC> {
192
193
        ConsensusContextRefs {
193
193
            context: self,
194
193
            computed: ac,
195
193
        }
196
193
    }
197
}
198

            
199
/// Error during calculation of a consensus
200
///
201
/// Normally errors at this stage should be avoided, because that would prevent
202
/// us from participating in the consensus.
203
#[derive(thiserror::Error, Clone, Debug)]
204
#[non_exhaustive]
205
pub enum ConsensusError {
206
    /// Tried to calculate a consensus from no votes!
207
    #[error("tried to calculate a consensus from no votes!")]
208
    NoVotes,
209

            
210
    /// Input votes implied unreasonable values
211
    #[error("votes imply unreasonable consensus contents")]
212
    Unreasonable(String),
213

            
214
    /// Internal error in calculation algorithm
215
    #[error("chosen consensus method is unsupported")]
216
    UnsupportedMethodChosen(#[from] UnsupportedConsensusMethod),
217

            
218
    /// Internal error in calculation algorithm
219
    #[error("bug calculating a consensus")]
220
    Internal(#[from] Bug),
221
}
222

            
223
impl From<crate::shared_random::UnreasonableTime> for ConsensusError {
224
    fn from(e: crate::shared_random::UnreasonableTime) -> Self {
225
        ConsensusError::Unreasonable(e.to_string())
226
    }
227
}
228

            
229
#[ext(name = TiSliceExt)]
230
pub(super) impl<V> TiSlice<VoterNum, V> {
231
    /// Get the value from one of the votes
232
    ///
233
    /// Convenience method for `.get(vnum)` which avoids recapitulating the error handling.
234
5436
    fn vote(&self, vnum: VoterNum) -> Result<&V, Bug> {
235
5436
        self.get(vnum)
236
            .ok_or_else(|| internal!("{vnum:?} out of range"))
237
5436
    }
238
}
239

            
240
/// "Global" inputs for calculating consensus from votes
241
#[derive(Debug, Clone)]
242
pub(super) struct ConsensusCommonContext<'r> {
243
    /// The consensus method for which to generate a consensus
244
    pub method: SupportedConsensusMethod,
245

            
246
    /// The number of authorities (>= the number of votes)
247
    pub n_authorities: usize,
248

            
249
    /// The input votes (in their entirity)
250
    pub votes: TiVec<VoterNum, &'r netstatus::vote::NetworkStatus>,
251

            
252
    /// The nicknames of the authorities, used only for logging/reporting
253
    pub nicknames: TiVec<VoterNum, &'r Nickname>,
254

            
255
    /// The votes' digests (in the same `VoterNum` order)
256
    pub sig_hashes: TiVec<VoterNum, &'r netstatus::DirectorySignaturesHashesAccu>,
257
}
258

            
259
impl<'r> ConsensusCommonContext<'r> {
260
    /// Is `n_some_voters` a big enough proprtion of all the authorities, according to `rule`?
261
3427
    pub(super) fn is_enough_of_all_auths<Rule: ThresholdRule>(&self, n_some_voters: usize) -> bool {
262
3427
        Rule::is_enough_of(n_some_voters, self.n_authorities)
263
3427
    }
264
}
265

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

            
285
    impl ConsensusCommonContext<'static> {
286
        pub(crate) fn new_for_test() -> Self {
287
            // TODO obtain (memoised?) from testdata2, using its constructor, when we have one
288
            ConsensusCommonContext {
289
                method: SupportedConsensusMethod::MAX,
290
                n_authorities: 0,
291
                votes: ti_vec![],
292
                nicknames: ti_vec![],
293
                sig_hashes: ti_vec![],
294
            }
295
        }
296
    }
297

            
298
    #[test]
299
    fn threshold_of_all_auths() {
300
        use crate::threshold::test::ExpectOneOutOfTwo;
301

            
302
        let mut context = ConsensusCommonContext::new_for_test();
303
        context.n_authorities = 2;
304
        context.is_enough_of_all_auths::<ExpectOneOutOfTwo>(1);
305
    }
306
}