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
use parity_scale_codec::{Decode, Encode};
use serde::{Deserialize, Serialize};

use crate::phron_primitives::BlockNumber;

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SessionBoundaries {
    first_block: BlockNumber,
    last_block: BlockNumber,
}

impl SessionBoundaries {
    pub fn first_block(&self) -> BlockNumber {
        self.first_block
    }

    pub fn last_block(&self) -> BlockNumber {
        self.last_block
    }
}

#[derive(Clone, Debug)]
pub struct SessionBoundaryInfo {
    session_period: SessionPeriod,
}

/// Struct for getting the session boundaries.
impl SessionBoundaryInfo {
    pub const fn new(session_period: SessionPeriod) -> Self {
        Self { session_period }
    }

    pub fn boundaries_for_session(&self, session_id: SessionId) -> SessionBoundaries {
        SessionBoundaries {
            first_block: self.first_block_of_session(session_id),
            last_block: self.last_block_of_session(session_id),
        }
    }

    /// Returns session id of the session that block belongs to.
    pub fn session_id_from_block_num(&self, n: BlockNumber) -> SessionId {
        SessionId(n / self.session_period.0)
    }

    /// Returns block number which is the last block of the session.
    pub fn last_block_of_session(&self, session_id: SessionId) -> BlockNumber {
        (session_id.0 + 1) * self.session_period.0 - 1
    }

    /// Returns block number which is the first block of the session.
    pub fn first_block_of_session(&self, session_id: SessionId) -> BlockNumber {
        session_id.0 * self.session_period.0
    }
}

#[cfg(test)]
pub mod testing {
    use sp_runtime::testing::UintAuthorityId;

    use crate::phron_primitives::SessionAuthorityData;

    pub fn authority_data(from: u32, to: u32) -> SessionAuthorityData {
        SessionAuthorityData::new(
            (from..to)
                .map(|id| UintAuthorityId(id.into()).to_public_key())
                .collect(),
            None,
        )
    }
}

#[derive(
    Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd,
    Encode, Decode, Serialize, Deserialize
)]
pub struct SessionId(pub u32);

impl SessionId {
    /// The id of the session following this one.
    pub fn next(&self) -> Self {
        SessionId(self.0 + 1)
    }
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd, Encode, Decode)]
pub struct SessionPeriod(pub u32);