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::{params::NetParameters, Error, HsDirs, Result};
29
use time::{OffsetDateTime, UtcOffset};
30
use tor_hscrypto::time::TimePeriod;
31
use tor_netdoc::doc::netstatus::{MdConsensus, SharedRandVal};
32

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

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

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

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

            
66
/// One day.
67
const ONE_DAY: Duration = Duration::new(86400, 0);
68

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

            
79
    /// Return the starting time for the shared-random-value protocol that
80
    /// produced the SRV for this time period.
81
2664
    pub fn start_of_shard_rand_period(&self) -> SystemTime {
82
2664
        self.srv_lifespan.start
83
2664
    }
84

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

            
101
2
        None
102
2672
    }
103

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

            
150
6476
        let current = find_params_for_time(&srvs[..], cur_period)?
151
6681
            .unwrap_or_else(|| disaster_params(cur_period));
152
6476

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

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

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

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

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

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

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

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

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

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

            
232
6480
    if let Some(cur) = consensus.shared_rand_cur() {
233
50
        let ts_begin = cur
234
50
            .timestamp()
235
54
            .unwrap_or_else(|| start_of_day_containing(consensus_ts));
236
50
        let ts_end = ts_begin + srv_interval;
237
50
        v.push((*cur.value(), ts_begin..ts_end));
238
6472
    }
239
6480
    if let Some(prev) = consensus.shared_rand_prev() {
240
8
        let ts_begin = prev
241
8
            .timestamp()
242
10
            .unwrap_or_else(|| start_of_day_containing(consensus_ts) - ONE_DAY);
243
8
        let ts_end = ts_begin + srv_interval;
244
8
        v.push((*prev.value(), ts_begin..ts_end));
245
6472
    }
246

            
247
6480
    v
