1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Timestamps used by Tendermint blockchains

use core::{
    convert::{TryFrom, TryInto},
    fmt,
    ops::{Add, Sub},
    str::FromStr,
    time::Duration,
};

use serde::{Deserialize, Serialize};
use tendermint_proto::{google::protobuf::Timestamp, serializers::timestamp, Protobuf};
use time::{
    format_description::well_known::Rfc3339,
    macros::{datetime, offset},
    OffsetDateTime, PrimitiveDateTime,
};

use crate::{error::Error, prelude::*};

/// Tendermint timestamps
///
/// A `Time` value is guaranteed to represent a valid `Timestamp` as defined
/// by Google's well-known protobuf type [specification]. Conversions and
/// operations that would result in exceeding `Timestamp`'s validity
/// range return an error or `None`.
///
/// The string serialization format for `Time` is defined as an RFC 3339
/// compliant string with the optional subsecond fraction part having
/// up to 9 digits and no trailing zeros, and the UTC offset denoted by Z.
/// This reproduces the behavior of Go's `time.RFC3339Nano` format.
///
/// [specification]: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Timestamp
// For memory efficiency, the inner member is `PrimitiveDateTime`, with assumed
// UTC offset. The `assume_utc` method is used to get the operational
// `OffsetDateTime` value.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "Timestamp", into = "Timestamp")]
pub struct Time(PrimitiveDateTime);

impl Protobuf<Timestamp> for Time {}

impl TryFrom<Timestamp> for Time {
    type Error = Error;

    fn try_from(value: Timestamp) -> Result<Self, Error> {
        let nanos = value
            .nanos
            .try_into()
            .map_err(|_| Error::timestamp_nanos_out_of_range())?;
        Self::from_unix_timestamp(value.seconds, nanos)
    }
}

impl From<Time> for Timestamp {
    fn from(value: Time) -> Self {
        let t = value.0.assume_utc();
        let seconds = t.unix_timestamp();
        // Safe to convert to i32 because .nanosecond()
        // is guaranteed to return a value in 0..1_000_000_000 range.
        let nanos = t.nanosecond() as i32;
        Timestamp { seconds, nanos }
    }
}

impl Time {
    #[cfg(feature = "clock")]
    pub fn now() -> Time {
        OffsetDateTime::now_utc().try_into().unwrap()
    }

    // Internal helper to produce a `Time` value validated with regard to
    // the date range allowed in protobuf timestamps.
    // The source `OffsetDateTime` value must have the zero UTC offset.
    fn from_utc(t: OffsetDateTime) -> Result<Self, Error> {
        debug_assert_eq!(t.offset(), offset!(UTC));
        match t.year() {
            1..=9999 => Ok(Self(PrimitiveDateTime::new(t.date(), t.time()))),
            _ => Err(Error::date_out_of_range()),
        }
    }

    /// Get the unix epoch ("1970-01-01 00:00:00 UTC") as a [`Time`]
    pub fn unix_epoch() -> Self {
        Self(datetime!(1970-01-01 00:00:00))
    }

    pub fn from_unix_timestamp(secs: i64, nanos: u32) -> Result<Self, Error> {
        if nanos > 999_999_999 {
            return Err(Error::timestamp_nanos_out_of_range());
        }
        let total_nanos = secs as i128 * 1_000_000_000 + nanos as i128;
        match OffsetDateTime::from_unix_timestamp_nanos(total_nanos) {
            Ok(odt) => Self::from_utc(odt),
            _ => Err(Error::timestamp_conversion()),
        }
    }

    /// Calculate the amount of time which has passed since another [`Time`]
    /// as a [`core::time::Duration`]
    pub fn duration_since(&self, other: Time) -> Result<Duration, Error> {
        let duration = self.0.assume_utc() - other.0.assume_utc();
        duration
            .try_into()
            .map_err(|_| Error::duration_out_of_range())
    }

