mithril_era/
era_checker.rs

1use std::sync::RwLock;
2
3use mithril_common::api_version::ApiVersionDiscriminantSource;
4use mithril_common::entities::{Epoch, SupportedEra};
5
6struct SupportedEraStamp {
7    era: SupportedEra,
8    epoch: Epoch,
9}
10
11/// EraChecker allows the verification of the current era
12pub struct EraChecker {
13    current_era_stamp: RwLock<SupportedEraStamp>,
14}
15
16impl EraChecker {
17    /// Era checker factory
18    pub fn new(era: SupportedEra, epoch: Epoch) -> Self {
19        Self {
20            current_era_stamp: RwLock::new(SupportedEraStamp { era, epoch }),
21        }
22    }
23
24    /// Retrieve the current era
25    pub fn current_era(&self) -> SupportedEra {
26        self.current_era_stamp.read().unwrap().era
27    }
28
29    /// Retrieve the Epoch the checker was the last updated.
30    pub fn current_epoch(&self) -> Epoch {
31        self.current_era_stamp.read().unwrap().epoch
32    }
33
34    /// Change the current era
35    pub fn change_era(&self, new_era: SupportedEra, current_epoch: Epoch) {
36        let new_stamp = SupportedEraStamp {
37            era: new_era,
38            epoch: current_epoch,
39        };
40        let mut stamp = self.current_era_stamp.write().unwrap();
41        *stamp = new_stamp;
42    }
43
44    /// Check if an era is active
45    pub fn is_era_active(&self, era: SupportedEra) -> bool {
46        self.current_era() == era
47    }
48}
49
50impl ApiVersionDiscriminantSource for EraChecker {
51    fn get_discriminant(&self) -> String {
52        self.current_era().to_string()
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use mithril_common::test::double::Dummy;
59
60    use super::*;
61
62    #[test]
63    fn can_change_era() {
64        let expected_era = SupportedEra::dummy();
65        let era_checker = EraChecker::new(expected_era, Epoch(1));
66        era_checker.change_era(expected_era, Epoch(2));
67
68        assert_eq!(expected_era, era_checker.current_era());
69        assert_eq!(Epoch(2), era_checker.current_epoch());
70        assert!(era_checker.is_era_active(expected_era));
71    }
72
73    #[test]
74    fn get_discriminant_return_current_era_string() {
75        let expected_era = SupportedEra::dummy();
76        let era_checker = EraChecker::new(expected_era, Epoch(1));
77
78        assert_eq!(expected_era.to_string(), era_checker.get_discriminant());
79    }
80}