mithril_common/era/
era_checker.rs

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