Skip to main content

ab_client_proof_of_time/source/
timekeeper.rs

1#[cfg(test)]
2mod tests;
3
4use crate::PotNextSlotInput;
5use crate::source::state::PotState;
6use crate::verifier::PotVerifier;
7use ab_core_primitives::pot::{PotCheckpoints, PotSeed, SlotDuration, SlotNumber};
8use ab_proof_of_time::PotError;
9use futures::SinkExt;
10use futures::channel::mpsc;
11use futures::executor::block_on;
12use std::num::NonZeroU32;
13use std::thread::sleep;
14use std::time::Instant;
15use tracing::{debug, trace};
16use triomphe::Arc;
17
18/// Poof generated by timekeeper
19#[derive(Debug, Copy, Clone)]
20pub struct TimekeeperProof {
21    /// Slot number
22    pub slot: SlotNumber,
23    /// Proof of time seed
24    pub seed: PotSeed,
25    /// Iterations per slot
26    pub slot_iterations: NonZeroU32,
27    /// Proof of time checkpoints
28    pub checkpoints: PotCheckpoints,
29}
30
31/// Timekeeper source
32#[derive(Debug)]
33#[must_use = "Doesn't do anything unless run() method is called"]
34pub struct Timekeeper {
35    state: Arc<PotState>,
36    pot_verifier: PotVerifier,
37    proof_sender: mpsc::Sender<TimekeeperProof>,
38    slot_duration: SlotDuration,
39}
40
41impl Timekeeper {
42    /// Create a new timekeeper source
43    pub fn new(
44        state: Arc<PotState>,
45        pot_verifier: PotVerifier,
46        slot_duration: SlotDuration,
47    ) -> (Self, mpsc::Receiver<TimekeeperProof>) {
48        let (proof_sender, proof_receiver) = mpsc::channel(1);
49
50        (
51            Self {
52                state,
53                pot_verifier,
54                proof_sender,
55                slot_duration,
56            },
57            proof_receiver,
58        )
59    }
60
61    /// Run timekeeper until receiver returned from constructor is dropped.
62    ///
63    /// Must be running on a dedicated high-frequency CPU core.
64    pub fn run(self) -> Result<(), PotError> {
65        let Self {
66            state,
67            pot_verifier,
68            mut proof_sender,
69            slot_duration,
70        } = self;
71
72        Self::try_debug_run(&state, &pot_verifier, &mut proof_sender, slot_duration)?;
73
74        let mut next_slot_input = state.next_slot_input();
75
76        loop {
77            let Some(new_next_slot_input) =
78                Self::prove_slot(&state, &pot_verifier, &mut proof_sender, next_slot_input)?
79            else {
80                return Ok(());
81            };
82            next_slot_input = new_next_slot_input;
83        }
84    }
85
86    /// A special version of [`Self::run()`] designed for debug purposes.
87    ///
88    /// It is used when the specified number of iterations is way too low for slot duration, in
89    /// which case artificial delay is applied to maintain slot duration at approximately specified
90    /// rate. This allows debugging things without burning a full CPU core at all times.
91    #[inline(never)]
92    fn try_debug_run(
93        state: &Arc<PotState>,
94        pot_verifier: &PotVerifier,
95        proof_sender: &mut mpsc::Sender<TimekeeperProof>,
96        slot_duration: SlotDuration,
97    ) -> Result<(), PotError> {
98        let mut next_slot_input = state.next_slot_input();
99
100        let delay = {
101            let start = Instant::now();
102            ab_proof_of_time::prove(next_slot_input.seed, next_slot_input.slot_iterations)?;
103            let duration = start.elapsed();
104
105            if duration.is_zero() || duration > slot_duration.as_duration() / 2 {
106                // Either can't identify or relatively fast
107                return Ok(());
108            }
109
110            slot_duration.as_duration().saturating_sub(duration)
111        };
112
113        loop {
114            let Some(new_next_slot_input) =
115                Self::prove_slot(state, pot_verifier, proof_sender, next_slot_input)?
116            else {
117                return Ok(());
118            };
119            next_slot_input = new_next_slot_input;
120
121            // Artificial delay
122            sleep(delay);
123        }
124    }
125
126    /// Prove the slot with `next_slot_input`, extend PoT chain with the proof and send it if the
127    /// chain was extended.
128    ///
129    /// Returns the input of the next slot to prove or `None` if the proof channel is closed.
130    fn prove_slot(
131        state: &PotState,
132        pot_verifier: &PotVerifier,
133        proof_sender: &mut mpsc::Sender<TimekeeperProof>,
134        next_slot_input: PotNextSlotInput,
135    ) -> Result<Option<PotNextSlotInput>, PotError> {
136        trace!(
137            "Proving for slot {} with {} iterations",
138            next_slot_input.slot, next_slot_input.slot_iterations
139        );
140        let checkpoints =
141            ab_proof_of_time::prove(next_slot_input.seed, next_slot_input.slot_iterations)?;
142
143        let proof = TimekeeperProof {
144            seed: next_slot_input.seed,
145            slot_iterations: next_slot_input.slot_iterations,
146            slot: next_slot_input.slot,
147            checkpoints,
148        };
149
150        pot_verifier.inject_verified_checkpoints(
151            next_slot_input.seed,
152            next_slot_input.slot_iterations,
153            checkpoints,
154        );
155
156        match state.try_extend(
157            next_slot_input,
158            next_slot_input.slot,
159            checkpoints.output(),
160            None,
161        ) {
162            Ok(new_next_slot_input) => {
163                if let Err(error) = proof_sender.try_send(proof)
164                    && let Err(error) = block_on(proof_sender.send(error.into_inner()))
165                {
166                    debug!(%error, "Couldn't send proof, the channel is closed");
167                    return Ok(None);
168                }
169
170                Ok(Some(new_next_slot_input))
171            }
172            Err(existing_next_slot_input) => {
173                // PoT chain was changed while proving, the proof is either known already or not on
174                // the chain that is followed anymore
175                trace!(
176                    slot = %next_slot_input.slot,
177                    "Proof of time chain was changed while proving, not sending the proof",
178                );
179
180                Ok(Some(existing_next_slot_input))
181            }
182        }
183    }
184}