1use crate::{BlockProducer, ClaimedSlot};
5use ab_client_api::{ChainInfo, ChainSyncStatus};
6use ab_client_consensus_common::ConsensusConstants;
7use ab_client_consensus_common::consensus_parameters::shard_membership_entropy_source;
8use ab_client_proof_of_time::PotNextSlotInput;
9use ab_client_proof_of_time::source::{PotSlotInfo, PotSlotInfoStream};
10use ab_client_proof_of_time::verifier::PotVerifier;
11use ab_core_primitives::block::BlockNumber;
12use ab_core_primitives::block::header::{
13 BeaconChainHeader, BlockHeaderConsensusInfo, OwnedBlockHeaderSeal,
14};
15use ab_core_primitives::block::owned::OwnedBeaconChainBlock;
16use ab_core_primitives::hashes::Blake3Hash;
17use ab_core_primitives::pot::{PotCheckpoints, PotOutput, PotParametersChange, SlotNumber};
18use ab_core_primitives::shard::NumShards;
19use ab_core_primitives::solutions::{ShardMembershipEntropy, Solution, SolutionRange};
20use ab_proof_of_space::Table;
21use futures::StreamExt;
22use futures::channel::{mpsc, oneshot};
23use send_future::SendFuture;
24use std::collections::BTreeMap;
25use std::marker::PhantomData;
26use std::time::Duration;
27use tokio::sync::broadcast;
28use tracing::{debug, error, info, trace, warn};
29
30const PENDING_SOLUTIONS_CHANNEL_CAPACITY: usize = 10;
32const BLOCK_SEALING_TIMEOUT: Duration = Duration::from_millis(500);
33
34#[derive(Debug, Copy, Clone)]
36pub struct NewSlotInfo {
37 pub slot: SlotNumber,
39 pub proof_of_time: PotOutput,
41 pub solution_range: SolutionRange,
43 pub shard_membership_entropy: ShardMembershipEntropy,
45 pub num_shards: NumShards,
47}
48
49#[derive(Debug, Copy, Clone, Eq, PartialEq)]
52struct SolutionParameters {
53 solution_range: SolutionRange,
54 shard_membership_entropy: ShardMembershipEntropy,
55 num_shards: NumShards,
56}
57
58#[derive(Debug, Clone)]
60pub struct NewSlotNotification {
61 pub new_slot_info: NewSlotInfo,
63 pub solution_sender: mpsc::Sender<Solution>,
65}
66#[derive(Debug)]
69pub struct BlockSealNotification {
70 pub pre_seal_hash: Blake3Hash,
72 pub public_key_hash: Blake3Hash,
74 pub seal_sender: oneshot::Sender<OwnedBlockHeaderSeal>,
76}
77
78#[derive(Debug)]
80pub struct SlotWorkerOptions<BP, BCI, CSS> {
81 pub block_producer: BP,
83 pub beacon_chain_info: BCI,
85 pub chain_sync_status: CSS,
87 pub force_authoring: bool,
89 pub new_slot_notification_sender: mpsc::Sender<NewSlotNotification>,
91 pub block_sealing_notification_sender: mpsc::Sender<BlockSealNotification>,
93 pub consensus_constants: ConsensusConstants,
95 pub pot_verifier: PotVerifier,
97}
98
99#[derive(Debug)]
101pub struct SlotWorker<PosTable, BP, BCI, CSS> {
102 block_producer: BP,
103 beacon_chain_info: BCI,
104 chain_sync_status: CSS,
105 force_authoring: bool,
106 new_slot_notification_sender: mpsc::Sender<NewSlotNotification>,
107 block_sealing_notification_sender: mpsc::Sender<BlockSealNotification>,
108 pending_solutions: BTreeMap<SlotNumber, (SolutionParameters, mpsc::Receiver<Solution>)>,
111 pot_checkpoints: BTreeMap<SlotNumber, PotCheckpoints>,
113 consensus_constants: ConsensusConstants,
114 pot_verifier: PotVerifier,
115 _pos_table: PhantomData<PosTable>,
116}
117
118impl<PosTable, BP, BCI, CSS> SlotWorker<PosTable, BP, BCI, CSS>
119where
120 PosTable: Table,
121 BP: BlockProducer,
122 BCI: ChainInfo<OwnedBeaconChainBlock>,
123 CSS: ChainSyncStatus,
124{
125 pub fn new(
127 SlotWorkerOptions {
128 block_producer,
129 beacon_chain_info,
130 chain_sync_status,
131 force_authoring,
132 new_slot_notification_sender,
133 block_sealing_notification_sender,
134 consensus_constants,
135 pot_verifier,
136 }: SlotWorkerOptions<BP, BCI, CSS>,
137 ) -> Self {
138 Self {
139 block_producer,
140 beacon_chain_info,
141 chain_sync_status,
142 force_authoring,
143 new_slot_notification_sender,
144 block_sealing_notification_sender,
145 pending_solutions: BTreeMap::new(),
146 pot_checkpoints: BTreeMap::new(),
147 consensus_constants,
148 pot_verifier,
149 _pos_table: PhantomData,
150 }
151 }
152
153 pub async fn run(mut self, mut slot_info_stream: PotSlotInfoStream) {
155 let mut last_processed_slot = SlotNumber::ZERO;
156
157 loop {
158 let PotSlotInfo { slot, checkpoints } = match slot_info_stream.recv().await {
159 Ok(slot_info) => slot_info,
160 Err(error) => match error {
161 broadcast::error::RecvError::Closed => {
162 info!("No Slot info senders available. Exiting slot worker.");
163 return;
164 }
165 broadcast::error::RecvError::Lagged(skipped_notifications) => {
166 debug!(
167 "Slot worker is lagging. Skipped {} slot notification(s)",
168 skipped_notifications
169 );
170 continue;
171 }
172 },
173 };
174
175 if last_processed_slot >= slot {
176 continue;
178 }
179 last_processed_slot = slot;
180
181 let best_beacon_chain_header = self.beacon_chain_info.best_header();
182 let best_beacon_chain_header = best_beacon_chain_header.header();
183
184 let oldest_claimable_slot =
186 slot.saturating_sub(self.consensus_constants.block_authoring_delay);
187
188 {
190 self.pot_checkpoints.retain(|&stored_slot, _checkpoints| {
193 (oldest_claimable_slot..slot).contains(&stored_slot)
194 });
195
196 self.pot_checkpoints.insert(slot, checkpoints);
197 }
198 self.pending_solutions
200 .retain(|&stored_slot, _pending_solutions| stored_slot >= oldest_claimable_slot);
201
202 if self.chain_sync_status.is_syncing() {
203 debug!(%slot, "Skipping farming due to syncing");
204 continue;
205 }
206
207 let shard_membership_entropy = match shard_membership_entropy_source(
214 best_beacon_chain_header.prefix.number + BlockNumber::ONE,
215 &best_beacon_chain_header.root(),
216 self.consensus_constants.shard_rotation_interval,
217 self.consensus_constants.shard_rotation_delay,
218 &self.beacon_chain_info,
219 ) {
220 Ok(shard_membership_entropy) => shard_membership_entropy,
221 Err(error) => {
222 error!(%error, "Failed to find shard membership entropy");
223 break;
224 }
225 };
226 let solution_parameters = {
227 let consensus_parameters = best_beacon_chain_header.consensus_parameters();
228
229 SolutionParameters {
230 solution_range: consensus_parameters
231 .next_solution_range
232 .unwrap_or(consensus_parameters.fixed_parameters.solution_range),
233 shard_membership_entropy,
234 num_shards: consensus_parameters.fixed_parameters.num_shards,
235 }
236 };
237
238 {
240 let new_slot_info = NewSlotInfo {
241 slot,
242 proof_of_time: checkpoints.output(),
243 solution_range: solution_parameters.solution_range,
244 shard_membership_entropy: solution_parameters.shard_membership_entropy,
245 num_shards: solution_parameters.num_shards,
246 };
247 let (solution_sender, solution_receiver) =
248 mpsc::channel(PENDING_SOLUTIONS_CHANNEL_CAPACITY);
249
250 if let Err(error) =
251 self.new_slot_notification_sender
252 .try_send(NewSlotNotification {
253 new_slot_info,
254 solution_sender,
255 })
256 {
257 warn!(%error, "Failed to send a new slot notification");
258 }
259
260 self.pending_solutions
261 .insert(slot, (solution_parameters, solution_receiver));
262 }
263
264 let Some(slot_to_claim) =
266 slot.checked_sub(self.consensus_constants.block_authoring_delay)
267 else {
268 trace!("Skipping a very early slot during chain start");
269 continue;
270 };
271
272 if !self.force_authoring && self.chain_sync_status.is_offline() {
273 debug!("Skipping slot, waiting for the network");
274
275 continue;
276 }
277
278 let Some(claimed_slot) = self
279 .claim_slot(best_beacon_chain_header, solution_parameters, slot_to_claim)
280 .await
281 else {
282 continue;
283 };
284
285 debug!(
286 slot = %claimed_slot.consensus_info.slot,
287 "Starting block authorship"
288 );
289
290 let seal_block = {
291 let block_sealing_notification_sender = &mut self.block_sealing_notification_sender;
292 let public_key_hash = claimed_slot.consensus_info.solution.public_key_hash;
293
294 move |pre_seal_hash| async move {
295 let (seal_sender, seal_receiver) = oneshot::channel::<OwnedBlockHeaderSeal>();
296
297 if let Err(error) =
298 block_sealing_notification_sender.try_send(BlockSealNotification {
299 pre_seal_hash,
300 public_key_hash,
301 seal_sender,
302 })
303 {
304 warn!(%error, "Failed to send block sealing notification");
305 }
306
307 match tokio::time::timeout(BLOCK_SEALING_TIMEOUT, seal_receiver).await {
308 Ok(Ok(seal)) => Some(seal),
309 _ => None,
310 }
311 }
312 };
313
314 self.block_producer
317 .produce_block(claimed_slot, best_beacon_chain_header, seal_block)
318 .send()
319 .await;
320 }
321 }
322
323 async fn claim_slot(
326 &mut self,
327 parent_beacon_chain_header: &BeaconChainHeader<'_>,
328 child_solution_parameters: SolutionParameters,
329 slot: SlotNumber,
330 ) -> Option<ClaimedSlot> {
331 let parent_number = parent_beacon_chain_header.prefix.number;
332 let parent_slot = parent_beacon_chain_header.consensus_info.slot;
333
334 if slot <= parent_slot {
335 debug!(
336 "Skipping claiming slot {slot}, it must be higher than parent slot {parent_slot}",
337 );
338
339 return None;
340 }
341
342 debug!(%slot, "Attempting to claim a slot");
343
344 let (solution_parameters, mut solution_receiver) = self.pending_solutions.remove(&slot)?;
345
346 if solution_parameters != child_solution_parameters {
347 debug!(
348 %slot,
349 ?solution_parameters,
350 ?child_solution_parameters,
351 "Skipping claiming slot, solutions were requested with parameters that are not \
352 valid for the current parent block"
353 );
354
355 return None;
356 }
357
358 let parent_consensus_parameters = parent_beacon_chain_header.consensus_parameters();
359
360 let parent_pot_parameters_change = parent_consensus_parameters
361 .pot_parameters_change
362 .copied()
363 .map(PotParametersChange::from);
364 let parent_future_slot = if parent_number == BlockNumber::ZERO {
365 parent_slot
366 } else {
367 parent_slot + self.consensus_constants.block_authoring_delay
368 };
369
370 let (proof_of_time, future_proof_of_time, checkpoints) = {
371 let proof_of_time = self.pot_checkpoints.get(&slot)?.output();
372
373 let future_slot = slot + self.consensus_constants.block_authoring_delay;
375
376 let pot_input = if parent_number == BlockNumber::ZERO {
377 PotNextSlotInput {
378 slot: parent_slot + SlotNumber::ONE,
379 slot_iterations: parent_consensus_parameters.fixed_parameters.slot_iterations,
380 seed: self.pot_verifier.genesis_seed(),
381 }
382 } else {
383 PotNextSlotInput::derive(
384 parent_consensus_parameters.fixed_parameters.slot_iterations,
385 parent_slot,
386 parent_beacon_chain_header.consensus_info.proof_of_time,
387 &parent_pot_parameters_change,
388 )
389 };
390
391 if !self.pot_verifier.is_output_valid(
393 pot_input,
394 slot - parent_slot,
395 proof_of_time,
396 parent_pot_parameters_change,
397 ) {
398 warn!(
399 %slot,
400 ?pot_input,
401 consensus_info = ?parent_beacon_chain_header.consensus_info,
402 "Proof of time is invalid, skipping block authoring at the slot"
403 );
404 return None;
405 }
406
407 let mut checkpoints_pot_input = if parent_number == BlockNumber::ZERO {
408 PotNextSlotInput {
409 slot: parent_slot + SlotNumber::ONE,
410 slot_iterations: parent_consensus_parameters.fixed_parameters.slot_iterations,
411 seed: self.pot_verifier.genesis_seed(),
412 }
413 } else {
414 PotNextSlotInput::derive(
415 parent_consensus_parameters.fixed_parameters.slot_iterations,
416 parent_future_slot,
417 parent_beacon_chain_header
418 .consensus_info
419 .future_proof_of_time,
420 &parent_pot_parameters_change,
421 )
422 };
423
424 let mut checkpoints =
425 Vec::with_capacity(u64::from(future_slot - parent_future_slot) as usize);
426
427 for slot in parent_future_slot + SlotNumber::ONE..=future_slot {
428 let maybe_slot_checkpoints = self.pot_verifier.get_checkpoints(
429 checkpoints_pot_input.slot_iterations,
430 checkpoints_pot_input.seed,
431 );
432 let Some(slot_checkpoints) = maybe_slot_checkpoints else {
433 warn!("Proving failed during block authoring");
434 return None;
435 };
436
437 checkpoints.push(slot_checkpoints);
438
439 checkpoints_pot_input = PotNextSlotInput::derive(
440 checkpoints_pot_input.slot_iterations,
441 slot,
442 slot_checkpoints.output(),
443 &parent_pot_parameters_change,
444 );
445 }
446
447 let future_proof_of_time = checkpoints
448 .last()
449 .expect("Never empty, there is at least one slot between blocks; qed")
450 .output();
451
452 (proof_of_time, future_proof_of_time, checkpoints)
453 };
454
455 solution_receiver.close();
457
458 let mut maybe_consensus_info = None;
459
460 while let Some(solution) = solution_receiver.next().await {
461 if maybe_consensus_info.is_none() {
462 debug!(%slot, "🚜 Claimed slot");
463 maybe_consensus_info.replace(BlockHeaderConsensusInfo {
464 slot,
465 proof_of_time,
466 future_proof_of_time,
467 solution,
468 });
469 } else {
470 debug!(
471 %slot,
472 "Skipping a solution that has quality sufficient for block because \
473 slot has already been claimed",
474 );
475 }
476 }
477
478 maybe_consensus_info.map(|consensus_info| ClaimedSlot {
479 consensus_info,
480 checkpoints,
481 })
482 }
483}