use core::ops::Range;
use tape_crypto::hash::{Hash, hashv};
use crate::types::{RoundNumber, SlotNumber};
const GRID_DOMAIN: &[u8] = b"WHIRLWIND_GRID";
pub const SLOT_MS: u64 = 400;
pub const SPAN_SLOTS: u64 = 2;
pub const SAMPLE_LOOKBACK_SLOTS: u64 = 64;
pub const PROOF_DEADLINE_SLOTS: u64 = 2;
pub const CONFIRMATION_SLOTS: u64 = 1;
pub const ATTESTATION_WINDOW_SLOTS: u64 = 2;
pub const CERTIFICATE_GOSSIP_SLOTS: u64 = 1;
pub const MAINNET_CADENCE_SLOTS: u64 = 7;
pub const SHORT_EPOCH_SLOTS: u64 = 1_800;
pub const FINALITY_SLOTS: u64 = 32;
pub const SETTLE_DEADLINE_SLOTS: u64 = FINALITY_SLOTS + 8;
pub const MAX_PENDING_ROUNDS: usize = (SETTLE_DEADLINE_SLOTS / round_width_slots() + 3) as usize;
pub const HANDOVER_GRACE_ROUNDS: u64 = 8;
pub const TARGET_ROUNDS_PER_EPOCH: u64 = 4;
pub const fn round_width_slots() -> u64 {
let tail = if PROOF_DEADLINE_SLOTS > ATTESTATION_WINDOW_SLOTS {
PROOF_DEADLINE_SLOTS
} else {
ATTESTATION_WINDOW_SLOTS
};
SPAN_SLOTS + tail + CERTIFICATE_GOSSIP_SLOTS
}
pub fn cadence_for_epoch(epoch_slots: u64) -> u64 {
let fitted = epoch_slots / TARGET_ROUNDS_PER_EPOCH;
let cap = if epoch_slots < SHORT_EPOCH_SLOTS {
round_width_slots()
} else {
MAINNET_CADENCE_SLOTS
};
cap.min(fitted).max(round_width_slots())
}
fn rounds_in(epoch_slots: u64, interval_slots: u64) -> u64 {
let width = round_width_slots();
if epoch_slots < width {
return 0;
}
(epoch_slots - width) / interval_slots + 1
}
pub fn grid_slack(epoch_slots: u64, interval_slots: u64) -> u64 {
let rounds = rounds_in(epoch_slots, interval_slots);
if rounds == 0 {
return 0;
}
let used = (rounds - 1) * interval_slots + round_width_slots();
epoch_slots.saturating_sub(used)
}
pub fn grid_offset(nonce: &Hash, slack: u64) -> u64 {
let mut head = [0u8; 8];
head.copy_from_slice(&hashv(&[GRID_DOMAIN, nonce.as_ref()]).as_ref()[..8]);
u64::from_le_bytes(head) % (slack + 1)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScheduleError {
RoundsOverlap { interval: u64, width: u64 },
EpochTooShort { epoch_slots: u64, width: u64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Schedule {
pub epoch_start_slot: SlotNumber,
pub epoch_slots: u64,
pub interval_slots: u64,
pub grid_offset: u64,
}
impl Schedule {
pub fn for_epoch(epoch_start_slot: SlotNumber, epoch_slots: u64, nonce: &Hash) -> Self {
let interval_slots = cadence_for_epoch(epoch_slots);
Self {
epoch_start_slot,
epoch_slots,
interval_slots,
grid_offset: grid_offset(nonce, grid_slack(epoch_slots, interval_slots)),
}
}
pub fn first_slot(&self) -> SlotNumber {
SlotNumber(self.epoch_start_slot.as_u64() + self.grid_offset)
}
pub fn validate(&self) -> Result<(), ScheduleError> {
let width = round_width_slots();
if self.interval_slots < width {
return Err(ScheduleError::RoundsOverlap {
interval: self.interval_slots,
width,
});
}
if self.epoch_slots < width {
return Err(ScheduleError::EpochTooShort {
epoch_slots: self.epoch_slots,
width,
});
}
Ok(())
}
pub fn rounds(&self) -> u64 {
rounds_in(self.epoch_slots, self.interval_slots)
}
pub fn sample_cutoff(&self, round: RoundNumber) -> SlotNumber {
SlotNumber(self.base_slot(round).as_u64().saturating_sub(SAMPLE_LOOKBACK_SLOTS))
}
pub fn base_slot(&self, round: RoundNumber) -> SlotNumber {
SlotNumber(self.first_slot().as_u64() + round.as_u64() * self.interval_slots)
}
pub fn entropy_window(&self, round: RoundNumber) -> Range<u64> {
let base = self.base_slot(round).as_u64();
base..base + SPAN_SLOTS
}
pub fn deadline_slot(&self, entropy_slot: SlotNumber) -> SlotNumber {
SlotNumber(entropy_slot.as_u64() + PROOF_DEADLINE_SLOTS)
}
pub fn round_at(&self, slot: SlotNumber) -> Option<RoundNumber> {
let offset = slot.as_u64().checked_sub(self.first_slot().as_u64())?;
if offset % self.interval_slots >= SPAN_SLOTS {
return None;
}
Some(RoundNumber(offset / self.interval_slots))
}
}
#[cfg(test)]
mod tests {
use super::*;
const MAINNET: u64 = 604_800;
const DEVNET: u64 = 3_600;
const LOCALNET: u64 = 100;
const SIMNET: u64 = 20;
fn epoch_slots(seconds: u64) -> u64 {
seconds * 1_000 / SLOT_MS
}
fn nonce(byte: u8) -> Hash {
Hash([byte; 32])
}
#[test]
fn round_width() {
assert_eq!(round_width_slots(), 5);
}
#[test]
fn preset_cadence() {
let expected = [
(MAINNET, 7u64, 216_000u64),
(DEVNET, 7, 1_286),
(LOCALNET, 5, 50),
(SIMNET, 5, 10),
];
for (seconds, interval, rounds) in expected {
let slots = epoch_slots(seconds);
let schedule = Schedule::for_epoch(SlotNumber(0), slots, &nonce(0));
assert_eq!(schedule.interval_slots, interval, "{seconds}s interval");
assert_eq!(schedule.rounds(), rounds, "{seconds}s rounds");
assert!(schedule.validate().is_ok(), "{seconds}s invalid");
}
}
#[test]
fn shortest_epoch() {
let schedule = Schedule::for_epoch(SlotNumber(0), epoch_slots(5), &nonce(0));
assert_eq!(schedule.interval_slots, round_width_slots());
assert_eq!(schedule.rounds(), 2);
assert!(schedule.validate().is_ok());
}
#[test]
fn epoch_too_short() {
let schedule = Schedule::for_epoch(SlotNumber(0), 4, &nonce(0));
assert_eq!(schedule.rounds(), 0);
assert_eq!(
schedule.validate(),
Err(ScheduleError::EpochTooShort {
epoch_slots: 4,
width: round_width_slots(),
})
);
}
#[test]
fn no_overlap() {
let schedule = Schedule::for_epoch(SlotNumber(1_000), epoch_slots(SIMNET), &nonce(0));
for round in 0..schedule.rounds() {
let window = schedule.entropy_window(RoundNumber(round));
let next = schedule.base_slot(RoundNumber(round + 1)).as_u64();
assert!(window.start >= schedule.first_slot().as_u64());
assert!(window.end + round_width_slots() - SPAN_SLOTS <= next);
}
}
#[test]
fn last_round_fits() {
for (seconds, byte) in [
(MAINNET, 0u8), (MAINNET, 200), (DEVNET, 3), (LOCALNET, 7),
(SIMNET, 11), (10, 13), (200, 17),
] {
let slots = epoch_slots(seconds);
let schedule = Schedule::for_epoch(SlotNumber(0), slots, &nonce(byte));
let Some(last) = schedule.rounds().checked_sub(1) else {
continue;
};
let end = schedule.base_slot(RoundNumber(last)).as_u64()
- schedule.epoch_start_slot.as_u64()
+ round_width_slots();
assert!(end <= slots, "{seconds}s overruns by {}", end - slots);
}
}
#[test]
fn long_epoch() {
let schedule = Schedule::for_epoch(SlotNumber(0), epoch_slots(SIMNET), &nonce(0));
let nominal = schedule.rounds();
assert_eq!(
schedule.round_at(schedule.base_slot(RoundNumber(nominal))),
Some(RoundNumber(nominal))
);
assert_eq!(
schedule.round_at(schedule.base_slot(RoundNumber(nominal + 10))),
Some(RoundNumber(nominal + 10))
);
}
#[test]
fn nonce_moves_grid() {
let slots = epoch_slots(MAINNET);
let offsets: Vec<u64> = (0..8u8)
.map(|byte| Schedule::for_epoch(SlotNumber(0), slots, &nonce(byte)).grid_offset)
.collect();
assert!(offsets.iter().all(|offset| *offset <= grid_slack(slots, MAINNET_CADENCE_SLOTS)));
assert!(
offsets.iter().collect::<std::collections::HashSet<_>>().len() > 1,
"the grid sat in the same place for every nonce: {offsets:?}"
);
}
#[test]
fn nonce_is_pure() {
let slots = epoch_slots(DEVNET);
let once = Schedule::for_epoch(SlotNumber(77), slots, &nonce(9));
let again = Schedule::for_epoch(SlotNumber(77), slots, &nonce(9));
assert_eq!(once, again);
assert_eq!(once.base_slot(RoundNumber(3)), again.base_slot(RoundNumber(3)));
}
#[test]
fn grid_inside_epoch() {
let slots = epoch_slots(SIMNET);
for byte in 0..32u8 {
let schedule = Schedule::for_epoch(SlotNumber(500), slots, &nonce(byte));
assert!(schedule.first_slot().as_u64() >= 500);
assert_eq!(
schedule.rounds(),
Schedule::for_epoch(SlotNumber(500), slots, &Hash([0; 32])).rounds()
);
}
}
#[test]
fn slot_to_round() {
let start = SlotNumber(9_000);
let schedule = Schedule::for_epoch(start, epoch_slots(DEVNET), &nonce(0));
for round in [0u64, 1, 30, schedule.rounds() + 5] {
let window = schedule.entropy_window(RoundNumber(round));
for slot in window.clone() {
assert_eq!(schedule.round_at(SlotNumber(slot)), Some(RoundNumber(round)));
}
assert_eq!(schedule.round_at(SlotNumber(window.end)), None);
}
assert_eq!(schedule.round_at(SlotNumber(schedule.first_slot().as_u64() - 1)), None);
}
}