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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright (c) 2022 MASSA LABS <info@massa.net>

//! warning: assumes `thread_count >= 1, t0_millis >= 1, t0_millis % thread_count == 0`

use massa_time::MassaTime;
use std::convert::TryInto;

use crate::{error::ModelsError, slot::Slot};

/// Counts the number of slots in a slot range [a, b)
///
/// # Arguments
/// * `a`: starting slot (included)
/// * `b`: ending slot (excluded)
/// * `thread_count`: number of threads
pub fn slot_count_in_range(a: Slot, b: Slot, thread_count: u8) -> Result<u64, ModelsError> {
    b.period
        .checked_sub(a.period)
        .ok_or(ModelsError::TimeOverflowError)?
        .checked_mul(thread_count as u64)
        .ok_or(ModelsError::TimeOverflowError)?
        .checked_add(b.thread as u64)
        .ok_or(ModelsError::TimeOverflowError)?
        .checked_sub(a.thread as u64)
        .ok_or(ModelsError::TimeOverflowError)
}

/// Gets timestamp in milliseconds for given slot.
///
/// # Arguments
/// * `thread_count`: number of threads.
/// * `t0`: time in milliseconds between two periods in the same thread.
/// * `slot`: the considered slot.
pub fn get_block_slot_timestamp(
    thread_count: u8,
    t0: MassaTime,
    genesis_timestamp: MassaTime,
    slot: Slot,
) -> Result<MassaTime, ModelsError> {
    let base: MassaTime = t0
        .checked_div_u64(thread_count as u64)
        .map_err(|_| ModelsError::TimeOverflowError)?
        .checked_mul(slot.thread as u64)
        .map_err(|_| ModelsError::TimeOverflowError)?;
    let shift: MassaTime = t0
        .checked_mul(slot.period)
        .map_err(|_| ModelsError::TimeOverflowError)?;
    genesis_timestamp
        .checked_add(base)
        .map_err(|_| ModelsError::TimeOverflowError)?
        .checked_add(shift)
        .map_err(|_| ModelsError::TimeOverflowError)
}

/// Returns the thread and block period index of the latest block slot at a given timestamp (inclusive), if any happened
///
/// # Arguments
/// * `thread_count`: number of threads.
/// * `t0`: time in milliseconds between two periods in the same thread.
/// * `genesis_timestamp`: when the blockclique first started, in milliseconds.
/// * `timestamp`: target timestamp in milliseconds.
pub fn get_latest_block_slot_at_timestamp(
    thread_count: u8,
    t0: MassaTime,
    genesis_timestamp: MassaTime,
    timestamp: MassaTime,
) -> Result<Option<Slot>, ModelsError> {
    if let Ok(time_since_genesis) = timestamp.checked_sub(genesis_timestamp) {
        let thread: u8 = time_since_genesis
            .checked_rem_time(t0)?
            .checked_div_time(t0.checked_div_u64(thread_count as u64)?)?
            as u8;
        return Ok(Some(Slot::new(
            time_since_genesis.checked_div_time(t0)?,
            thread,
        )));
    }
    Ok(None)
}

/// Returns the thread and block slot index of the current block slot (inclusive), if any happened yet
///
/// # Arguments
/// * `thread_count`: number of threads.
/// * `t0`: time in milliseconds between two periods in the same thread.
/// * `genesis_timestamp`: when the blockclique first started, in milliseconds.
pub fn get_current_latest_block_slot(
    thread_count: u8,
    t0: MassaTime,
    genesis_timestamp: MassaTime,
) -> Result<Option<Slot>, ModelsError> {
    get_latest_block_slot_at_timestamp(thread_count, t0, genesis_timestamp, MassaTime::now())
}

/// Turns an `MassaTime` range [start, end) with optional start/end to a `Slot` range [start, end) with optional start/end
///
/// # Arguments
/// * `thread_count`: number of threads.
/// * `t0`: time in milliseconds between two periods in the same thread.
/// * `genesis_timestamp`: when the blockclique first started, in milliseconds
/// * `start_time`: optional start time
/// * `end_time`: optional end time
/// # Returns
/// `(Option<Slot>, Option<Slot>)` pair of options representing the start (included) and end (excluded) slots
/// or `ConsensusError` on error
pub fn time_range_to_slot_range(
    thread_count: u8,
    t0: MassaTime,
    genesis_timestamp: MassaTime,
    start_time: Option<MassaTime>,
    end_time: Option<MassaTime>,
) -> Result<(Option<Slot>, Option<Slot>), ModelsError> {
    let start_slot = match start_time {
        None => None,
        Some(t) => {
            let inter_slot = t0.checked_div_u64(thread_count as u64)?;
            let slot_number: u64 = t
                .saturating_sub(genesis_timestamp)
                .checked_add(inter_slot)?
                .saturating_sub(MassaTime::EPSILON)
                .checked_div_time(inter_slot)?;
            Some(Slot::new(
                slot_number
                    .checked_div(thread_count as u64)
                    .ok_or(ModelsError::TimeOverflowError)?,
                slot_number
                    .checked_rem(thread_count as u64)
                    .ok_or(ModelsError::TimeOverflowError)?
                    .try_into()
                    .map_err(|_| ModelsError::ThreadOverflowError)?,
            ))
        }
    };

    let end_slot = match end_time {
        None => None,
        Some(t) => {
            let inter_slot = t0.checked_div_u64(thread_count as u64)?;
            let slot_number: u64 = t
                .saturating_sub(genesis_timestamp)
                .checked_add(inter_slot)?
                .saturating_sub(MassaTime::EPSILON)
                .checked_div_time(inter_slot)?;
            Some(Slot::new(
                slot_number
                    .checked_div(thread_count as u64)
                    .ok_or(ModelsError::TimeOverflowError)?,
                slot_number
                    .checked_rem(thread_count as u64)
                    .ok_or(ModelsError::TimeOverflowError)?
                    .try_into()
                    .map_err(|_| ModelsError::ThreadOverflowError)?,
            ))
        }
    };

    Ok((start_slot, end_slot))
}

