1
//! Compute which time period and shared random value from a consensus to use at
2
//! any given time.
3
//!
4
//! This is, unfortunately, a bit complex.  It works as follows:
5
//!
6
//!   * The _current_ time period is the one that contains the valid-after time
7
//!     for the consensus...
8
//!      * but to compute the time period interval, you need to look at the
9
//!        consensus parameters,
10
//!      * and to compute the time period offset, you need to know the consensus
11
//!        voting interval.
12
//!
13
//!   * The SRV for any given time period is the one that that was the most
14
//!     recent at the _start_ of the time period...
15
//!      * but to know when an SRV was most recent, you need to read a timestamp
16
//!        from it that won't be there until proposal 342 is implemented...
17
//!      * and until then, you have to compute the start of the UTC day when the
18
//!        consensus became valid.
19
//!
20
//! This module could conceivably be part of `tor-netdoc`, but it seems better
21
//! to make it part of `tor-netdir`: this is where we put our complexity.
22
///
23
/// (Here in Arti we use the word "ring" in types and variable names only
24
/// to refer to the actual actual reified ring, not to HSDir parameters, or
25
/// or other aspects of the HSDir ring structure.)
26
use std::time::{Duration, SystemTime};
27

            
28
use crate::{Error, HsDirs, Result, params::NetParameters};
29
use tor_hscrypto::time::TimePeriod;
30
use tor_netdoc::doc::netstatus::{SharedRandVal, md::NetworkStatus as MdConsensus};
31

            
32
#[cfg(feature = "hs-service")]
33
use tor_hscrypto::ope::SrvPeriodOffset;
34

            
35
/// Parameters for generating and using an HsDir ring.
36
///
37
/// These parameters are derived from the shared random values and time
38
/// parameters in the consensus, and are used to determine the
39
/// position of each HsDir within the ring.
40
#[derive(Clone, Debug, Eq, PartialEq)]
41
pub struct HsDirParams {
42
    /// The time period for this ring.  It's used to ensure that blinded onion
43
    /// keys rotate in a _predictable_ way over time.
44
    pub(crate) time_period: TimePeriod,
45
    /// The SharedRandVal for this ring.  It's used to ensure that the position
46
    /// of each HsDir within the ring rotates _unpredictably_ over time.
47
    pub(crate) shared_rand: SharedRandVal,
48
    /// The range of times over which the srv is most current.
49
    pub(crate) srv_lifespan: std::ops::Range<SystemTime>,
50
}
51

            
52
/// By how many voting periods do we offset the beginning of our first time
53
/// period from the epoch?
54
///
55
/// We do this so that each of our time periods begins at a time when the SRV is
56
/// not rotating.
57
const VOTING_PERIODS_IN_OFFSET: u32 = 12;
58

            
59
/// How many voting periods make up an entire round of the shared random value
60
/// commit-and-reveal protocol?
61
///
62
/// We use this to compute an SRV lifetime if one of the SRV values is missing.
63
const VOTING_PERIODS_IN_SRV_ROUND: u32 = 24;
64

            
65
impl HsDirParams {
66
    /// Return the time period for which these parameters are valid.
67
    ///
68
    /// The `hs_blind_id` for an onion service changes every time period: when
69
    /// uploading, callers should use this time period to determine which
70
    /// `hs_blind_id`'s descriptor should be sent to which directory.
71
9024
    pub fn time_period(&self) -> TimePeriod {
72
9024
        self.time_period
73
9024
    }
74

            
75
    /// Return the starting time for the shared-random-value protocol that
76
    /// produced the SRV for this time period.
77
3760
    pub fn start_of_shard_rand_period(&self) -> SystemTime {
78
3760
        self.srv_lifespan.start
79
3760
    }
80

            
81
    /// Return an opaque offset for `when` from the start of the shared-random-value protocol
82
    /// period corresponding to the SRV for this time period.
83
    ///
84
    /// When uploading, callers should this offset to determine
85
    /// the revision counter for their descriptors.
86
    ///
87
    /// Returns `None` if when is after the start of the SRV period.
88
    #[cfg(feature = "hs-service")]
89
3764
    pub fn offset_within_srv_period(&self, when: SystemTime) -> Option<SrvPeriodOffset> {
90
3764
        if when >= self.srv_lifespan.start {
91
3763
            let d = when
92
3763
                .duration_since(self.srv_lifespan.start)
93
3763
                .expect("Somehow, range comparison was not reliable!");
94
3763
            return Some(SrvPeriodOffset::from(d.as_secs() as u32));
95
1
        }
96

            
97
1
        None
98
3764
    }
99

            
100
    /// Compute the `HsDirParams` for the current time period, according to a given
101
    /// consensus.
102
    ///
103
    /// rend-spec-v3 section 2.2.1 et seq
104
    ///
105
    /// Return the ring parameters for the current period (which clients use when
106
    /// fetching onion service descriptors), along with a Vec of ring
107
    /// parameters for any secondary periods that onion services should additionally
108
    /// use when publishing their descriptors.
109
    ///
110
    /// Note that "current" here is always relative to a given consensus, not the
111
    /// current wall-clock time.
112
    ///
113
    /// (This function's return type is a bit cumbersome; these parameters are
114
    /// bundled together because it is efficient to compute them all at once.)
115
    ///
116
    /// Note that this function will only return an error if something is
117
    /// _extremely_ wrong with the provided consensus: for other error cases, it
118
    /// returns a "disaster fallback".
119
19399
    pub(crate) fn compute(
120
19399
        consensus: &MdConsensus,
121
19399
        params: &NetParameters,
122
19399
    ) -> Result<HsDirs<HsDirParams>> {
123
19399
        let srvs = extract_srvs(consensus)?;
124
19399
        let tp_length: Duration = params.hsdir_timeperiod_length.try_into().map_err(|_| {
125
            // Note that this error should be impossible:
126
            // The type of hsdir_timeperiod_length() is IntegerMinutes<BoundedInt32<30, 14400>>...
127
            // It should be at most 10 days, which _definitely_ fits into a Duration.
128
            Error::InvalidConsensus(
129
                "Minutes in hsdir timeperiod could not be converted to a Duration",
130
            )
131
        })?;
132
19399
        let lifetime = &consensus.preamble.lifetime;
133
19399
        let offset = lifetime.voting_period() * VOTING_PERIODS_IN_OFFSET;
134
        let cur_period =
135
19399
            TimePeriod::new(tp_length, lifetime.valid_after(), offset).map_err(|_| {
136
                // This error should be nearly impossible too:
137
                // - It can occur if the time period length is not an integer
138
                //   number of minutes--but we took it from an IntegerMinutes,
139
                //   so that's unlikely.
140
                // - It can occur if the time period length or the offset is
141
                //   greater than can be represented in u32 seconds.
142
                // - It can occur if the valid_after time is so far from the
143
                //   epoch that we can't represent the distance as a Duration.
144
                Error::InvalidConsensus("Consensus valid-after did not fall in a time period")
145
            })?;
146

            
147
19399
        let current = find_params_for_time(&srvs[..], cur_period)?.unwrap_or_else(|| {
148
19021
            tracing::debug!("No SRV params for {cur_period:?}; falling back to disaster params");
149
19021
            disaster_params(cur_period)
150
19021
        });
151

            
152
        // When computing secondary rings, we don't try so many fallback operations:
153
        // if they aren't available, they aren't available.
154
        #[cfg(feature = "hs-service")]
155
19399
        let secondary = [cur_period.prev(), cur_period.next()]
156
19399
            .iter()
157
19399
            .flatten()
158
38798
            .flat_map(|period| find_params_for_time(&srvs[..], *period).ok().flatten())
159
            .collect();
160

            
161
19399
        Ok(HsDirs {
162
19399
            current,
163
19399
            #[cfg(feature = "hs-service")]
164
19399
            secondary,
165
19399
        })
166
19399
    }
167
}
168

            
169
/// Compute ring parameters using a Disaster SRV for this period.
170
19021
fn disaster_params(period: TimePeriod) -> HsDirParams {
171
19021
    HsDirParams {
172
19021
        time_period: period,
173
19021
        shared_rand: disaster_srv(period),
174
19021
        srv_lifespan: period
175
19021
            .range()
176
19021
            .expect("Time period cannot be represented as SystemTime"),
177
19021
    }
178
19021
}
179

            
180
/// Compute the "Disaster SRV" for a given time period.
181
///
182
/// This SRV is used if the authorities do not list any shared random value for
183
/// that time period, but we need to compute an HsDir ring for it anyway.
184
19022
fn disaster_srv(period: TimePeriod) -> SharedRandVal {
185
    use digest::Digest;
186
19022
    let mut d = tor_llcrypto::d::Sha3_256::new();
187
19022
    d.update(b"shared-random-disaster");
188
19022
    d.update(u64::from(period.length().as_minutes()).to_be_bytes());
189
19022
    d.update(period.interval_num().to_be_bytes());
190

            
191
19022
    let v: [u8; 32] = d.finalize().into();
192
19022
    v.into()
193
19022
}
194

            
195
/// Helper type: A `SharedRandVal`, and the time range over which it is the most
196
/// recent.
197
type SrvInfo = (SharedRandVal, std::ops::Range<SystemTime>);
198

            
199
/// Given a list of SrvInfo, return an HsRingParams instance for a given time
200
/// period, if possible.
201
58197
fn find_params_for_time(info: &[SrvInfo], period: TimePeriod) -> Result<Option<HsDirParams>> {
202
58197
    let start = period
203
58197
        .range()
204
        .map_err(|_| {
205
            Error::InvalidConsensus(
206
                "HsDir time period in consensus could not be represented as a SystemTime range.",
207
            )
208
        })?
209
        .start;
210

            
211
58197
    Ok(find_srv_for_time(info, start).map(|srv| HsDirParams {
212
1133
        time_period: period,
213
1133
        shared_rand: srv.0,
214
1133
        srv_lifespan: srv.1.clone(),
215
1133
    }))
216
58197
}
217

            
218
/// Given a list of SrvInfo, return the SrvInfo (if any) that is the most
219
/// recent SRV at `when`.
220
58204
fn find_srv_for_time(info: &[SrvInfo], when: SystemTime) -> Option<&SrvInfo> {
221
58204
    info.iter().find(|(_, range)| range.contains(&when))
222
58204
}
223

            
224
/// Return every SRV from a consensus, along with a duration over which it is
225
/// most recent SRV.
226
19401
fn extract_srvs(consensus: &MdConsensus) -> Result<Vec<SrvInfo>> {
227
19401
    let mut v = Vec::new();
228
19401
    let srv_interval = srv_interval(consensus);
229

            
230
19401
    let shared_rand = &consensus.preamble.shared_rand;
231
19401
    if let Some(cur) = &shared_rand.shared_rand_current_value {
232
380
        let ts_begin = cur
233
380
            .timestamp()
234
380
            .map(Ok)
235
378
            .unwrap_or_else(|| start_of_sr_round(consensus))?;
236
380
        let ts_end = ts_begin + srv_interval;
237
380
        v.push((*cur.value(), ts_begin..ts_end));
238
19021
    }
239
19401
    if let Some(prev) = &shared_rand.shared_rand_previous_value {
240
380
        let ts_begin = prev
241
380
            .timestamp()
242
380
            .map(Ok)
243
378
            .unwrap_or_else(|| start_of_sr_round(consensus).map(|t| t - srv_interval))?;
244
380
        let ts_end = ts_begin + srv_interval;
245
380
        v.push((*prev.value(), ts_begin..ts_end));
246
19021
    }
247

            
248
19401
    Ok(v)
249
19401
}
250

            
251
/// Return the length of time for which a single SRV value is valid.
252
19410
fn srv_interval(consensus: &MdConsensus) -> Duration {
253
    // What we _want_ to do, ideally, is is to learn the duration from the
254
    // difference between the declared time for the previous value and the
255
    // declared time for the current one.
256
    //
257
    // (This assumes that proposal 342 is implemented.)
258
19410
    let shared_rand = &consensus.preamble.shared_rand;
259
19410
    if let (Some(cur), Some(prev)) = (
260
19410
        &shared_rand.shared_rand_current_value,
261
19410
        &shared_rand.shared_rand_previous_value,
262
19410
    ) {
263
389
        if let (Some(cur_ts), Some(prev_ts)) = (cur.timestamp(), prev.timestamp()) {
264
4
            if let Ok(d) = cur_ts.duration_since(prev_ts) {
265
3
                return d;
266
1
            }
267
385
        }
268
19021
    }
269

            
270
    // But if one of those values is missing, or if it has no timestamp, we have
271
    // to fall back to admitting that we know the schedule for the voting
272
    // algorithm.
273
19407
    consensus.preamble.lifetime.voting_period() * VOTING_PERIODS_IN_SRV_ROUND
274
19410
}
275

            
276
/// Return the start time of the current SR protocol run
277
/// of the specified `consensus`.
278
///
279
/// If a full SR protocol run is 24 hours, this function returns
280
/// the start of the UTC day containing the `valid-after` timestamp
281
/// of the consensus.
282
///
283
/// Corresponds to C Tor's `sr_state_get_start_time_of_current_protocol_run()`.
284
762
fn start_of_sr_round(consensus: &MdConsensus) -> Result<SystemTime> {
285
762
    let t = consensus.preamble.lifetime.valid_after();
286
762
    let beginning_of_curr_round = t
287
762
        .duration_since(SystemTime::UNIX_EPOCH)
288
        .map_err(|_| Error::InvalidConsensus("consensus valid-after is before Unix epoch?!"))?
289
        .as_secs();
290
762
    let voting_interval = consensus.preamble.lifetime.voting_period().as_secs();
291

            
292
    // The voting_interval is always going to be greater than 0,
293
    // because the Lifetime's constructor enforces that
294
    // valid_after < fresh_until < valid_until.
295
762
    debug_assert!(voting_interval > 0);
296

            
297
    let curr_round_slot =
298
762
        (beginning_of_curr_round / voting_interval) % u64::from(VOTING_PERIODS_IN_SRV_ROUND);
299
762
    let time_elapsed_since_start_of_run = curr_round_slot * voting_interval;
300

            
301
762
    let offset = Duration::from_secs(beginning_of_curr_round - time_elapsed_since_start_of_run);
302
762
    Ok(SystemTime::UNIX_EPOCH + offset)
303
762
}
304

            
305
#[cfg(test)]
306
mod test {
307
    // @@ begin test lint list maintained by maint/add_warning @@
308
    #![allow(clippy::bool_assert_comparison)]
309
    #![allow(clippy::clone_on_copy)]
310
    #![allow(clippy::dbg_macro)]
311
    #![allow(clippy::mixed_attributes_style)]
312
    #![allow(clippy::print_stderr)]
313
    #![allow(clippy::print_stdout)]
314
    #![allow(clippy::single_char_pattern)]
315
    #![allow(clippy::unwrap_used)]
316
    #![allow(clippy::unchecked_time_subtraction)]
317
    #![allow(clippy::useless_vec)]
318
    #![allow(clippy::needless_pass_by_value)]
319
    #![allow(clippy::string_slice)] // See arti#2571
320
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
321
    use crate::testnet::simple_empty_consensus;
322

            
323
    use super::*;
324
    use hex_literal::hex;
325
    use tor_netdoc::doc::netstatus::{Lifetime, SharedRandStatusConstructor};
326

            
327
    /// Helper: parse an rfc3339 time.
328
    ///
329
    /// # Panics
330
    ///
331
    /// Panics if the time is invalid.
332
    fn t(s: &str) -> SystemTime {
333
        humantime::parse_rfc3339(s).unwrap()
334
    }
335
    /// Helper: parse a duration.
336
    ///
337
    /// # Panics
338
    ///
339
    /// Panics if the time is invalid.
340
    fn d(s: &str) -> Duration {
341
        humantime::parse_duration(s).unwrap()
342
    }
343

            
344
    fn example_lifetime() -> Lifetime {
345
        Lifetime::new(
346
            t("1985-10-25T07:00:00Z"),
347
            t("1985-10-25T08:00:00Z"),
348
            t("1985-10-25T10:00:00Z"),
349
        )
350
        .unwrap()
351
    }
352

            
353
    const SRV1: [u8; 32] = *b"next saturday night were sending";
354
    const SRV2: [u8; 32] = *b"you......... back to the future!";
355

            
356
    fn example_consensus() -> MdConsensus {
357
        let mut bld = simple_empty_consensus(Some(example_lifetime())).unwrap();
358

            
359
        bld.preamble.params.set("hsdir_interval".into(), 1440);
360
        bld.preamble.shared_rand.shared_rand_previous_value = Some(
361
            SharedRandStatusConstructor {
362
                n_reveals: 7,
363
                value: SRV1.into(),
364
            }
365
            .construct(),
366
        );
367
        bld.preamble.shared_rand.shared_rand_current_value = Some(
368
            SharedRandStatusConstructor {
369
                n_reveals: 7,
370
                value: SRV2.into(),
371
            }
372
            .construct(),
373
        );
374

            
375
        bld
376
    }
377

            
378
    #[test]
379
    fn invalid_lifetime() {
380
        let lifetimes = [
381
            // (valid_after, fresh_until, valid_until)
382
            //
383
            // Invalid because valid_after >= fresh_until
384
            (
385
                "2015-04-20T00:00:00Z",
386
                "2015-04-20T00:00:00Z",
387
                "2015-04-22T00:00:00Z",
388
            ),
389
            (
390
                "2015-04-21T00:00:00Z",
391
                "2015-04-20T00:00:00Z",
392
                "2015-04-22T00:00:00Z",
393
            ),
394
            // Invalid because fresh_until >= valid_until
395
            (
396
                "2015-04-20T00:00:00Z",
397
                "2015-04-22T00:00:00Z",
398
                "2015-04-22T00:00:00Z",
399
            ),
400
            (
401
                "2015-04-20T00:00:00Z",
402
                "2015-04-23T00:00:00Z",
403
                "2015-04-22T00:00:00Z",
404
            ),
405
        ];
406

            
407
        for (valid_after, fresh_until, valid_until) in lifetimes {
408
            let err = Lifetime::new(t(valid_after), t(fresh_until), t(valid_until))
409
                .unwrap_err()
410
                .netdoc_error_kind();
411

            
412
            assert_eq!(err, tor_netdoc::NetdocErrorKind::InvalidLifetime);
413
        }
414
    }
415

            
416
    #[test]
417
    fn vote_period() {
418
        assert_eq!(example_lifetime().voting_period(), d("1 hour"));
419

            
420
        let lt2 = Lifetime::new(
421
            t("1985-10-25T07:00:00Z"),
422
            t("1985-10-25T07:22:00Z"),
423
            t("1985-10-25T07:59:00Z"),
424
        )
425
        .unwrap();
426

            
427
        assert_eq!(lt2.voting_period(), d("22 min"));
428
    }
429

            
430
    /// Helper: Adjust the SRV timestamps.
431
    ///
432
    /// # Panics
433
    ///
434
    /// Panics if consensus does not have both SRV entries.
435
    fn set_srv_timestamps(consensus: &mut MdConsensus, prev: SystemTime, cur: SystemTime) {
436
        // If there are timestamps, we look at the difference between them.
437
        consensus
438
            .preamble
439
            .shared_rand
440
            .shared_rand_previous_value
441
            .as_mut()
442
            .unwrap()
443
            .timestamp = Some(prev.into());
444
        consensus
445
            .preamble
446
            .shared_rand
447
            .shared_rand_current_value
448
            .as_mut()
449
            .unwrap()
450
            .timestamp = Some(cur.into());
451
    }
452

            
453
    #[test]
454
    fn srv_period() {
455
        // In a basic consensus with no SRV timestamps, we'll assume 24 voting periods.
456
        let mut consensus = example_consensus();
457
        assert_eq!(srv_interval(&consensus), d("1 day"));
458

            
459
        // If there are timestamps, we look at the difference between them.
460
        set_srv_timestamps(
461
            &mut consensus,
462
            t("1985-10-25T00:00:00Z"),
463
            t("1985-10-25T06:00:05Z"),
464
        );
465
        assert_eq!(srv_interval(&consensus), d("6 hours 5 sec"));
466

            
467
        // Note that if the timestamps are in reversed order, we fall back to 24 hours.
468
        set_srv_timestamps(
469
            &mut consensus,
470
            t("1985-10-25T06:00:05Z"),
471
            t("1985-10-25T00:00:00Z"),
472
        );
473
        assert_eq!(srv_interval(&consensus), d("1 day"));
474
    }
475

            
476
    #[test]
477
    fn srvs_extract_and_find() {
478
        let mut consensus = example_consensus();
479
        let srvs = extract_srvs(&consensus).unwrap();
480
        assert_eq!(
481
            srvs,
482
            vec![
483
                // Since no timestamps are given in the example, the current srv
484
                // is valid from midnight to midnight...
485
                (
486
                    SRV2.into(),
487
                    t("1985-10-25T00:00:00Z")..t("1985-10-26T00:00:00Z")
488
                ),
489
                // ...and the previous SRV is valid midnight-to-midnight on the
490
                // previous day.
491
                (
492
                    SRV1.into(),
493
                    t("1985-10-24T00:00:00Z")..t("1985-10-25T00:00:00Z")
494
                )
495
            ]
496
        );
497

            
498
        // Now try with explicit timestamps on the SRVs.
499
        set_srv_timestamps(
500
            &mut consensus,
501
            t("1985-10-25T00:00:00Z"),
502
            t("1985-10-25T06:00:05Z"),
503
        );
504
        let srvs = extract_srvs(&consensus).unwrap();
505
        assert_eq!(
506
            srvs,
507
            vec![
508
                (
509
                    SRV2.into(),
510
                    t("1985-10-25T06:00:05Z")..t("1985-10-25T12:00:10Z")
511
                ),
512
                (
513
                    SRV1.into(),
514
                    t("1985-10-25T00:00:00Z")..t("1985-10-25T06:00:05Z")
515
                )
516
            ]
517
        );
518

            
519
        // See if we can look up SRVs in that period.
520
        assert_eq!(None, find_srv_for_time(&srvs, t("1985-10-24T23:59:00Z")));
521
        assert_eq!(
522
            Some(&srvs[1]),
523
            find_srv_for_time(&srvs, t("1985-10-25T00:00:00Z"))
524
        );
525
        assert_eq!(
526
            Some(&srvs[1]),
527
            find_srv_for_time(&srvs, t("1985-10-25T03:59:00Z"))
528
        );
529
        assert_eq!(
530
            Some(&srvs[1]),
531
            find_srv_for_time(&srvs, t("1985-10-25T00:00:00Z"))
532
        );
533
        assert_eq!(
534
            Some(&srvs[0]),
535
            find_srv_for_time(&srvs, t("1985-10-25T06:00:05Z"))
536
        );
537
        assert_eq!(
538
            Some(&srvs[0]),
539
            find_srv_for_time(&srvs, t("1985-10-25T12:00:00Z"))
540
        );
541
        assert_eq!(None, find_srv_for_time(&srvs, t("1985-10-25T12:00:30Z")));
542
    }
543

            
544
    #[test]
545
    fn disaster() {
546
        use digest::Digest;
547
        use tor_llcrypto::d::Sha3_256;
548
        let period = TimePeriod::new(d("1 day"), t("1970-01-02T17:33:00Z"), d("12 hours")).unwrap();
549
        assert_eq!(period.length().as_minutes(), 86400 / 60);
550
        assert_eq!(period.interval_num(), 1);
551

            
552
        let dsrv = disaster_srv(period);
553
        assert_eq!(
554
            dsrv.as_ref(),
555
            &hex!("F8A4948707653837FA44ABB5BBC75A12F6F101E7F8FAF699B9715F4965D3507D")
556
        );
557
        assert_eq!(
558
            &dsrv.as_ref()[..],
559
            &Sha3_256::digest(b"shared-random-disaster\0\0\0\0\0\0\x05\xA0\0\0\0\0\0\0\0\x01")[..]
560
        );
561
    }
562

            
563
    #[test]
564
    #[cfg(feature = "hs-service")]
565
    fn ring_params_simple() {
566
        // Compute ring parameters in a legacy environment, where the time
567
        // period and the SRV lifetime are one day long, and they are offset by
568
        // 12 hours.
569
        let consensus = example_consensus();
570
        let netparams = NetParameters::from_netstatus(&consensus.preamble.params);
571
        let HsDirs { current, secondary } = HsDirParams::compute(&consensus, &netparams).unwrap();
572

            
573
        assert_eq!(
574
            current.time_period,
575
            TimePeriod::new(d("1 day"), t("1985-10-25T07:00:00Z"), d("12 hours")).unwrap()
576
        );
577
        // We use the "previous" SRV since the start of this time period was 12:00 on the 24th.
578
        assert_eq!(current.shared_rand.as_ref(), &SRV1);
579

            
580
        // Our secondary SRV will be the one that starts when we move into the
581
        // next time period.
582
        assert_eq!(secondary.len(), 1);
583
        assert_eq!(
584
            secondary[0].time_period,
585
            TimePeriod::new(d("1 day"), t("1985-10-25T12:00:00Z"), d("12 hours")).unwrap(),
586
        );
587
        assert_eq!(secondary[0].shared_rand.as_ref(), &SRV2);
588
    }
589

            
590
    #[test]
591
    #[cfg(feature = "hs-service")]
592
    fn ring_params_tricky() {
593
        // In this case we give the SRVs timestamps and we choose an odd hsdir_interval.
594
        let mut consensus = example_consensus();
595
        set_srv_timestamps(
596
            &mut consensus,
597
            t("1985-10-25T00:00:00Z"),
598
            t("1985-10-25T05:00:00Z"),
599
        );
600
        consensus.preamble.params.set("hsdir_interval".into(), 120);
601
        let netparams = NetParameters::from_netstatus(&consensus.preamble.params);
602
        let HsDirs { current, secondary } = HsDirParams::compute(&consensus, &netparams).unwrap();
603

            
604
        assert_eq!(
605
            current.time_period,
606
            TimePeriod::new(d("2 hours"), t("1985-10-25T07:00:00Z"), d("12 hours")).unwrap()
607
        );
608
        assert_eq!(current.shared_rand.as_ref(), &SRV2);
609

            
610
        assert_eq!(secondary.len(), 2);
611
        assert_eq!(
612
            secondary[0].time_period,
613
            TimePeriod::new(d("2 hours"), t("1985-10-25T05:00:00Z"), d("12 hours")).unwrap()
614
        );
615
        assert_eq!(secondary[0].shared_rand.as_ref(), &SRV1);
616
        assert_eq!(
617
            secondary[1].time_period,
618
            TimePeriod::new(d("2 hours"), t("1985-10-25T09:00:00Z"), d("12 hours")).unwrap()
619
        );
620
        assert_eq!(secondary[1].shared_rand.as_ref(), &SRV2);
621
    }
622

            
623
    #[test]
624
    #[cfg(feature = "hs-service")]
625
    fn offset_within_srv_period() {
626
        // This test doesn't actually use the time_period or shared_rand values, so their value is
627
        // arbitrary.
628
        let time_period =
629
            TimePeriod::new(d("2 hours"), t("1985-10-25T05:00:00Z"), d("12 hours")).unwrap();
630

            
631
        let srv_start = t("1985-10-25T09:00:00Z");
632
        let srv_end = t("1985-10-25T20:00:00Z");
633
        let srv_lifespan = srv_start..srv_end;
634

            
635
        let params = HsDirParams {
636
            time_period,
637
            shared_rand: SRV1.into(),
638
            srv_lifespan,
639
        };
640

            
641
        let before_srv_period = t("1985-10-25T08:59:00Z");
642
        let after_srv_period = t("1985-10-26T10:19:00Z");
643
        assert!(params.offset_within_srv_period(before_srv_period).is_none());
644
        assert_eq!(
645
            params.offset_within_srv_period(srv_start).unwrap(),
646
            SrvPeriodOffset::from(0)
647
        );
648
        // The period is 11h long
649
        assert_eq!(
650
            params.offset_within_srv_period(srv_end).unwrap(),
651
            SrvPeriodOffset::from(11 * 60 * 60)
652
        );
653
        // This timestamp is 1 day 1h 19m from the start of the SRV period
654
        assert_eq!(
655
            params.offset_within_srv_period(after_srv_period).unwrap(),
656
            SrvPeriodOffset::from((25 * 60 + 19) * 60)
657
        );
658
    }
659

            
660
    #[test]
661
    fn start_of_sr_protocol_run() {
662
        let test_cases = [
663
            // (valid_after, fresh_until, expected_sr_start, expected_srv_interval)
664
            //
665
            // Voting interval = 1h
666
            // The start of the current SR run is always the start
667
            // of the day of valid-after of the consensus.
668
            // An SRV protocol run takes 1h * 24 rounds = 24h
669
            (
670
                "2015-04-20T00:00:00Z",
671
                "2015-04-20T01:00:00Z",
672
                "2015-04-20T00:00:00Z",
673
                "24 hours",
674
            ),
675
            (
676
                "2015-04-20T22:00:00Z",
677
                "2015-04-20T23:00:00Z",
678
                "2015-04-20T00:00:00Z",
679
                "24 hours",
680
            ),
681
            (
682
                "2015-04-19T23:00:00Z",
683
                "2015-04-20T00:00:00Z",
684
                "2015-04-19T00:00:00Z",
685
                "24 hours",
686
            ),
687
            // Voting interval = 10s
688
            // An SRV protocol run takes 10s * 24 rounds = 4 mins
689
            (
690
                "2015-04-20T00:15:30Z",
691
                "2015-04-20T00:15:40Z",
692
                "2015-04-20T00:12:00Z",
693
                "4 minutes",
694
            ),
695
            // Voting interval = 20s
696
            // An SRV protocol run takes 20s * 24 rounds = 8 mins
697
            (
698
                "2015-04-20T00:15:00Z",
699
                "2015-04-20T00:15:20Z",
700
                "2015-04-20T00:08:00Z",
701
                "8 minutes",
702
            ),
703
            (
704
                "2015-04-20T00:15:30Z",
705
                "2015-04-20T00:15:50Z",
706
                "2015-04-20T00:08:10Z",
707
                "8 minutes",
708
            ),
709
        ];
710

            
711
        for (valid_after, fresh_until, expected_start, expected_interval) in test_cases {
712
            let lifetime = Lifetime::new(
713
                t(valid_after),
714
                t(fresh_until),
715
                // The valid-until doesn't matter for the purposes of this test
716
                t("2020-10-25T10:00:00Z"),
717
            )
718
            .unwrap();
719

            
720
            let mut consensus = example_consensus();
721
            consensus.preamble.lifetime = lifetime;
722
            let sr_start = start_of_sr_round(&consensus).unwrap();
723

            
724
            assert_eq!(
725
                t(expected_start),
726
                sr_start,
727
                "{expected_start} != {} (valid-after = {valid_after}, fresh-until = {fresh_until})",
728
                humantime::format_rfc3339(sr_start)
729
            );
730

            
731
            assert_eq!(d(expected_interval), srv_interval(&consensus));
732
        }
733
    }
734
}