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
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_runtime::RuntimeDebug;
use sp_std::vec::Vec;

pub const SECONDS_PER_HOUR: u32 = 3600;
pub const SECONDS_PER_YEAR: u32 = 31557600;
pub const SECONDS_PER_BLOCK: u32 = 12;
pub const BLOCKS_PER_HOUR: u32 = SECONDS_PER_HOUR / SECONDS_PER_BLOCK;
pub const BLOCKS_PER_DAY: u32 = 24 * BLOCKS_PER_HOUR;
pub const BLOCKS_PER_YEAR: u32 = SECONDS_PER_YEAR / SECONDS_PER_BLOCK;
pub const DEFAULT_ROUND_TERM: u32 = 6 * BLOCKS_PER_HOUR;

/// A range consisting of min, ideal, and max.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(
    Eq,
    PartialEq,
    Clone,
    Copy,
    Encode,
    Decode,
    Default,
    RuntimeDebug,
    MaxEncodedLen,
    TypeInfo,
    PartialOrd,
    Ord,
)]
pub struct Range<T> {
    pub min: T,
    pub ideal: T,
    pub max: T,
}

impl<T: Ord> Range<T> {
    pub fn is_valid(&self) -> bool {
        self.min <= self.ideal && self.ideal <= self.max
    }
}

/// Round identifier (one-based).
pub type RoundIndex = u32;

/// General round information consisting ofindex (one-based), head
/// (beginning block number), and term (round length in number of blocks).
#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct RoundInfo<BlockNumber> {
    /// Current round index.
    pub index: RoundIndex,
    /// The first block of the current round.
    pub head: BlockNumber,
    /// The length of the current round in number of blocks.
    pub term: BlockNumber,
}

impl<
        B: Copy + sp_std::ops::Add<Output = B> + sp_std::ops::Sub<Output = B> + From<u32> + PartialOrd,
    > RoundInfo<B>
{
    pub fn new(index: RoundIndex, head: B, term: B) -> RoundInfo<B> {
        RoundInfo { index, head, term }
    }

    /// Check if the round should be updated
    pub fn should_update(&self, now: B) -> bool {
        now - self.head >= self.term
    }

    /// New round
    pub fn update(&mut self, now: B) {
        self.index = self.index.saturating_add(1u32);
        self.head = now;
    }
}

impl<
        B: Copy + sp_std::ops::Add<Output = B> + sp_std::ops::Sub<Output = B> + From<u32> + PartialOrd,
    > Default for RoundInfo<B>
{
    fn default() -> RoundInfo<B> {
        RoundInfo::new(1u32, 1u32.into(), 299u32.into())
    }
}

/// An ordered set backed by `Vec`.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Default, Clone, TypeInfo)]
pub struct OrderedSet<T>(pub Vec<T>);

impl<T: Ord> OrderedSet<T> {
    /// Create a new empty set
    pub fn new() -> Self {
        Self(Vec::new())
    }

    /// Create a set from a `Vec`.
    /// `v` will be sorted and dedup first.
    pub fn from(mut v: Vec<T>) -> Self {
        v.sort();
        v.dedup();
        Self::from_sorted_set(v)
    }

    /// Create a set from a `Vec`.
    /// Assume `v` is sorted and contain unique elements.
    pub fn from_sorted_set(v: Vec<T>) -> Self {
        Self(v)
    }

    /// Insert an element.
    /// Return true if insertion happened.
    pub fn insert(&mut self, value: T) -> bool {
        match self.0.binary_search(&value) {
            Ok(_) => false,
            Err(loc) => {
                self.0.insert(loc, value);
                true
            },
        }
    }

    /// Remove an element.
    /// Return true if removal happened.
    pub fn remove(&mut self, value: &T) -> bool {
        match self.0.binary_search(value) {
            Ok(loc) => {
                self.0.remove(loc);
                true
            },
            Err(_) => false,
        }
    }

    /// Return if the set contains `value`
    pub fn contains(&self, value: &T) -> bool {
        self.0.binary_search(value).is_ok()
    }

    /// Clear the set
    pub fn clear(&mut self) {
        self.0.clear();
    }
}

impl<T: Ord> From<Vec<T>> for OrderedSet<T> {
    fn from(v: Vec<T>) -> Self {
        Self::from(v)
    }
}

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

    #[test]
    fn test_should_update() {
        let mut r = RoundInfo::<u32>::new(1, 1, 400);
        assert!(r.should_update(402));
        assert!(r.should_update(401));
        r.head = 50;
        assert!(!r.should_update(50));
    }
}