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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
use std::{
    cmp::Ordering,
    fmt::{Display, Formatter, Result},
    ops::{Deref, Range},
};

use crate::{
    crypto_helper::{MKMapKey, MKTreeNode},
    StdResult,
};

/// BlockNumber is the block number of a Cardano transaction.
pub type BlockNumber = u64;

/// BlockRangeLength is the length of a block range.
pub type BlockRangeLength = u64;

/// BlockRange for the Cardano chain
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Debug, Hash)]
pub struct BlockRange {
    inner_range: Range<u64>,
}

impl BlockRange {
    /// The length of the block range
    /// Important: this value should be updated with extreme care (probably with an era change) in order to avoid signing disruptions.
    pub const LENGTH: BlockRangeLength = 15;

    /// BlockRange factory
    pub fn new(start: BlockNumber, end: BlockNumber) -> Self {
        Self {
            inner_range: start..end,
        }
    }

    cfg_test_tools! {
        /// Try to add two BlockRanges
        pub fn try_add(&self, other: &BlockRange) -> StdResult<BlockRange> {
            if self.inner_range.end.max(other.inner_range.end)
                < self.inner_range.start.min(other.inner_range.start)
            {
                return Err(anyhow!(
                    "BlockRange cannot be added as they don't strictly overlap"
                ));
            }

            Ok(Self {
                inner_range: Range {
                    start: self.inner_range.start.min(other.inner_range.start),
                    end: self.inner_range.end.max(other.inner_range.end),
                },
            })
        }
    }

    /// Create a BlockRange from a block number
    pub fn from_block_number(number: BlockNumber) -> Self {
        // Unwrap is safe as the length is always strictly greater than 0
        Self::from_block_number_and_length(number, Self::LENGTH).unwrap()
    }

    /// Create a BlockRange from a block number and a range length
    pub(crate) fn from_block_number_and_length(
        number: BlockNumber,
        length: BlockRangeLength,
    ) -> StdResult<Self> {
        if length == 0 {
            return Err(anyhow!(
                "BlockRange cannot be be computed with a length of 0"
            ));
        }
        // The formula used to compute the lower bound of the block range is `⌊number / length⌋ * length`
        // The computation of the floor is done with the integer division `/` of Rust
        let block_range_start = (number / length) * length;
        let block_range_end = block_range_start + length;
        Ok(Self {
            inner_range: block_range_start..block_range_end,
        })
    }
}

impl Display for BlockRange {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "[{},{}[", self.inner_range.start, self.inner_range.end)
    }
}

impl Deref for BlockRange {
    type Target = Range<u64>;

    fn deref(&self) -> &Self::Target {
        &self.inner_range
    }
}

impl PartialOrd for BlockRange {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(std::cmp::Ord::cmp(self, other))
    }
}

impl Ord for BlockRange {
    fn cmp(&self, other: &Self) -> Ordering {
        // Order by range start, then by range end
        match self.inner_range.start.cmp(&other.inner_range.start) {
            Ordering::Equal => self.inner_range.end.cmp(&other.inner_range.end),
            order => order,
        }
    }
}

impl From<Range<u64>> for BlockRange {
    fn from(other: Range<u64>) -> Self {
        BlockRange { inner_range: other }
    }
}

impl From<BlockRange> for MKTreeNode {
    fn from(other: BlockRange) -> Self {
        let start = other.start.to_string();
        let end = other.end.to_string();
        let mut bytes = vec![];
        bytes.extend_from_slice(start.as_bytes());
        bytes.extend_from_slice("-".as_bytes());
        bytes.extend_from_slice(end.as_bytes());
        MKTreeNode::new(bytes)
    }
}

impl MKMapKey for BlockRange {}

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

    #[test]
    fn test_block_range_cmp() {
        assert_eq!(BlockRange::new(1, 10), BlockRange::new(1, 10));
        assert_ne!(BlockRange::new(1, 10), BlockRange::new(1, 11));
        assert_ne!(BlockRange::new(1, 10), BlockRange::new(2, 10));
        assert_ne!(BlockRange::new(1, 11), BlockRange::new(2, 10));

        assert!(BlockRange::new(1, 10) < BlockRange::new(1, 11));
        assert!(BlockRange::new(1, 10) < BlockRange::new(2, 10));
        assert!(BlockRange::new(1, 11) < BlockRange::new(2, 10));
    }

    #[test]
    fn test_block_range_try_add() {
        assert_eq!(
            BlockRange::new(1, 10)
                .try_add(&BlockRange::new(1, 10))
                .unwrap(),
            BlockRange::new(1, 10)
        );
        assert_eq!(
            BlockRange::new(1, 10)
                .try_add(&BlockRange::new(1, 11))
                .unwrap(),
            BlockRange::new(1, 11)
        );
        assert_eq!(
            BlockRange::new(1, 10)
                .try_add(&BlockRange::new(2, 10))
                .unwrap(),
            BlockRange::new(1, 10)
        );
    }

    #[test]
    fn test_block_range_from_number() {
        assert_eq!(BlockRange::from_block_number(0), BlockRange::new(0, 15));
        assert_eq!(BlockRange::from_block_number(1), BlockRange::new(0, 15));
        assert_eq!(BlockRange::from_block_number(14), BlockRange::new(0, 15));
        assert_eq!(BlockRange::from_block_number(15), BlockRange::new(15, 30));
        assert_eq!(BlockRange::from_block_number(16), BlockRange::new(15, 30));
        assert_eq!(BlockRange::from_block_number(29), BlockRange::new(15, 30));
    }

    #[test]
    fn test_block_range_from_number_and_length_with_valid_input() {
        assert_eq!(
            BlockRange::from_block_number_and_length(0, 10).unwrap(),
            BlockRange::new(0, 10)
        );
        assert_eq!(
            BlockRange::from_block_number_and_length(1, 10).unwrap(),
            BlockRange::new(0, 10)
        );
        assert_eq!(
            BlockRange::from_block_number_and_length(9, 10).unwrap(),
            BlockRange::new(0, 10)
        );
        assert_eq!(
            BlockRange::from_block_number_and_length(10, 10).unwrap(),
            BlockRange::new(10, 20)
        );
        assert_eq!(
            BlockRange::from_block_number_and_length(11, 10).unwrap(),
            BlockRange::new(10, 20)
        );
        assert_eq!(
            BlockRange::from_block_number_and_length(19, 10).unwrap(),
            BlockRange::new(10, 20)
        );
    }

    #[test]
    fn test_block_range_from_number_and_length_with_invalid_input() {
        BlockRange::from_block_number_and_length(10, 0)
            .expect_err("BlockRange should not be computed with a length of 0");
    }
}