Skip to main content

ab_client_proof_of_time/source/
state.rs

1#[cfg(test)]
2mod tests;
3
4use crate::PotNextSlotInput;
5use crate::verifier::PotVerifier;
6use ab_core_primitives::pot::{PotOutput, PotParametersChange, SlotNumber};
7use parking_lot::Mutex;
8
9#[derive(Debug, Copy, Clone, Eq, PartialEq)]
10struct InnerState {
11    next_slot_input: PotNextSlotInput,
12    parameters_change: Option<PotParametersChange>,
13}
14
15impl InnerState {
16    #[expect(
17        clippy::option_option,
18        reason = "External option indicates whether the change should be done, while internal is \
19        the value itself"
20    )]
21    fn update(
22        mut self,
23        mut slot: SlotNumber,
24        mut output: PotOutput,
25        maybe_updated_parameters_change: Option<Option<PotParametersChange>>,
26        pot_verifier: &PotVerifier,
27    ) -> Self {
28        if let Some(updated_parameters_change) = maybe_updated_parameters_change {
29            self.parameters_change = updated_parameters_change;
30        }
31
32        loop {
33            self.next_slot_input = PotNextSlotInput::derive(
34                self.next_slot_input.slot_iterations,
35                slot,
36                output,
37                &self.parameters_change,
38            );
39
40            // Advance further as far as possible using previously verified proofs/checkpoints
41            if let Some(checkpoints) = pot_verifier.try_get_checkpoints(
42                self.next_slot_input.slot_iterations,
43                self.next_slot_input.seed,
44            ) {
45                slot = self.next_slot_input.slot;
46                output = checkpoints.output();
47            } else {
48                break;
49            }
50        }
51
52        self
53    }
54}
55
56/// Result of [`PotState::set_known_good_output()`] call
57#[derive(Debug)]
58pub enum PotStateSetOutcome {
59    /// Nothing has changed
60    NoChange,
61    /// PoT chain extension
62    Extension {
63        from: PotNextSlotInput,
64        to: PotNextSlotInput,
65    },
66    /// PoT chain reorg
67    Reorg {
68        from: PotNextSlotInput,
69        to: PotNextSlotInput,
70    },
71}
72
73/// Global PoT state.
74///
75/// Maintains the accurate information about PoT state and current tip.
76#[derive(Debug)]
77pub struct PotState {
78    inner_state: Mutex<InnerState>,
79    verifier: PotVerifier,
80}
81
82impl PotState {
83    /// Create a new PoT state
84    pub fn new(
85        next_slot_input: PotNextSlotInput,
86        parameters_change: Option<PotParametersChange>,
87        verifier: PotVerifier,
88    ) -> Self {
89        let inner = InnerState {
90            next_slot_input,
91            parameters_change,
92        };
93
94        Self {
95            inner_state: Mutex::new(inner),
96            verifier,
97        }
98    }
99
100    /// PoT input for the next slot
101    pub fn next_slot_input(&self) -> PotNextSlotInput {
102        self.inner_state.lock().next_slot_input
103    }
104
105    /// Extend PoT chain if it matches provided expected next slot input.
106    ///
107    /// Returns `Ok(new_next_slot_input)` if PoT chain was extended successfully and
108    /// `Err(existing_next_slot_input)` in case the state was changed in the meantime.
109    pub fn try_extend(
110        &self,
111        expected_existing_next_slot_input: PotNextSlotInput,
112        best_slot: SlotNumber,
113        best_output: PotOutput,
114        maybe_updated_parameters_change: Option<Option<PotParametersChange>>,
115    ) -> Result<PotNextSlotInput, PotNextSlotInput> {
116        let mut existing_inner_state = self.inner_state.lock();
117        if expected_existing_next_slot_input != existing_inner_state.next_slot_input {
118            return Err(existing_inner_state.next_slot_input);
119        }
120
121        *existing_inner_state = existing_inner_state.update(
122            best_slot,
123            best_output,
124            maybe_updated_parameters_change,
125            &self.verifier,
126        );
127
128        Ok(existing_inner_state.next_slot_input)
129    }
130
131    /// Check whether a proof with `proof_output` for `proof_slot_input` belongs to the PoT chain
132    /// that is currently followed, either as one of the recent slots or as the next slot.
133    ///
134    /// Recent slots are connected to the tip using previously verified proofs, so `false` is also
135    /// returned for proofs that can't be connected this way.
136    pub fn is_on_current_chain(
137        &self,
138        proof_slot_input: PotNextSlotInput,
139        proof_output: PotOutput,
140    ) -> bool {
141        let inner_state = *self.inner_state.lock();
142        let next_slot_input = inner_state.next_slot_input;
143
144        if proof_slot_input.slot >= next_slot_input.slot {
145            return proof_slot_input == next_slot_input;
146        }
147
148        let mut slot_input = PotNextSlotInput::derive(
149            proof_slot_input.slot_iterations,
150            proof_slot_input.slot,
151            proof_output,
152            &inner_state.parameters_change,
153        );
154
155        while slot_input.slot < next_slot_input.slot {
156            let Some(checkpoints) = self
157                .verifier
158                .try_get_checkpoints(slot_input.slot_iterations, slot_input.seed)
159            else {
160                return false;
161            };
162
163            slot_input = PotNextSlotInput::derive(
164                slot_input.slot_iterations,
165                slot_input.slot,
166                checkpoints.output(),
167                &inner_state.parameters_change,
168            );
169        }
170
171        slot_input == next_slot_input
172    }
173
174    /// Set known good output for time slot, overriding PoT chain if it doesn't match the provided
175    /// output.
176    ///
177    /// This is typically called with information obtained from received block. It typically lags
178    /// behind PoT tip and is used as a correction mechanism in case PoT reorg is needed.
179    pub fn set_known_good_output(
180        &self,
181        slot: SlotNumber,
182        output: PotOutput,
183        updated_parameters_change: Option<PotParametersChange>,
184    ) -> PotStateSetOutcome {
185        let previous_best_state;
186        let new_best_state;
187        {
188            let mut inner_state = self.inner_state.lock();
189            previous_best_state = *inner_state;
190            new_best_state = previous_best_state.update(
191                slot,
192                output,
193                Some(updated_parameters_change),
194                &self.verifier,
195            );
196            *inner_state = new_best_state;
197        }
198
199        if previous_best_state.next_slot_input == new_best_state.next_slot_input {
200            return PotStateSetOutcome::NoChange;
201        }
202
203        if previous_best_state.next_slot_input.slot < new_best_state.next_slot_input.slot {
204            let mut slot_iterations = previous_best_state.next_slot_input.slot_iterations;
205            let mut seed = previous_best_state.next_slot_input.seed;
206
207            for slot in
208                previous_best_state.next_slot_input.slot..new_best_state.next_slot_input.slot
209            {
210                let Some(checkpoints) = self.verifier.try_get_checkpoints(slot_iterations, seed)
211                else {
212                    break;
213                };
214
215                let pot_input = PotNextSlotInput::derive(
216                    slot_iterations,
217                    slot,
218                    checkpoints.output(),
219                    &updated_parameters_change,
220                );
221
222                // TODO: Consider carrying of the whole `PotNextSlotInput` rather than individual
223                //  variables
224                let next_slot = slot + SlotNumber::ONE;
225                slot_iterations = pot_input.slot_iterations;
226                seed = pot_input.seed;
227
228                if next_slot == new_best_state.next_slot_input.slot
229                    && slot_iterations == new_best_state.next_slot_input.slot_iterations
230                    && seed == new_best_state.next_slot_input.seed
231                {
232                    return PotStateSetOutcome::Extension {
233                        from: previous_best_state.next_slot_input,
234                        to: new_best_state.next_slot_input,
235                    };
236                }
237            }
238        }
239
240        PotStateSetOutcome::Reorg {
241            from: previous_best_state.next_slot_input,
242            to: new_best_state.next_slot_input,
243        }
244    }
245}