    /// Parse [`Time`] from an RFC 3339 date
    pub fn parse_from_rfc3339(s: &str) -> Result<Self, Error> {
        let date = OffsetDateTime::parse(s, &Rfc3339)
            .map_err(Error::time_parse)?
            .to_offset(offset!(UTC));
        Self::from_utc(date)
    }

    /// Return an RFC 3339 and ISO 8601 date and time string with subseconds (if nonzero) and Z.
    pub fn to_rfc3339(&self) -> String {
        timestamp::to_rfc3339_nanos(self.0.assume_utc())
    }

    /// Return a Unix timestamp in seconds.
    pub fn unix_timestamp(&self) -> i64 {
        self.0.assume_utc().unix_timestamp()
    }

    /// Return a Unix timestamp in nanoseconds.
    pub fn unix_timestamp_nanos(&self) -> i128 {
        self.0.assume_utc().unix_timestamp_nanos()
    }

    /// Computes `self + duration`, returning `None` if an overflow occurred.
    pub fn checked_add(self, duration: Duration) -> Option<Self> {
        let duration = duration.try_into().ok()?;
        let t = self.0.checked_add(duration)?;
        Self::from_utc(t.assume_utc()).ok()
    }

    /// Computes `self - duration`, returning `None` if an overflow occurred.
    pub fn checked_sub(self, duration: Duration) -> Option<Self> {
        let duration = duration.try_into().ok()?;
        let t = self.0.checked_sub(duration)?;
        Self::from_utc(t.assume_utc()).ok()
    }

    /// Check whether this time is before the given time.
    pub fn before(&self, other: Time) -> bool {
        self.0.assume_utc() < other.0.assume_utc()
    }

    /// Check whether this time is after the given time.
    pub fn after(&self, other: Time) -> bool {
        self.0.assume_utc() > other.0.assume_utc()
    }
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        timestamp::fmt_as_rfc3339_nanos(self.0.assume_utc(), f)
    }
}

impl FromStr for Time {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_from_rfc3339(s)
    }
}

impl TryFrom<OffsetDateTime> for Time {
    type Error = Error;

    fn try_from(t: OffsetDateTime) -> Result<Time, Error> {
        Self::from_utc(t.to_offset(offset!(UTC)))
    }
}

impl From<Time> for OffsetDateTime {
    fn from(t: Time) -> OffsetDateTime {
        t.0.assume_utc()
    }
}

impl Add<Duration> for Time {
    type Output = Result<Self, Error>;

    fn add(self, rhs: Duration) -> Self::Output {
        let duration = rhs.try_into().map_err(|_| Error::duration_out_of_range())?;
        let t = self
            .0
            .checked_add(duration)
            .ok_or_else(Error::duration_out_of_range)?;
        Self::from_utc(t.assume_utc())
    }
}

impl Sub<Duration> for Time {
    type Output = Result<Self, Error>;

    fn sub(self, rhs: Duration) -> Self::Output {
        let duration = rhs.try_into().map_err(|_| Error::duration_out_of_range())?;
        let t = self
            .0
            .checked_sub(duration)
            .ok_or_else(Error::duration_out_of_range)?;
        Self::from_utc(t.assume_utc())
    }
}

/// Parse [`Time`] from a type
pub trait ParseTimestamp {
    /// Parse [`Time`], or return an [`Error`] if parsing failed
    fn parse_timestamp(&self) -> Result<Time, Error>;
}

#[cfg(test)]
mod tests {
    use proptest::{prelude::*, sample::select};
    use tendermint_pbt_gen as pbt;
    use time::{Date, Month::*};

    use super::*;
    use crate::error::ErrorDetail;

