Skip to main content

ab_client_proof_of_time/
source.rs

1pub mod block_import;
2pub mod gossip;
3pub mod state;
4#[cfg(test)]
5mod tests;
6pub mod timekeeper;
7
8use crate::PotNextSlotInput;
9use crate::source::block_import::BestBlockPotInfo;
10use crate::source::gossip::{GossipProof, ToGossipMessage};
11use crate::source::state::{PotState, PotStateSetOutcome};
12use crate::source::timekeeper::TimekeeperProof;
13use crate::verifier::PotVerifier;
14use ab_client_api::ChainSyncStatus;
15use ab_core_primitives::block::BlockNumber;
16use ab_core_primitives::block::header::BeaconChainHeader;
17use ab_core_primitives::pot::{PotCheckpoints, PotParametersChange, SlotNumber};
18use derive_more::{Deref, DerefMut};
19use futures::channel::mpsc;
20use futures::{FutureExt, StreamExt, select};
21use std::future;
22use tokio::sync::broadcast;
23use tracing::{debug, trace, warn};
24use triomphe::Arc;
25
26const SLOTS_CHANNEL_CAPACITY: usize = 10;
27
28/// Initialize [`PotState`] using the best available beacon chain header
29pub fn init_pot_state(
30    best_beacon_chain_header: &BeaconChainHeader<'_>,
31    pot_verifier: PotVerifier,
32    block_authoring_delay: SlotNumber,
33) -> PotState {
34    let block_number = best_beacon_chain_header.prefix.number;
35    let consensus_info = best_beacon_chain_header.consensus_info;
36    let consensus_parameters = best_beacon_chain_header.consensus_parameters();
37
38    let parent_slot = if block_number == BlockNumber::ZERO {
39        SlotNumber::ZERO
40    } else {
41        // The best one seen
42        consensus_info.slot + block_authoring_delay
43    };
44
45    let maybe_next_parameters_change = consensus_parameters
46        .pot_parameters_change
47        .copied()
48        .map(PotParametersChange::from);
49
50    let pot_input = if block_number == BlockNumber::ZERO {
51        PotNextSlotInput {
52            slot: parent_slot + SlotNumber::ONE,
53            slot_iterations: consensus_parameters.fixed_parameters.slot_iterations,
54            seed: pot_verifier.genesis_seed(),
55        }
56    } else {
57        PotNextSlotInput::derive(
58            consensus_parameters.fixed_parameters.slot_iterations,
59            parent_slot,
60            consensus_info.future_proof_of_time,
61            &maybe_next_parameters_change,
62        )
63    };
64
65    PotState::new(pot_input, maybe_next_parameters_change, pot_verifier)
66}
67
68/// Proof of time slot information
69#[derive(Debug, Copy, Clone)]
70pub struct PotSlotInfo {
71    /// Slot number
72    pub slot: SlotNumber,
73    /// Proof of time checkpoints
74    pub checkpoints: PotCheckpoints,
75}
76
77/// Stream with proof of time slots
78#[derive(Debug, Deref, DerefMut)]
79pub struct PotSlotInfoStream(broadcast::Receiver<PotSlotInfo>);
80
81impl Clone for PotSlotInfoStream {
82    #[inline]
83    fn clone(&self) -> Self {
84        Self(self.0.resubscribe())
85    }
86}
87
88impl PotSlotInfoStream {
89    fn new(receiver: broadcast::Receiver<PotSlotInfo>) -> Self {
90        Self(receiver)
91    }
92}
93
94/// Worker producing proofs of time.
95///
96/// Depending on configuration may produce proofs of time locally, send/receive via gossip and keep
97/// up to day with blockchain reorgs.
98#[derive(Debug)]
99#[must_use = "Proof of time source doesn't do anything unless run() method is called"]
100pub struct PotSourceWorker<CSS> {
101    chain_sync_status: CSS,
102    timekeeper_proof_receiver: Option<mpsc::Receiver<TimekeeperProof>>,
103    to_gossip_sender: mpsc::Sender<ToGossipMessage>,
104    from_gossip_receiver: mpsc::Receiver<GossipProof>,
105    best_block_pot_info_receiver: mpsc::Receiver<BestBlockPotInfo>,
106    last_slot_sent: SlotNumber,
107    slot_sender: broadcast::Sender<PotSlotInfo>,
108    pot_state: Arc<PotState>,
109}
110
111impl<CSS> PotSourceWorker<CSS>
112where
113    CSS: ChainSyncStatus,
114{
115    pub fn new(
116        timekeeper_proof_receiver: Option<mpsc::Receiver<TimekeeperProof>>,
117        to_gossip_sender: mpsc::Sender<ToGossipMessage>,
118        from_gossip_receiver: mpsc::Receiver<GossipProof>,
119        best_block_pot_info_receiver: mpsc::Receiver<BestBlockPotInfo>,
120        chain_sync_status: CSS,
121        pot_state: Arc<PotState>,
122    ) -> (Self, PotSlotInfoStream) {
123        let (slot_sender, slot_receiver) = broadcast::channel(SLOTS_CHANNEL_CAPACITY);
124
125        let source_worker = Self {
126            chain_sync_status,
127            timekeeper_proof_receiver,
128            to_gossip_sender,
129            from_gossip_receiver,
130            best_block_pot_info_receiver,
131            last_slot_sent: SlotNumber::ZERO,
132            slot_sender,
133            pot_state,
134        };
135
136        let pot_slot_info_stream = PotSlotInfoStream::new(slot_receiver);
137
138        (source_worker, pot_slot_info_stream)
139    }
140
141    /// Run proof of time source
142    pub async fn run(mut self) {
143        loop {
144            let timekeeper_proof = async {
145                if let Some(timekeeper_proof_receiver) = &mut self.timekeeper_proof_receiver {
146                    timekeeper_proof_receiver.next().await
147                } else {
148                    future::pending().await
149                }
150            };
151
152            select! {
153                maybe_timekeeper_proof = timekeeper_proof.fuse() => {
154                    if let Some(timekeeper_proof) = maybe_timekeeper_proof {
155                        self.handle_timekeeper_proof(timekeeper_proof);
156                    } else {
157                        debug!("Timekeeper proof stream ended, exiting");
158                        return;
159                    }
160                }
161                maybe_gossip_proof = self.from_gossip_receiver.next() => {
162                    if let Some(gossip_proof) = maybe_gossip_proof {
163                        self.handle_gossip_proof(gossip_proof);
164                    } else {
165                        debug!("Incoming gossip messages stream ended, exiting");
166                        return;
167                    }
168                }
169                maybe_best_block_pot_info = self.best_block_pot_info_receiver.next() => {
170                    if let Some(best_block_pot_info) = maybe_best_block_pot_info {
171                        self.handle_best_block_pot_info(best_block_pot_info);
172                    } else {
173                        debug!("Import notifications stream ended, exiting");
174                        return;
175                    }
176                }
177            }
178        }
179    }
180
181    fn handle_timekeeper_proof(&mut self, proof: TimekeeperProof) {
182        let TimekeeperProof {
183            slot,
184            seed,
185            slot_iterations,
186            checkpoints,
187        } = proof;
188
189        if self.chain_sync_status.is_syncing() {
190            trace!(
191                ?slot,
192                %seed,
193                %slot_iterations,
194                output = %checkpoints.output(),
195                "Ignore timekeeper proof due to major syncing",
196            );
197
198            return;
199        }
200
201        // Timekeeper may have produced the proof before PoT chain was changed by block import
202        if !self.pot_state.is_on_current_chain(
203            PotNextSlotInput {
204                slot,
205                slot_iterations,
206                seed,
207            },
208            checkpoints.output(),
209        ) {
210            debug!(
211                ?slot,
212                %seed,
213                %slot_iterations,
214                output = %checkpoints.output(),
215                "Ignore timekeeper proof that is not on the current proof of time chain",
216            );
217
218            return;
219        }
220
221        debug!(
222            ?slot,
223            %seed,
224            %slot_iterations,
225            output = %checkpoints.output(),
226            "Received timekeeper proof",
227        );
228
229        if self
230            .to_gossip_sender
231            .try_send(ToGossipMessage::Proof(GossipProof {
232                slot,
233                seed,
234                slot_iterations,
235                checkpoints,
236            }))
237            .is_err()
238        {
239            debug!(
240                %slot,
241                "Gossip is not able to keep-up with slot production (timekeeper)",
242            );
243        }
244
245        if slot > self.last_slot_sent {
246            self.last_slot_sent = slot;
247
248            // We don't care if block production is too slow or block production is not enabled on
249            // this node at all
250            let _: Result<_, _> = self.slot_sender.send(PotSlotInfo { slot, checkpoints });
251        }
252    }
253
254    // TODO: Follow both verified and unverified checkpoints to start secondary timekeeper ASAP in
255    //  case verification succeeds
256    fn handle_gossip_proof(&mut self, proof: GossipProof) {
257        let expected_next_slot_input = PotNextSlotInput {
258            slot: proof.slot,
259            slot_iterations: proof.slot_iterations,
260            seed: proof.seed,
261        };
262
263        if let Ok(next_slot_input) = self.pot_state.try_extend(
264            expected_next_slot_input,
265            proof.slot,
266            proof.checkpoints.output(),
267            None,
268        ) {
269            if proof.slot > self.last_slot_sent {
270                self.last_slot_sent = proof.slot;
271
272                // We don't care if block production is too slow or block production is not enabled
273                // on this node at all
274                let _: Result<_, _> = self.slot_sender.send(PotSlotInfo {
275                    slot: proof.slot,
276                    checkpoints: proof.checkpoints,
277                });
278            }
279
280            if self
281                .to_gossip_sender
282                .try_send(ToGossipMessage::NextSlotInput(next_slot_input))
283                .is_err()
284            {
285                debug!(
286                    slot = %proof.slot,
287                    next_slot = %next_slot_input.slot,
288                    "Gossip is not able to keep-up with slot production (gossip)",
289                );
290            }
291        }
292    }
293
294    fn handle_best_block_pot_info(&mut self, best_block_pot_info: BestBlockPotInfo) {
295        // This will do one of 3 things depending on circumstances:
296        // * if block import is ahead of timekeeper and gossip, it will update next slot input
297        // * if block import is on a different PoT chain, it will update next slot input to the
298        //   correct fork (reorg)
299        // * if block import is on the same PoT chain this will essentially do nothing
300        match self.pot_state.set_known_good_output(
301            best_block_pot_info.slot,
302            best_block_pot_info.pot_output,
303            best_block_pot_info.pot_parameters_change,
304        ) {
305            PotStateSetOutcome::NoChange => {
306                trace!(
307                    slot = %best_block_pot_info.slot,
308                    "Block import didn't result in proof of time chain changes",
309                );
310            }
311            PotStateSetOutcome::Extension { from, to } => {
312                warn!(
313                    from_next_slot = %from.slot,
314                    to_next_slot = %to.slot,
315                    "Proof of time chain was extended from block import",
316                );
317
318                if self
319                    .to_gossip_sender
320                    .try_send(ToGossipMessage::NextSlotInput(to))
321                    .is_err()
322                {
323                    debug!(
324                        next_slot = %to.slot,
325                        "Gossip is not able to keep-up with slot production (block import)",
326                    );
327                }
328            }
329            PotStateSetOutcome::Reorg { from, to } => {
330                warn!(
331                    from_next_slot = %from.slot,
332                    to_next_slot = %to.slot,
333                    "Proof of time chain reorg happened",
334                );
335
336                if self
337                    .to_gossip_sender
338                    .try_send(ToGossipMessage::NextSlotInput(to))
339                    .is_err()
340                {
341                    debug!(
342                        next_slot = %to.slot,
343                        "Gossip is not able to keep-up with slot production (block import)",
344                    );
345                }
346            }
347        }
348    }
349}