mithril_common/era/
era_checker.rs

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
use std::sync::RwLock;

use crate::entities::Epoch;

use super::SupportedEra;

struct SupportedEraStamp {
    era: SupportedEra,
    epoch: Epoch,
}

/// EraChecker allows the verification of the current era
pub struct EraChecker {
    current_era_stamp: RwLock<SupportedEraStamp>,
}

impl EraChecker {
    /// Era checker factory
    pub fn new(era: SupportedEra, epoch: Epoch) -> Self {
        Self {
            current_era_stamp: RwLock::new(SupportedEraStamp { era, epoch }),
        }
    }

    /// Retrieve the current era
    pub fn current_era(&self) -> SupportedEra {
        self.current_era_stamp.read().unwrap().era
    }

    /// Retrieve the Epoch the checker was the last updated.
    pub fn current_epoch(&self) -> Epoch {
        self.current_era_stamp.read().unwrap().epoch
    }

    /// Change the current era
    pub fn change_era(&self, new_era: SupportedEra, current_epoch: Epoch) {
        let new_stamp = SupportedEraStamp {
            era: new_era,
            epoch: current_epoch,
        };
        let mut stamp = self.current_era_stamp.write().unwrap();
        *stamp = new_stamp;
    }

    /// Check if an era is active
    pub fn is_era_active(&self, era: SupportedEra) -> bool {
        self.current_era() == era
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_change_era() {
        let expected_era = SupportedEra::dummy();
        let era_checker = EraChecker::new(expected_era, Epoch(1));
        era_checker.change_era(expected_era, Epoch(2));

        assert_eq!(expected_era, era_checker.current_era());
        assert_eq!(Epoch(2), era_checker.current_epoch());
        assert!(era_checker.is_era_active(expected_era));
    }
}