    // We want to make sure that these timestamps specifically get tested.
    fn particular_rfc3339_timestamps() -> impl Strategy<Value = String> {
        let strs: Vec<String> = vec![
            "0001-01-01T00:00:00Z",
            "9999-12-31T23:59:59.999999999Z",
            "2020-09-14T16:33:54.21191421Z",
            "2020-09-14T16:33:00Z",
            "2020-09-14T16:33:00.1Z",
            "2020-09-14T16:33:00.211914212Z",
            "1970-01-01T00:00:00Z",
            "2021-01-07T20:25:56.0455760Z",
            "2021-01-07T20:25:57.039219Z",
            "2021-01-07T20:25:58.03562100Z",
            "2021-01-07T20:25:59.000955200Z",
            "2021-01-07T20:26:04.0121030Z",
            "2021-01-07T20:26:05.005096Z",
            "2021-01-07T20:26:09.08488400Z",
            "2021-01-07T20:26:11.0875340Z",
            "2021-01-07T20:26:12.078268Z",
            "2021-01-07T20:26:13.08074100Z",
            "2021-01-07T20:26:15.079663000Z",
        ]
        .into_iter()
        .map(String::from)
        .collect();

        select(strs)
    }

    fn particular_datetimes_out_of_range() -> impl Strategy<Value = OffsetDateTime> {
        let dts = vec![
            datetime!(0000-12-31 23:59:59.999999999 UTC),
            datetime!(0001-01-01 00:00:00.999999999 +00:00:01),
            Date::from_calendar_date(-1, October, 9)
                .unwrap()
                .midnight()
                .assume_utc(),
        ];
        select(dts)
    }

    proptest! {
        #[test]
        fn can_parse_rfc3339_timestamps(stamp in pbt::time::arb_protobuf_safe_rfc3339_timestamp()) {
            prop_assert!(stamp.parse::<Time>().is_ok())
        }

        #[test]
        fn serde_from_value_is_the_inverse_of_to_value_within_reasonable_time_range(
            datetime in pbt::time::arb_protobuf_safe_datetime()
        ) {
            // If `from_value` is the inverse of `to_value`, then it will always
            // map the JSON `encoded_time` to back to the initial `time`.
            let time: Time = datetime.try_into().unwrap();
            let json_encoded_time = serde_json::to_value(time).unwrap();
            let decoded_time: Time = serde_json::from_value(json_encoded_time).unwrap();
            prop_assert_eq!(time, decoded_time);
        }

        #[test]
        fn serde_of_rfc3339_timestamps_is_safe(
            stamp in prop_oneof![
                pbt::time::arb_protobuf_safe_rfc3339_timestamp(),
                particular_rfc3339_timestamps(),
            ]
        ) {
            // ser/de of rfc3339 timestamps is safe if it never panics.
            // This differs from the the inverse test in that we are testing on
            // arbitrarily generated textual timestamps, rather than times in a
            // range. Tho we do incidentally test the inversion as well.
            let time: Time = stamp.parse().unwrap();
            let json_encoded_time = serde_json::to_value(time).unwrap();
            let decoded_time: Time = serde_json::from_value(json_encoded_time).unwrap();
            prop_assert_eq!(time, decoded_time);
        }

        #[test]
        fn conversion_unix_timestamp_is_safe(
            stamp in prop_oneof![
                pbt::time::arb_protobuf_safe_rfc3339_timestamp(),
                particular_rfc3339_timestamps(),
            ]
        ) {
            let time: Time = stamp.parse().unwrap();
            let timestamp = time.unix_timestamp();
            let parsed = Time::from_unix_timestamp(timestamp, 0).unwrap();
            prop_assert_eq!(timestamp, parsed.unix_timestamp());
        }

        #[test]
        fn conversion_from_datetime_succeeds_for_4_digit_ce_years(
            datetime in prop_oneof![
                pbt::time::arb_datetime_with_offset(),
                particular_datetimes_out_of_range(),
            ]
        ) {
            let res: Result<Time, _> = datetime.try_into();
            match datetime.to_offset(offset!(UTC)).year() {
                1 ..= 9999 => {
                    let t = res.unwrap();
                    let dt_converted_back: OffsetDateTime = t.into();
                    assert_eq!(dt_converted_back, datetime);
                }
                _ => {
                    let e = res.unwrap_err();
                    assert!(matches!(e.detail(), ErrorDetail::DateOutOfRange(_)))
                }
            }
        }

        #[test]
        fn from_unix_timestamp_rejects_out_of_range_nanos(
            datetime in pbt::time::arb_protobuf_safe_datetime(),
            nanos in 1_000_000_000 ..= u32::MAX,
        ) {
            let secs = datetime.unix_timestamp();
            let res = Time::from_unix_timestamp(secs, nanos);
            let e = res.unwrap_err();
            assert!(matches!(e.detail(), ErrorDetail::TimestampNanosOutOfRange(_)))
        }
    }

