1
//! Handling thresholds like "at least two thirds"
2
//!
3
//! TODO maybe this should be promoted somewhere?
4

            
5
use crate::internal_prelude::*;
6

            
7
/// `>1/2`: `n_y` is strictly more than half of `n_total` - i.e., a majority
8
///
9
/// Threshold rule token, implementing [`ThresholdRule`].
10
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
11
pub(crate) struct MoreThanHalf;
12

            
13
/// `>=2/3`: `n_y` is at least two thirds of `n_total`
14
///
15
/// Threshold rule token, implementing [`ThresholdRule`].
16
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
17
pub(crate) struct AtLeastTwoThirds;
18

            
19
/// `>2/3`: `n_y` is strictly more than two thirds of `n_total`
20
///
21
/// Threshold rule token, implementing [`ThresholdRule`].
22
///
23
/// Used only for selecting the best consensus method,
24
/// <https://spec.torproject.org/dir-spec/computing-consensus.html#consensus-method-list>
25
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
26
pub(crate) struct StrictlyMoreThanTwoThirds;
27

            
28
/// Threshold rule, such as "at least two thirds"
29
///
30
/// Implemented for unit token types [`MoreThanHalf`] [`AtLeastTwoThirds`].
31
///
32
/// Use these token types, instead of open-coding,
33
/// to avoid rounding and off-by-one bugs.
34
///
35
/// The rule types can be used with methods from this trait
36
/// and also with `ConsensusesCommonContext::is_enough_of_all_auths`.
37
///
38
// The trait allows sharing code for checking an iterator,
39
// or checking against a number of authorities:
40
// there are going to be three rules, and at least three possible testing contexts,
41
// of which we may use only a subset.  This way it can all be regular.
42
//
43
/// The token types do not ever need to be constructed -
44
/// they are always used as generic parameters.
45
// This facilitates use with, eg, the consensus `calc!` macro.)
46
pub(crate) trait ThresholdRule {
47
    /// Is `n_y` enough of `n_total`, according to a threshold rule ?
48
    ///
49
    /// # Correctness - take care with argument order!
50
    ///
51
    /// Prefer
52
    /// [`is_true_for_enough_of`](ThresholdRule::is_true_for_enough_of)
53
    /// or
54
    /// `ConsensusesCommonContext::is_enough_of_all_auths`
55
    /// because those functions eliminate that possible error.
56
    fn is_enough_of(n_y: usize, n_total: usize) -> bool;
57

            
58
    /// Is `predicate` true for enough of the values in `iterator`?
59
    //
60
    // The signature of this function is complicated, compared to the alternative
61
    //   fn is_for_more_than_half_of(some: usize, all: usize)
62
    // but makes it impossible to accidentally swap the arguments, or get the wrong
63
    // total value, or some such.
64
    //
65
    // We can't have an infallible version of this, because it needs to throw `Bug`
66
    // on arithmetic overflow.
67
558
    fn is_true_for_enough_of<I, E>(
68
558
        iterator: impl IntoIterator<Item = I>,
69
558
        predicate: impl Fn(I) -> Result<bool, E>,
70
558
    ) -> Result<bool, E>
71
558
    where
72
558
        E: From<Bug>,
73
    {
74
558
        let mut all = 0;
75
558
        let mut yes = 0;
76
558
        for i in iterator {
77
2966
            all.try_add_assign(1)?;
78
2966
            if predicate(i)? {
79
2950
                yes.try_add_assign(1)?;
80
16
            }
81
        }
82
558
        Ok(Self::is_enough_of(yes, all))
83
558
    }
84
}
85

            
86
impl ThresholdRule for MoreThanHalf {
87
3534
    fn is_enough_of(n_y: usize, n_total: usize) -> bool {
88
        // This way of writing it avoids any possibility of over/under-flow
89
        //
90
3534
        n_y > n_total / 2
91
3534
    }
92
}
93

            
94
impl ThresholdRule for AtLeastTwoThirds {
95
1019
    fn is_enough_of(n_y: usize, n_total: usize) -> bool {
96
        // Overflow ought to be impossible since it would involve an unreasonable number
97
        // of authorities, but in that case return `fale`.
98
        //
99
        // The alternative would be to suppress the rule against possibly-panicking arithmetic,
100
        // which would impose an additional review burden.
101
1019
        let thresh = match n_total.checked_mul(2) {
102
1019
            Some(y) => y,
103
            None => return false,
104
        }
105
1019
        .div_ceil(3);
106

            
107
1019
        n_y >= thresh
108
1019
    }
109
}
110

            
111
impl ThresholdRule for StrictlyMoreThanTwoThirds {
112
288
    fn is_enough_of(n_y: usize, n_total: usize) -> bool {
113
        // Very similar to `AtLeastTwoThirds::is_enough_of`, but needs different rounding.
114
288
        let thresh = match n_total.checked_mul(2) {
115
288
            Some(y) => y,
116
            None => return false,
117
288
        } / 3;
118

            
119
288
        n_y > thresh
120
288
    }
121
}
122

            
123
#[cfg(test)]
124
pub(crate) mod test {
125
    // @@ begin test lint list maintained by maint/add_warning @@
126
    #![allow(clippy::bool_assert_comparison)]
127
    #![allow(clippy::clone_on_copy)]
128
    #![allow(clippy::dbg_macro)]
129
    #![allow(clippy::mixed_attributes_style)]
130
    #![allow(clippy::print_stderr)]
131
    #![allow(clippy::print_stdout)]
132
    #![allow(clippy::single_char_pattern)]
133
    #![allow(clippy::unwrap_used)]
134
    #![allow(clippy::unchecked_time_subtraction)]
135
    #![allow(clippy::useless_vec)]
136
    #![allow(clippy::needless_pass_by_value)]
137
    #![allow(clippy::string_slice)] // See arti#2571
138
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
139
    #![allow(clippy::arithmetic_side_effects)]
140
    use super::*;
141

            
142
    /// Checks that `Rule` gives the same answers as `reference`
143
    ///
144
    /// Unlike `Rule`'s impl, `reference` doesn't need to use panic-free arithmetic,
145
    /// so it can be simple and obvious.
146
    fn check_against_reference<Rule: ThresholdRule>(reference: impl Fn(usize, usize) -> bool) {
147
        for total in 0..20 {
148
            for y in 0..=total {
149
                assert_eq!(
150
                    Rule::is_enough_of(y, total),
151
                    reference(y, total),
152
                    "{y}/{total}",
153
                );
154
            }
155
        }
156
    }
157

            
158
    /// Check that `Rule` is `true` for `total` iff `y` >= `minimum`
159
    fn check_minimum<Rule: ThresholdRule>(total: usize, minimum: usize) {
160
        for y in 0..=(total + 1) {
161
            assert_eq!(
162
                Rule::is_enough_of(y, total),
163
                y >= minimum,
164
                "{y}/{total} {minimum}",
165
            );
166
        }
167
    }
168

            
169
    #[test]
170
    fn more_than_half() {
171
        check_against_reference::<MoreThanHalf>(|y, total| y * 2 > total);
172

            
173
        let minimum = check_minimum::<MoreThanHalf>;
174
        minimum(0, 1);
175
        minimum(1, 1);
176
        minimum(2, 2);
177
        minimum(3, 2);
178
        minimum(4, 3);
179
        minimum(5, 3);
180
    }
181

            
182
    #[test]
183
    fn at_least_two_thirds() {
184
        check_against_reference::<AtLeastTwoThirds>(|y, total| 3 * y >= 2 * total);
185

            
186
        let minimum = check_minimum::<AtLeastTwoThirds>;
187
        minimum(0, 0);
188
        minimum(1, 1);
189
        minimum(2, 2);
190
        minimum(3, 2);
191
        minimum(4, 3);
192
        minimum(5, 4);
193
        minimum(6, 4);
194
        minimum(7, 5);
195
        minimum(8, 6);
196
        minimum(9, 6);
197
    }
198

            
199
    #[test]
200
    fn strictly_more_than_two_thirds() {
201
        check_against_reference::<StrictlyMoreThanTwoThirds>(|y, total| 3 * y > 2 * total);
202

            
203
        let minimum = check_minimum::<StrictlyMoreThanTwoThirds>;
204
        minimum(0, 1);
205
        minimum(1, 1);
206
        minimum(2, 2);
207
        minimum(3, 3);
208
        minimum(4, 3);
209
        minimum(5, 4);
210
        minimum(6, 5);
211
        minimum(7, 5);
212
        minimum(8, 6);
213
        minimum(9, 7);
214
    }
215

            
216
    /// Threshold rule for testing, with exciting behaviour
217
    ///
218
    /// Asserts that we were asked "is 1 out of 2 enough?".
219
    ///
220
    /// The return value is not interesting.
221
    pub(crate) struct ExpectOneOutOfTwo;
222

            
223
    impl ThresholdRule for ExpectOneOutOfTwo {
224
        fn is_enough_of(y: usize, total: usize) -> bool {
225
            assert_eq!(y, 1);
226
            assert_eq!(total, 2);
227
            true
228
        }
229
    }
230

            
231
    #[test]
232
    fn enough_of_iter() {
233
        ExpectOneOutOfTwo::is_true_for_enough_of(0..2, |i| Ok::<_, Bug>(i < 1)).unwrap();
234
    }
235
}