clone_solana_epoch_schedule/
lib.rs

1//! Configuration for epochs and slots.
2//!
3//! Epochs mark a period of time composed of _slots_, for which a particular
4//! [leader schedule][ls] is in effect. The epoch schedule determines the length
5//! of epochs, and the timing of the next leader-schedule selection.
6//!
7//! [ls]: https://docs.solanalabs.com/consensus/leader-rotation#leader-schedule-rotation
8//!
9//! The epoch schedule does not change during the life of a blockchain,
10//! though the length of an epoch does — during the initial launch of
11//! the chain there is a "warmup" period, where epochs are short, with subsequent
12//! epochs increasing in slots until they last for [`DEFAULT_SLOTS_PER_EPOCH`].
13//!
14//! [`DEFAULT_SLOTS_PER_EPOCH`]: https://docs.rs/solana-clock/latest/clone_solana_clock/constant.DEFAULT_SLOTS_PER_EPOCH.html
15#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
16#![no_std]
17#[cfg(feature = "frozen-abi")]
18extern crate std;
19
20#[cfg(feature = "sysvar")]
21pub mod sysvar;
22
23use clone_solana_sdk_macro::CloneZeroed;
24#[cfg(feature = "serde")]
25use serde_derive::{Deserialize, Serialize};
26
27// inlined to avoid clone_solana_clock dep
28const DEFAULT_SLOTS_PER_EPOCH: u64 = 432_000;
29#[cfg(test)]
30static_assertions::const_assert_eq!(
31    DEFAULT_SLOTS_PER_EPOCH,
32    clone_solana_clock::DEFAULT_SLOTS_PER_EPOCH
33);
34/// The default number of slots before an epoch starts to calculate the leader schedule.
35pub const DEFAULT_LEADER_SCHEDULE_SLOT_OFFSET: u64 = DEFAULT_SLOTS_PER_EPOCH;
36
37/// The maximum number of slots before an epoch starts to calculate the leader schedule.
38///
39/// Default is an entire epoch, i.e. leader schedule for epoch X is calculated at
40/// the beginning of epoch X - 1.
41pub const MAX_LEADER_SCHEDULE_EPOCH_OFFSET: u64 = 3;
42
43/// The minimum number of slots per epoch during the warmup period.
44///
45/// Based on `MAX_LOCKOUT_HISTORY` from `vote_program`.
46pub const MINIMUM_SLOTS_PER_EPOCH: u64 = 32;
47
48#[repr(C)]
49#[cfg_attr(
50    feature = "frozen-abi",
51    derive(clone_solana_frozen_abi_macro::AbiExample)
52)]
53#[cfg_attr(
54    feature = "serde",
55    derive(Deserialize, Serialize),
56    serde(rename_all = "camelCase")
57)]
58#[derive(Debug, CloneZeroed, PartialEq, Eq)]
59pub struct EpochSchedule {
60    /// The maximum number of slots in each epoch.
61    pub slots_per_epoch: u64,
62
63    /// A number of slots before beginning of an epoch to calculate
64    /// a leader schedule for that epoch.
65    pub leader_schedule_slot_offset: u64,
66
67    /// Whether epochs start short and grow.
68    pub warmup: bool,
69
70    /// The first epoch after the warmup period.
71    ///
72    /// Basically: `log2(slots_per_epoch) - log2(MINIMUM_SLOTS_PER_EPOCH)`.
73    pub first_normal_epoch: u64,
74
75    /// The first slot after the warmup period.
76    ///
77    /// Basically: `MINIMUM_SLOTS_PER_EPOCH * (2.pow(first_normal_epoch) - 1)`.
78    pub first_normal_slot: u64,
79}
80
81impl Default for EpochSchedule {
82    fn default() -> Self {
83        Self::custom(
84            DEFAULT_SLOTS_PER_EPOCH,
85            DEFAULT_LEADER_SCHEDULE_SLOT_OFFSET,
86            true,
87        )
88    }
89}
90
91impl EpochSchedule {
92    pub fn new(slots_per_epoch: u64) -> Self {
93        Self::custom(slots_per_epoch, slots_per_epoch, true)
94    }
95    pub fn without_warmup() -> Self {
96        Self::custom(
97            DEFAULT_SLOTS_PER_EPOCH,
98            DEFAULT_LEADER_SCHEDULE_SLOT_OFFSET,
99            false,
100        )
101    }
102    pub fn custom(slots_per_epoch: u64, leader_schedule_slot_offset: u64, warmup: bool) -> Self {
103        assert!(slots_per_epoch >= MINIMUM_SLOTS_PER_EPOCH);
104        let (first_normal_epoch, first_normal_slot) = if warmup {
105            let next_power_of_two = slots_per_epoch.next_power_of_two();
106            let log2_slots_per_epoch = next_power_of_two
107                .trailing_zeros()
108                .saturating_sub(MINIMUM_SLOTS_PER_EPOCH.trailing_zeros());
109
110            (
111                u64::from(log2_slots_per_epoch),
112                next_power_of_two.saturating_sub(MINIMUM_SLOTS_PER_EPOCH),
113            )
114        } else {
115            (0, 0)
116        };
117        EpochSchedule {
118            slots_per_epoch,
119            leader_schedule_slot_offset,
120            warmup,
121            first_normal_epoch,
122            first_normal_slot,
123        }
124    }
125
126    /// get the length of the given epoch (in slots)
127    pub fn get_slots_in_epoch(&self, epoch: u64) -> u64 {
128        if epoch < self.first_normal_epoch {
129            2u64.saturating_pow(
130                (epoch as u32).saturating_add(MINIMUM_SLOTS_PER_EPOCH.trailing_zeros()),
131            )
132        } else {
133            self.slots_per_epoch
134        }
135    }
136
137    /// get the epoch for which the given slot should save off
138    ///  information about stakers
139    pub fn get_leader_schedule_epoch(&self, slot: u64) -> u64 {
140        if slot < self.first_normal_slot {
141            // until we get to normal slots, behave as if leader_schedule_slot_offset == slots_per_epoch
142            self.get_epoch_and_slot_index(slot).0.saturating_add(1)
143        } else {
144            let new_slots_since_first_normal_slot = slot.saturating_sub(self.first_normal_slot);
145            let new_first_normal_leader_schedule_slot =
146                new_slots_since_first_normal_slot.saturating_add(self.leader_schedule_slot_offset);
147            let new_epochs_since_first_normal_leader_schedule =
148                new_first_normal_leader_schedule_slot
149                    .checked_div(self.slots_per_epoch)
150                    .unwrap_or(0);
151            self.first_normal_epoch
152                .saturating_add(new_epochs_since_first_normal_leader_schedule)
153        }
154    }
155
156    /// get epoch for the given slot
157    pub fn get_epoch(&self, slot: u64) -> u64 {
158        self.get_epoch_and_slot_index(slot).0
159    }
160
161    /// get epoch and offset into the epoch for the given slot
162    pub fn get_epoch_and_slot_index(&self, slot: u64) -> (u64, u64) {
163        if slot < self.first_normal_slot {
164            let epoch = slot
165                .saturating_add(MINIMUM_SLOTS_PER_EPOCH)
166                .saturating_add(1)
167                .next_power_of_two()
168                .trailing_zeros()
169                .saturating_sub(MINIMUM_SLOTS_PER_EPOCH.trailing_zeros())
170                .saturating_sub(1);
171
172            let epoch_len =
173                2u64.saturating_pow(epoch.saturating_add(MINIMUM_SLOTS_PER_EPOCH.trailing_zeros()));
174
175            (
176                u64::from(epoch),
177                slot.saturating_sub(epoch_len.saturating_sub(MINIMUM_SLOTS_PER_EPOCH)),
178            )
179        } else {
180            let normal_slot_index = slot.saturating_sub(self.first_normal_slot);
181            let normal_epoch_index = normal_slot_index
182                .checked_div(self.slots_per_epoch)
183                .unwrap_or(0);
184            let epoch = self.first_normal_epoch.saturating_add(normal_epoch_index);
185            let slot_index = normal_slot_index
186                .checked_rem(self.slots_per_epoch)
187                .unwrap_or(0);
188            (epoch, slot_index)
189        }
190    }
191
192    pub fn get_first_slot_in_epoch(&self, epoch: u64) -> u64 {
193        if epoch <= self.first_normal_epoch {
194            2u64.saturating_pow(epoch as u32)
195                .saturating_sub(1)
196                .saturating_mul(MINIMUM_SLOTS_PER_EPOCH)
197        } else {
198            epoch
199                .saturating_sub(self.first_normal_epoch)
200                .saturating_mul(self.slots_per_epoch)
201                .saturating_add(self.first_normal_slot)
202        }
203    }
204
205    pub fn get_last_slot_in_epoch(&self, epoch: u64) -> u64 {
206        self.get_first_slot_in_epoch(epoch)
207            .saturating_add(self.get_slots_in_epoch(epoch))
208            .saturating_sub(1)
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn test_epoch_schedule() {
218        // one week of slots at 8 ticks/slot, 10 ticks/sec is
219        // (1 * 7 * 24 * 4500u64).next_power_of_two();
220
221        // test values between MINIMUM_SLOT_LEN and MINIMUM_SLOT_LEN * 16, should cover a good mix
222        for slots_per_epoch in MINIMUM_SLOTS_PER_EPOCH..=MINIMUM_SLOTS_PER_EPOCH * 16 {
223            let epoch_schedule = EpochSchedule::custom(slots_per_epoch, slots_per_epoch / 2, true);
224
225            assert_eq!(epoch_schedule.get_first_slot_in_epoch(0), 0);
226            assert_eq!(
227                epoch_schedule.get_last_slot_in_epoch(0),
228                MINIMUM_SLOTS_PER_EPOCH - 1
229            );
230
231            let mut last_leader_schedule = 0;
232            let mut last_epoch = 0;
233            let mut last_slots_in_epoch = MINIMUM_SLOTS_PER_EPOCH;
234            for slot in 0..(2 * slots_per_epoch) {
235                // verify that leader_schedule_epoch is continuous over the warmup
236                // and into the first normal epoch
237
238                let leader_schedule = epoch_schedule.get_leader_schedule_epoch(slot);
239                if leader_schedule != last_leader_schedule {
240                    assert_eq!(leader_schedule, last_leader_schedule + 1);
241                    last_leader_schedule = leader_schedule;
242                }
243
244                let (epoch, offset) = epoch_schedule.get_epoch_and_slot_index(slot);
245
246                //  verify that epoch increases continuously
247                if epoch != last_epoch {
248                    assert_eq!(epoch, last_epoch + 1);
249                    last_epoch = epoch;
250                    assert_eq!(epoch_schedule.get_first_slot_in_epoch(epoch), slot);
251                    assert_eq!(epoch_schedule.get_last_slot_in_epoch(epoch - 1), slot - 1);
252
253                    // verify that slots in an epoch double continuously
254                    //   until they reach slots_per_epoch
255
256                    let slots_in_epoch = epoch_schedule.get_slots_in_epoch(epoch);
257                    if slots_in_epoch != last_slots_in_epoch && slots_in_epoch != slots_per_epoch {
258                        assert_eq!(slots_in_epoch, last_slots_in_epoch * 2);
259                    }
260                    last_slots_in_epoch = slots_in_epoch;
261                }
262                // verify that the slot offset is less than slots_in_epoch
263                assert!(offset < last_slots_in_epoch);
264            }
265
266            // assert that these changed  ;)
267            assert!(last_leader_schedule != 0); // t
268            assert!(last_epoch != 0);
269            // assert that we got to "normal" mode
270            assert!(last_slots_in_epoch == slots_per_epoch);
271        }
272    }
273
274    #[test]
275    fn test_clone() {
276        let epoch_schedule = EpochSchedule {
277            slots_per_epoch: 1,
278            leader_schedule_slot_offset: 2,
279            warmup: true,
280            first_normal_epoch: 4,
281            first_normal_slot: 5,
282        };
283        #[allow(clippy::clone_on_copy)]
284        let cloned_epoch_schedule = epoch_schedule.clone();
285        assert_eq!(cloned_epoch_schedule, epoch_schedule);
286    }
287}