1
//! Shared random (consensus calculation)
2

            
3
use super::*;
4
use crate::shared_random::*;
5
use netstatus::{SharedRandStatus, SharedRandStatuses, SharedRandStatusesConstructor};
6

            
7
/// Number of authorities needed at 00:00 to make SRV
8
///
9
/// <https://spec.torproject.org/srv-spec/overview.html#inserting>
10
const NEW_SRV_MIN_VOTERS_PARAM: &str = "AuthDirNumSRVAgreements";
11

            
12
/// Inputs needed for calculating SRV field in a consensus
13
///
14
/// These are just the corresponding fields from the preamble
15
pub(super) struct SrvAC<'r> {
16
    /// lifetime fields
17
    pub(crate) lifetime: &'r netstatus::Lifetime,
18
    /// netparams, `params`
19
    pub(crate) params: &'r netstatus::NetParams,
20
}
21

            
22
impl Aggregate<SrvAC<'_>> for SharedRandStatuses {
23
    type Output = Self;
24

            
25
34
    fn aggregate<'i>(
26
34
        context: ConsensusContextRefs<SrvAC>,
27
34
        inputs: impl ComponentInVotes<&'i Self>,
28
34
    ) -> Result<Self::Output, ConsensusError>
29
34
    where
30
34
        Self: 'i,
31
    {
32
34
        calc! { out.shared_rand_previous_value }
33
34
        calc! { out.shared_rand_current_value }
34
34
        Ok(construct! {
35
34
            SharedRandStatuses {
36
34
            } {
37
34
                out. shared_rand_previous_value;
38
34
                out. shared_rand_current_value;
39
34
            }
40
34
        })
41
34
    }
42
}
43

            
44
impl Aggregate<SrvAC<'_>> for Option<SharedRandStatus> {
45
    type Output = Self;
46

            
47
68
    fn aggregate<'i>(
48
68
        context: ConsensusContextRefs<SrvAC>,
49
68
        inputs: impl ComponentInVotes<&'i Self>,
50
68
    ) -> Result<Self::Output, ConsensusError>
51
68
    where
52
68
        Self: 'i,
53
    {
54
        // https://spec.torproject.org/srv-spec/overview.html#inserting
55

            
56
68
        let ac = context.computed;
57

            
58
68
        let phase = shared_random::Phase::for_voting_period(
59
68
            *ac.lifetime.valid_after,
60
68
            ac.lifetime
61
68
                .fresh_until
62
68
                .duration_since(*ac.lifetime.valid_after)
63
                .map_err(|_: std::time::SystemTimeError| {
64
                    ConsensusError::Unreasonable("lifetime fresh_until before valid_after".into())
65
                })?,
66
        )?;
67

            
68
        // IEFE allows us to use `?` to early exit with `Ok(None)`
69
68
        Ok((|| {
70
364
            let counts = inputs.votes().filter_map(|srv| srv.as_ref()).counts();
71
82
            let (srv, n_in_favour) = counts.into_iter().max_by_key(|(_, n)| *n)?;
72
68
            context
73
68
                .is_enough_of_all_auths::<MoreThanHalf>(n_in_favour)
74
68
                .then_some(())?;
75
60
            if phase == shared_random::Phase::NEW_SRV {
76
20
                if let Some(reqd) = ac.params.without_defaults().get(NEW_SRV_MIN_VOTERS_PARAM) {
77
                    // reqd is i32, saturatingly convert to usize
78
8
                    let reqd = usize::try_from(*reqd).unwrap_or(usize::MAX);
79
8
                    (n_in_favour >= reqd).then_some(())?;
80
12
                }
81
40
            }
82
58
            Some(srv.clone())
83
        })())
84
68
    }