248
6480
}
249

            
250
/// Return the length of time for which a single SRV value is valid.
251
6486
fn srv_interval(consensus: &MdConsensus) -> Duration {
252
    // What we _want_ to do, ideally, is is to learn the duration from the
253
    // difference between the declared time for the previous value and the
254
    // declared time for the current one.
255
    //
256
    // (This assumes that proposal 342 is implemented.)
257
6486
    if let (Some(cur), Some(prev)) = (consensus.shared_rand_cur(), consensus.shared_rand_prev()) {
258
14
        if let (Some(cur_ts), Some(prev_ts)) = (cur.timestamp(), prev.timestamp()) {
259
8
            if let Ok(d) = cur_ts.duration_since(prev_ts) {
260
6
                return d;
261
2
            }
262
6
        }
263
6472
    }
264

            
265
    // But if one of those values is missing, or if it has no timestamp, we have
266
    // to fall back to admitting that we know the schedule for the voting
267
    // algorithm.
268
6480
    consensus.lifetime().voting_period() * VOTING_PERIODS_IN_SRV_ROUND
269
6486
}
270

            
271
/// Return the length of the voting period in the consensus.
272
///
273
/// (The "voting period" is the length of time between between one consensus and the next.)
274

            
275
/// Return a time at the start of the UTC day containing `t`.
276
56
fn start_of_day_containing(t: SystemTime) -> SystemTime {
277
56
    OffsetDateTime::from(t)
278
56
        .to_offset(UtcOffset::UTC)
279
56
        .replace_time(time::macros::time!(00:00))
280
56
        .into()
281
56
}
282

            
283
#[cfg(test)]
284
mod test {
285
    // @@ begin test lint list maintained by maint/add_warning @@
286
    #![allow(clippy::bool_assert_comparison)]
287
    #![allow(clippy::clone_on_copy)]
288
    #![allow(clippy::dbg_macro)]
289
    #![allow(clippy::print_stderr)]
290
    #![allow(clippy::print_stdout)]
291
    #![allow(clippy::single_char_pattern)]
292
    #![allow(clippy::unwrap_used)]
293
    #![allow(clippy::unchecked_duration_subtraction)]
294
    #![allow(clippy::useless_vec)]
295
    #![allow(clippy::needless_pass_by_value)]
296
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
297
    use super::*;
298
    use hex_literal::hex;
299
    use tor_netdoc::doc::netstatus::{ConsensusBuilder, Lifetime, MdConsensusRouterStatus};
300

            
301
    /// Helper: parse an rfc3339 time.
302
    ///
303
    /// # Panics
304
    ///
305
    /// Panics if the time is invalid.
306
    fn t(s: &str) -> SystemTime {
307
        humantime::parse_rfc3339(s).unwrap()
308
    }
309
    /// Helper: parse a duration.
310
    ///
311
    /// # Panics
312
    ///
313
    /// Panics if the time is invalid.
314
    fn d(s: &str) -> Duration {
315
        humantime::parse_duration(s).unwrap()
316
    }
317

            
318
    fn example_lifetime() -> Lifetime {
319
        Lifetime::new(
320
            t("1985-10-25T07:00:00Z"),
321
            t("1985-10-25T08:00:00Z"),
322
            t("1985-10-25T10:00:00Z"),
323
        )
324
        .unwrap()
325
    }
326

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

            
330
    fn example_consensus_builder() -> ConsensusBuilder<MdConsensusRouterStatus> {
331
        let mut bld = MdConsensus::builder();
332

            
333
        bld.consensus_method(34)
334
            .lifetime(example_lifetime())
335
            .param("bwweightscale", 1)
336
            .param("hsdir_interval", 1440)
337
            .weights("".parse().unwrap())
338
            .shared_rand_prev(7, SRV1.into(), None)
339
            .shared_rand_cur(7, SRV2.into(), None);
340

            
341
        bld
342
    }
343

            
344
    #[test]
345
    fn start_of_day() {
346
        assert_eq!(
347
            start_of_day_containing(t("1985-10-25T07:00:00Z")),
348
            t("1985-10-25T00:00:00Z")
349
        );
350
        assert_eq!(
351
            start_of_day_containing(t("1985-10-25T00:00:00Z")),
352
            t("1985-10-25T00:00:00Z")
353
        );
354
        assert_eq!(
355
            start_of_day_containing(t("1985-10-25T23:59:59.999Z")),
356
            t("1985-10-25T00:00:00Z")
357
        );
358
    }
359

            
360
    #[test]
361
    fn vote_period() {
362
        assert_eq!(example_lifetime().voting_period(), d("1 hour"));
363

            
364
        let lt2 = Lifetime::new(
365
            t("1985-10-25T07:00:00Z"),
366
            t("1985-10-25T07:22:00Z"),
367
            t("1985-10-25T07:59:00Z"),
368
        )
369
        .unwrap();
370

            
371
        assert_eq!(lt2.voting_period(), d("22 min"));
372
    }
373

            
374
    #[test]
375
    fn srv_period() {
376
        // In a basic consensus with no SRV timestamps, we'll assume 24 voting periods.
377
        let consensus = example_consensus_builder().testing_consensus().unwrap();
378
        assert_eq!(srv_interval(&consensus), d("1 day"));
379

            
380
        // If there are timestamps, we look at the difference between them.
381
        let consensus = example_consensus_builder()
382
            .shared_rand_prev(7, SRV1.into(), Some(t("1985-10-25T00:00:00Z")))
383
            .shared_rand_cur(7, SRV2.into(), Some(t("1985-10-25T06:00:05Z")))
384
            .testing_consensus()
385
            .unwrap();
386
        assert_eq!(srv_interval(&consensus), d("6 hours 5 sec"));
387

            
388
        // Note that if the timestamps are in reversed order, we fall back to 24 hours.
389
        let consensus = example_consensus_builder()
390
            .shared_rand_cur(7, SRV1.into(), Some(t("1985-10-25T00:00:00Z")))
391
            .shared_rand_prev(7, SRV2.into(), Some(t("1985-10-25T06:00:05Z")))
392
            .testing_consensus()
393
            .unwrap();
394
        assert_eq!(srv_interval(&consensus), d("1 day"));
395
    }
396

            
397
    #[test]
398
    fn srvs_extract_and_find() {
399
        let consensus = example_consensus_builder().testing_consensus().unwrap();
400
        let srvs = extract_srvs(&consensus);
401
        assert_eq!(
402
            srvs,
403
            vec![
404
                // Since no timestamps are given in the example, the current srv
405
                // is valid from midnight to midnight...
406
                (
407
                    SRV2.into(),
408
                    t("1985-10-25T00:00:00Z")..t("1985-10-26T00:00:00Z")
409
                ),
410
                // ...and the previous SRV is valid midnight-to-midnight on the
411
                // previous day.
412
                (
413
                    SRV1.into(),
414
                    t("1985-10-24T00:00:00Z")..t("1985-10-25T00:00:00Z")
415
                )
416
            ]
417
        );
418

            
419
        // Now try with explicit timestamps on the SRVs.
420
        let consensus = example_consensus_builder()
421
            .shared_rand_prev(7, SRV1.into(), Some(t("1985-10-25T00:00:00Z")))
422
            .shared_rand_cur(7, SRV2.into(), Some(t("1985-10-25T06:00:05Z")))
423
            .testing_consensus()
424
            .unwrap();
425
        let srvs = extract_srvs(&consensus);
426
        assert_eq!(
427
            srvs,
428
            vec![
429
                (
430
                    SRV2.into(),
431
                    t("1985-10-25T06:00:05Z")..t("1985-10-25T12:00:10Z")
432
                ),
433
                (
434
                    SRV1.into(),
435
                    t("1985-10-25T00:00:00Z")..t("1985-10-25T06:00:05Z")
436
                )
437
            ]
438
        );
439

            
440
        // See if we can look up SRVs in that period.
441
        assert_eq!(None, find_srv_for_time(&srvs, t("1985-10-24T23:59:00Z")));
442
        assert_eq!(
443
            Some(&srvs[1]),
444
            find_srv_for_time(&srvs, t("1985-10-25T00:00:00Z"))
445
        );
446
        assert_eq!(
447
            Some(&srvs[1]),
448
            find_srv_for_time(&srvs, t("1985-10-25T03:59:00Z"))
449
        );
450
        assert_eq!(
451
            Some(&srvs[1]),
452
            find_srv_for_time(&srvs, t("1985-10-25T00:00:00Z"))
453
        );
454
        assert_eq!(
455
            Some(&srvs[0]),
456
            find_srv_for_time(&srvs, t("1985-10-25T06:00:05Z"))
457
        );
458
        assert_eq!(
459
            Some(&srvs[0]),
460
            find_srv_for_time(&srvs, t("1985-10-25T12:00:00Z"))
461
        );
462
        assert_eq!(None, find_srv_for_time(&srvs, t("1985-10-25T12:00:30Z")));
463
    }
464

            
465
    #[test]
466
    fn disaster() {
467
        use digest::Digest;
468
        use tor_llcrypto::d::Sha3_256;
469
        let period = TimePeriod::new(d("1 day"), t("1970-01-02T17:33:00Z"), d("12 hours")).unwrap();
470
        assert_eq!(period.length().as_minutes(), 86400 / 60);
471
        assert_eq!(period.interval_num(), 1);
472

            
473
        let dsrv = disaster_srv(period);
474
        assert_eq!(
475
            dsrv.as_ref(),
476
            &hex!("F8A4948707653837FA44ABB5BBC75A12F6F101E7F8FAF699B9715F4965D3507D")
477
        );
478
        assert_eq!(
479
            &dsrv.as_ref()[..],
480
            &Sha3_256::digest(b"shared-random-disaster\0\0\0\0\0\0\x05\xA0\0\0\0\0\0\0\0\x01")[..]
481
        );
482
    }
483

            
484
    #[test]
485
    #[cfg(feature = "hs-service")]
486
    fn ring_params_simple() {
487
        // Compute ring parameters in a legacy environment, where the time
488
        // period and the SRV lifetime are one day long, and they are offset by
489
        // 12 hours.
490
        let consensus = example_consensus_builder().testing_consensus().unwrap();
491
        let netparams = NetParameters::from_map(consensus.params());
492
        let HsDirs { current, secondary } = HsDirParams::compute(&consensus, &netparams).unwrap();
493

            
494
        assert_eq!(
495
            current.time_period,
496
            TimePeriod::new(d("1 day"), t("1985-10-25T07:00:00Z"), d("12 hours")).unwrap()
497
        );
498
        // We use the "previous" SRV since the start of this time period was 12:00 on the 24th.
499
        assert_eq!(current.shared_rand.as_ref(), &SRV1);
500

            
501
        // Our secondary SRV will be the one that starts when we move into the
502
        // next time period.
503
        assert_eq!(secondary.len(), 1);
504
        assert_eq!(
505
            secondary[0].time_period,
506
            TimePeriod::new(d("1 day"), t("1985-10-25T12:00:00Z"), d("12 hours")).unwrap(),
507
        );
508
        assert_eq!(secondary[0].shared_rand.as_ref(), &SRV2);
509
    }
510

            
511
    #[test]
512
    #[cfg(feature = "hs-service")]
513
    fn ring_params_tricky() {
514
        // In this case we give the SRVs timestamps and we choose an odd hsdir_interval.
515
        let consensus = example_consensus_builder()
516
            .shared_rand_prev(7, SRV1.into(), Some(t("1985-10-25T00:00:00Z")))
517
            .shared_rand_cur(7, SRV2.into(), Some(t("1985-10-25T05:00:00Z")))
518
            .param("hsdir_interval", 120) // 2 hours
519
            .testing_consensus()
520
            .unwrap();
521
        let netparams = NetParameters::from_map(consensus.params());
522
        let HsDirs { current, secondary } = HsDirParams::compute(&consensus, &netparams).unwrap();
523

            
524
        assert_eq!(
525
            current.time_period,
526
            TimePeriod::new(d("2 hours"), t("1985-10-25T07:00:00Z"), d("12 hours")).unwrap()
527
        );
528
        assert_eq!(current.shared_rand.as_ref(), &SRV2);
529

            
530
        assert_eq!(secondary.len(), 2);
531
        assert_eq!(
532
            secondary[0].time_period,
533
            TimePeriod::new(d("2 hours"), t("1985-10-25T05:00:00Z"), d("12 hours")).unwrap()
534
        );
535
        assert_eq!(secondary[0].shared_rand.as_ref(), &SRV1);
536
        assert_eq!(
537
            secondary[1].time_period,
538
            TimePeriod::new(d("2 hours"), t("1985-10-25T09:00:00Z"), d("12 hours")).unwrap()
539
        );
540
        assert_eq!(secondary[1].shared_rand.as_ref(), &SRV2);
541
    }
542

            
543
    #[test]
544
    #[cfg(feature = "hs-service")]
545
    fn offset_within_srv_period() {
546
        // This test doesn't actually use the time_period or shared_rand values, so their value is
547
        // arbitrary.
548
        let time_period =
549
            TimePeriod::new(d("2 hours"), t("1985-10-25T05:00:00Z"), d("12 hours")).unwrap();
550

            
551
        let srv_start = t("1985-10-25T09:00:00Z");
552
        let srv_end = t("1985-10-25T20:00:00Z");
553
        let srv_lifespan = srv_start..srv_end;
554

            
555
        let params = HsDirParams {
556
            time_period,
557
            shared_rand: SRV1.into(),
558
            srv_lifespan,
559
        };
560

            
561
        let before_srv_period = t("1985-10-25T08:59:00Z");
562
        let after_srv_period = t("1985-10-26T10:19:00Z");
563
        assert!(params.offset_within_srv_period(before_srv_period).is_none());
564
        assert_eq!(
565
            params.offset_within_srv_period(srv_start).unwrap(),
566
            SrvPeriodOffset::from(0)
567
        );
568
        // The period is 11h long
569
        assert_eq!(
570
            params.offset_within_srv_period(srv_end).unwrap(),
571
            SrvPeriodOffset::from(11 * 60 * 60)
572
        );
573
        // This timestamp is 1 day 1h 19m from the start of the SRV period
574
        assert_eq!(
575
            params.offset_within_srv_period(after_srv_period).unwrap(),
576
            SrvPeriodOffset::from((25 * 60 + 19) * 60)
577
        );
578
    }
579
}