1
//! Shared random - support for calculating votes and consensuses
2

            
3
use crate::internal_prelude::*;
4

            
5
/// Number of nominal hours in a nominal day
6
const PHASES: u8 = 24;
7

            
8
/// Phase within the 24-phase shared random protocol
9
///
10
/// This is the "nominal hour" from the spec, which in the live network is the UTC hour.
11
///
12
/// <https://spec.torproject.org/srv-spec/overview.html#times-and-the-voting-interval>
13
#[derive(Copy, Clone, Eq, PartialEq, derive_more::Debug, derive_more::From)]
14
#[debug("SrvPhase({nominal_hour:02}:00)")]
15
pub(crate) struct Phase {
16
    /// Nominal hour
17
    nominal_hour: u8,
18
}
19

            
20
/// Error thrown by `Phase::try_from_hour`
21
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
22
#[error("SRV phase out of range")]
23
pub(crate) struct PhaseOutOfRange;
24

            
25
/// Bad times means we couldn't calculate the phase
26
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
27
pub(crate) enum UnreasonableTime {
28
    /// bad valid after
29
    #[error("bad valid_after (must be after the unix epoch)")]
30
    ValidAfter,
31
    /// bad voting period
32
    #[error("bad voting period (must be nonzero)")]
33
    VotingPeriod,
34
}
35

            
36
impl Phase {
37
    /// Phase in which we declare a new SRV.  Midnight.
38
    pub(crate) const NEW_SRV: Phase = Phase::from_hour_const(0);
39

            
40
    /// Construct a `Phase` from a nominal hour value
41
97
    pub(crate) const fn try_from_hour(nominal_hour: u8) -> Result<Self, PhaseOutOfRange> {
42
97
        if nominal_hour >= PHASES {
43
2
            Err(PhaseOutOfRange)
44
        } else {
45
95
            Ok(Phase { nominal_hour })
46
        }
47
97
    }
48

            
49
    /// Construct a `Phase` from a nominal hour value
50
    ///
51
    /// # Panics
52
    ///
53
    /// Panics if the value is out of range (`>24`),
54
    /// with a rather poor error message.
55
    pub(crate) const fn from_hour_const(nominal_hour: u8) -> Self {
56
        match Phase::try_from_hour(nominal_hour) {
57
            Ok(y) => y,
58
            Err(_) => panic!(),
59
        }
60
    }
61

            
62
    /// Return the nominal hour for a particular voting period
63
80
    pub(crate) fn for_voting_period(
64
80
        valid_after: SystemTime,
65
80
        voting_period: Duration,
66
80
    ) -> Result<Phase, UnreasonableTime> {
67
80
        let unix_time = valid_after
68
80
            .duration_since(SystemTime::UNIX_EPOCH)
69
            .map_err(|_| UnreasonableTime::ValidAfter)?
70
            .as_secs();
71
80
        let interval_number = unix_time
72
80
            .checked_div(voting_period.as_secs())
73
80
            .ok_or(UnreasonableTime::VotingPeriod)?;
74
80
        let hour = interval_number
75
            .checked_rem(const { PHASES as u64 })
76
80
            .expect("PHASES is nonzero");
77
80
        let hour = u8::try_from(hour).expect("just reduced");
78
80
        let phase = Phase::try_from_hour(hour).expect("just reduced");
79
80
        Ok(phase)
80
80
    }
81
}
82

            
83
#[cfg(test)]
84
pub(crate) mod test {
85
    // @@ begin test lint list maintained by maint/add_warning @@
86
    #![allow(clippy::bool_assert_comparison)]
87
    #![allow(clippy::clone_on_copy)]
88
    #![allow(clippy::dbg_macro)]
89
    #![allow(clippy::mixed_attributes_style)]
90
    #![allow(clippy::print_stderr)]
91
    #![allow(clippy::print_stdout)]
92
    #![allow(clippy::single_char_pattern)]
93
    #![allow(clippy::unwrap_used)]
94
    #![allow(clippy::unchecked_time_subtraction)]
95
    #![allow(clippy::useless_vec)]
96
    #![allow(clippy::needless_pass_by_value)]
97
    #![allow(clippy::string_slice)] // See arti#2571
98
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
99
    use super::*;
100
    use humantime::parse_rfc3339;
101

            
102
    #[test]
103
    fn phase_basic() {
104
        let ok = |h| assert_eq!(Phase::try_from_hour(h), Ok(Phase { nominal_hour: h }));
105
        let err = |h| Phase::try_from_hour(h).unwrap_err();
106
        ok(0);
107
        ok(1);
108
        ok(23);
109
        err(24);
110
        err(255);
111
    }
112

            
113
    #[test]
114
    fn phase_for_period() {
115
        let chk = |vp, t, exp| {
116
            assert_eq!(
117
                Phase::for_voting_period(parse_rfc3339(t).expect(t), Duration::from_secs(vp),),
118
                Ok(Phase::try_from_hour(exp).unwrap()),
119
                "{vp} {t:?} {exp}",
120
            );
121
        };
122

            
123
        let chk_h = |t, exp| chk(3600, t, exp);
124

            
125
        chk_h("2026-10-01T23:59:59Z", 23);
126
        chk_h("2026-10-02T00:00:00Z", 0);
127
        chk_h("2026-10-02T00:00:01Z", 0);
128
        chk_h("2026-10-02T00:00:59Z", 0);
129
        chk_h("2026-10-02T01:00:00Z", 1);
130
        chk_h("2026-10-02T02:00:00Z", 2);
131
        chk_h("2026-10-02T23:59:59Z", 23);
132
        chk(60, "1970-01-01T00:00:00Z", 0);
133
        chk(60, "1970-01-01T00:00:59Z", 0);
134
        chk(60, "1970-01-01T00:01:00Z", 1);
135
        chk(60, "1970-01-01T00:23:59Z", 23);
136
        chk(60, "1970-01-01T00:24:00Z", 0);
137
    }
138
}