85
}
86

            
87
#[cfg(test)]
88
pub(crate) mod test {
89
    // @@ begin test lint list maintained by maint/add_warning @@
90
    #![allow(clippy::bool_assert_comparison)]
91
    #![allow(clippy::clone_on_copy)]
92
    #![allow(clippy::dbg_macro)]
93
    #![allow(clippy::mixed_attributes_style)]
94
    #![allow(clippy::print_stderr)]
95
    #![allow(clippy::print_stdout)]
96
    #![allow(clippy::single_char_pattern)]
97
    #![allow(clippy::unwrap_used)]
98
    #![allow(clippy::unchecked_time_subtraction)]
99
    #![allow(clippy::useless_vec)]
100
    #![allow(clippy::needless_pass_by_value)]
101
    #![allow(clippy::string_slice)] // See arti#2571
102
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
103
    use super::*;
104
    use crate::consensus::test::compute_test;
105
    use humantime::parse_rfc3339;
106
    use netstatus::SharedRandVal;
107
    use std::cell::RefCell;
108

            
109
    #[test]
110
    fn srv() {
111
        fn chk(
112
            n_votes: usize,
113
            n_auths: usize,
114
            votes: &[u8], // if too short, other voters vote None
115
            hour: u8,
116
            auth_dir_num_s_r_v_agreements_netparam: Option<i32>,
117
            exp: Option<u8>,
118
        ) {
119
            assert!(votes.len() <= n_votes);
120

            
121
            let mk_srs = |byte: u8| {
122
                let value = SharedRandVal::from(std::array::repeat(byte));
123
                netstatus::SharedRandStatusConstructor {
124
                    n_reveals: 1,
125
                    value,
126
                }
127
                .construct()
128
            };
129
            let hours = |h: u8| Duration::from_hours(h.into());
130

            
131
            let prev = RefCell::new(None);
132

            
133
            compute_test(
134
                n_votes,
135
                n_auths,
136
                |vnum, vote| {
137
                    let ss = &mut vote.authority.authority.shared_rand;
138
                    ss.shared_rand_current_value = votes.get(vnum).copied().map(mk_srs);
139

            
140
                    *prev.borrow_mut() = ss.shared_rand_previous_value.clone();
141

            
142
                    let valid_after = Iso8601TimeSp::from(
143
                        parse_rfc3339("2026-10-01T00:00:00Z").unwrap() + hours(hour),
144
                    );
145
                    let fresh_until = (*valid_after + hours(1)).into();
146
                    let valid_until = (*valid_after + hours(100)).into();
147

            
148
                    vote.preamble.lifetime = netstatus::LifetimeConstructor {
149
                        valid_after,
150
                        fresh_until,
151
                        valid_until,
152
                    }
153
                    .construct();
154

            
155
                    let params = &mut vote.preamble.params;
156
                    match auth_dir_num_s_r_v_agreements_netparam {
157
                        Some(v) => params.set(NEW_SRV_MIN_VOTERS_PARAM.into(), v),
158
                        None => params.clear(NEW_SRV_MIN_VOTERS_PARAM),
159
                    }
160

            
161
                    Ok(())
162
                },
163
                |Consensuses { plain, md }| {
164
                    let chk_out = |ss: &SharedRandStatuses| {
165
                        assert_eq!(
166
                            ss.shared_rand_current_value,
167
                            exp.map(mk_srs),
168
                            "{n_votes} {n_auths} {votes:?} {hour} {:?}",
169
                            auth_dir_num_s_r_v_agreements_netparam,
170
                        );
171

            
172
                        if exp.is_some() {
173
                            assert_eq!(ss.shared_rand_previous_value, *prev.borrow(),);
174
                        }
175
                    };
176

            
177
                    chk_out(&plain.preamble.shared_rand);
178
                    chk_out(&md.preamble.shared_rand);
179
                    Ok(())
180
                },
181
            );
182
        }
183

            
184
        chk(3, 7, &[1, 1, 1], 0, None, None);
185
        chk(4, 7, &[1, 1, 1, 1], 0, None, Some(1));
186
        chk(6, 6, &[1, 1, 1, 2, 2, 2], 0, None, None);
187

            
188
        chk(6, 7, &[1, 1, 1, 2, 2, 2], 0, None, None);
189
        chk(6, 7, &[1, 1, 1, 1, 2, 2], 0, None, Some(1));
190
        chk(6, 7, &[1, 1, 1, 1, 2, 2], 0, Some(2), Some(1));
191
        chk(6, 7, &[1, 1, 1, 1, 2, 2], 0, Some(5), None);
192
        chk(6, 7, &[1, 1, 1, 1, 2, 2], 1, Some(5), Some(1));
193
        chk(6, 7, &[1, 1, 1, 1, 2, 2], 23, Some(5), Some(1));
194
    }
195
}