    fn duration_from_nanos(whole_nanos: u128) -> Duration {
        let secs: u64 = (whole_nanos / 1_000_000_000).try_into().unwrap();
        let nanos = (whole_nanos % 1_000_000_000) as u32;
        Duration::new(secs, nanos)
    }

    prop_compose! {
        fn args_for_regular_add()
            (t in pbt::time::arb_protobuf_safe_datetime())
            (
                t in Just(t),
                d_nanos in 0 ..= (pbt::time::max_protobuf_time() - t).whole_nanoseconds() as u128,
            ) -> (OffsetDateTime, Duration)
            {
                (t, duration_from_nanos(d_nanos))
            }
    }

    prop_compose! {
        fn args_for_regular_sub()
            (t in pbt::time::arb_protobuf_safe_datetime())
            (
                t in Just(t),
                d_nanos in 0 ..= (t - pbt::time::min_protobuf_time()).whole_nanoseconds() as u128,
            ) -> (OffsetDateTime, Duration)
            {
                (t, duration_from_nanos(d_nanos))
            }
    }

    prop_compose! {
        fn args_for_overflowed_add()
            (t in pbt::time::arb_protobuf_safe_datetime())
            (
                t in Just(t),
                d_nanos in (
                    (pbt::time::max_protobuf_time() - t).whole_nanoseconds() as u128 + 1
                    ..=
                    Duration::MAX.as_nanos()
                ),
            ) -> (OffsetDateTime, Duration)
            {
                (t, duration_from_nanos(d_nanos))
            }
    }

    prop_compose! {
        fn args_for_overflowed_sub()
            (t in pbt::time::arb_protobuf_safe_datetime())
            (
                t in Just(t),
                d_nanos in (
                    (t - pbt::time::min_protobuf_time()).whole_nanoseconds() as u128 + 1
                    ..=
                    Duration::MAX.as_nanos()
                ),
            ) -> (OffsetDateTime, Duration)
            {
                (t, duration_from_nanos(d_nanos))
            }
    }

    proptest! {
        #[test]
        fn checked_add_regular((dt, d) in args_for_regular_add()) {
            let t: Time = dt.try_into().unwrap();
            let t = t.checked_add(d).unwrap();
            let res: OffsetDateTime = t.into();
            assert_eq!(res, dt + d);
        }

        #[test]
        fn checked_sub_regular((dt, d) in args_for_regular_sub()) {
            let t: Time = dt.try_into().unwrap();
            let t = t.checked_sub(d).unwrap();
            let res: OffsetDateTime = t.into();
            assert_eq!(res, dt - d);
        }

        #[test]
        fn checked_add_overflow((dt, d) in args_for_overflowed_add()) {
            let t: Time = dt.try_into().unwrap();
            assert_eq!(t.checked_add(d), None);
        }

        #[test]
        fn checked_sub_overflow((dt, d) in args_for_overflowed_sub()) {
            let t: Time = dt.try_into().unwrap();
            assert_eq!(t.checked_sub(d), None);
        }
    }
}