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
use chrono::{DateTime, NaiveDateTime, SecondsFormat, Utc};
use std::num::TryFromIntError;
const _ISO_FORMAT: &str = "%FT%X.%.9F";
pub const EPOCH_DURATION_SECONDS: i64 = 30;
pub type ChainEpoch = i64;
pub const EPOCH_UNDEFINED: ChainEpoch = -1;
pub struct ChainEpochClock {
genesis_time: DateTime<Utc>,
}
impl ChainEpochClock {
pub fn new(genesis_time: i64) -> ChainEpochClock {
let native_date_time = NaiveDateTime::from_timestamp(genesis_time, 0);
let date_time = DateTime::<Utc>::from_utc(native_date_time, Utc);
date_time.to_rfc3339_opts(SecondsFormat::Nanos, true);
ChainEpochClock {
genesis_time: date_time,
}
}
pub fn get_genesis_time(&self) -> DateTime<Utc> {
self.genesis_time
}
pub fn epoch_at_time(&self, time: &DateTime<Utc>) -> Result<ChainEpoch, TryFromIntError> {
let difference = time.signed_duration_since(self.genesis_time);
let epochs = (difference / EPOCH_DURATION_SECONDS as i32)
.num_nanoseconds()
.expect("Epoch_at_time failed");
Ok(epochs)
}
}