/// TODO DOC
pub fn get_closest_slot_to_timestamp(
    thread_count: u8,
    t0: MassaTime,
    genesis_timestamp: MassaTime,
    timestamp: MassaTime,
) -> Slot {
    // get the latest past slot at this timestamp (if any)
    let latest_past_slot =
        match get_latest_block_slot_at_timestamp(thread_count, t0, genesis_timestamp, timestamp)
            .unwrap()
        {
            None => return Slot::new(0, 0), // we are before genesis
            Some(s) => s,
        };

    // compute the time of the latest past slot
    let t_latest = get_block_slot_timestamp(
        thread_count,
        t0,
        genesis_timestamp,
        latest_past_slot
    ).expect("t_latest computation failed but it should be computable because that slot was obtained with get_latest_block_slot_at_timestamp");

    // compute how much time has passed since that latest slot
    let delta_t = timestamp.saturating_sub(t_latest);

    // check whether delta_t is lower than half the time difference between two consecutive slots
    if delta_t
        .checked_mul(2)
        .expect("delta_t should be multiplicate by 2")
        <= t0
            .checked_div_u64(thread_count as u64)
            .expect("thread_count should not be 0")
    {
        latest_past_slot
    } else {
        latest_past_slot
            .get_next_slot(thread_count)
            .unwrap_or(latest_past_slot)
    }
}

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

    #[test]
    #[serial]
    fn test_slot_count_in_range() {
        assert_eq!(
            slot_count_in_range(Slot::new(100, 3), Slot::new(100, 3), 32).unwrap(),
            0
        );
        assert_eq!(
            slot_count_in_range(Slot::new(100, 3), Slot::new(100, 5), 32).unwrap(),
            2
        );
        assert_eq!(
            slot_count_in_range(Slot::new(100, 4), Slot::new(103, 13), 32).unwrap(),
            105
        );
        assert_eq!(
            slot_count_in_range(Slot::new(100, 13), Slot::new(103, 4), 32).unwrap(),
            87
        );
    }

    #[test]
    #[serial]
    fn test_time_range_to_slot_range() {
        let thread_count = 3u8;
        let t0: MassaTime = MassaTime::from_millis(30);
        let genesis_timestamp: MassaTime = MassaTime::from_millis(100);
        /* slots:   (0, 0)  (0, 1)  (0, 2)  (1, 0)  (1, 1)  (1, 2)  (2, 0)  (2, 1)  (2, 2)
            time:    100      110     120    130      140    150     160     170     180
        */

        // time [111, 115) => empty slot range
        let (out_start, out_end) = time_range_to_slot_range(
            thread_count,
            t0,
            genesis_timestamp,
            Some(MassaTime::from_millis(111)),
            Some(MassaTime::from_millis(115)),
        )
        .unwrap();
        assert_eq!(out_start, out_end);

        // time [10, 100) => empty slot range
        let (out_start, out_end) = time_range_to_slot_range(
            thread_count,
            t0,
            genesis_timestamp,
            Some(MassaTime::from_millis(10)),
            Some(MassaTime::from_millis(100)),
        )
        .unwrap();
        assert_eq!(out_start, out_end);

        // time [115, 145) => slots [(0,2), (1,2))
        let (out_start, out_end) = time_range_to_slot_range(
            thread_count,
            t0,
            genesis_timestamp,
            Some(MassaTime::from_millis(115)),
            Some(MassaTime::from_millis(145)),
        )
        .unwrap();
        assert_eq!(out_start, Some(Slot::new(0, 2)));
        assert_eq!(out_end, Some(Slot::new(1, 2)));

        // time [110, 160) => slots [(0,1), (2,0))
        let (out_start, out_end) = time_range_to_slot_range(
            thread_count,
            t0,
            genesis_timestamp,
            Some(MassaTime::from_millis(110)),
            Some(MassaTime::from_millis(160)),
        )
        .unwrap();
        assert_eq!(out_start, Some(Slot::new(0, 1)));
        assert_eq!(out_end, Some(Slot::new(2, 0)));
    }

    #[test]
    #[serial]
    fn test_get_closest_slot_to_timestamp() {
        let thread_count = 3u8;
        let t0: MassaTime = MassaTime::from_millis(30);
        let genesis_timestamp: MassaTime = MassaTime::from_millis(100);
        /* slots:   (0, 0)  (0, 1)  (0, 2)  (1, 0)  (1, 1)  (1, 2)  (2, 0)  (2, 1)  (2, 2)
            time:    100      110     120    130      140    150     160     170     180
        */
        let out_slot = get_closest_slot_to_timestamp(
            thread_count,
            t0,
            genesis_timestamp,
            MassaTime::from_millis(150),
        );
        assert_eq!(out_slot, Slot::new(1, 2));
    }
}