ab_client_block_verification/
beacon_chain.rs

1use crate::{BlockVerification, BlockVerificationError, GenericBody, GenericHeader};
2use ab_client_api::{BlockOrigin, ChainInfo, ChainSyncStatus};
3use ab_client_archiving::segment_headers_store::SegmentHeadersStore;
4use ab_client_consensus_common::ConsensusConstants;
5use ab_client_consensus_common::consensus_parameters::{
6    DeriveConsensusParametersError, derive_consensus_parameters,
7};
8use ab_client_proof_of_time::PotNextSlotInput;
9use ab_client_proof_of_time::verifier::PotVerifier;
10use ab_core_primitives::block::body::{BeaconChainBody, IntermediateShardBlocksInfo};
11use ab_core_primitives::block::header::{
12    BeaconChainHeader, BlockHeaderConsensusParameters, BlockHeaderPrefix,
13    OwnedBlockHeaderConsensusParameters,
14};
15use ab_core_primitives::block::owned::OwnedBeaconChainBlock;
16use ab_core_primitives::block::{BlockNumber, BlockRoot, BlockTimestamp};
17use ab_core_primitives::hashes::Blake3Hash;
18use ab_core_primitives::pot::{PotCheckpoints, PotOutput, PotParametersChange, SlotNumber};
19use ab_core_primitives::segments::SegmentRoot;
20use ab_core_primitives::solutions::{SolutionVerifyError, SolutionVerifyParams};
21use ab_proof_of_space::Table;
22use rand::prelude::*;
23use rayon::prelude::*;
24use std::iter;
25use std::marker::PhantomData;
26use std::time::SystemTime;
27use tracing::{debug, trace};
28
29/// Errors for [`BeaconChainBlockVerification`]
30#[derive(Debug, thiserror::Error)]
31pub enum BeaconChainBlockVerificationError {
32    /// Consensus parameters derivation error
33    #[error("Consensus parameters derivation error: {error}")]
34    ConsensusParametersDerivation {
35        /// Consensus parameters derivation error
36        #[from]
37        error: DeriveConsensusParametersError,
38    },
39    /// Invalid consensus parameters
40    #[error("Invalid consensus parameters")]
41    InvalidConsensusParameters,
42    /// Invalid PoT checkpoints
43    #[error("Invalid PoT checkpoints")]
44    InvalidPotCheckpoints,
45    /// Invalid proof of time
46    #[error("Invalid proof of time")]
47    InvalidProofOfTime,
48    /// Solution error
49    #[error("Solution error: {error}")]
50    SolutionError {
51        /// Solution error
52        #[from]
53        error: SolutionVerifyError,
54    },
55}
56
57impl From<BeaconChainBlockVerificationError> for BlockVerificationError {
58    #[inline(always)]
59    fn from(error: BeaconChainBlockVerificationError) -> Self {
60        Self::Custom {
61            error: error.into(),
62        }
63    }
64}
65
66#[derive(Debug)]
67pub struct BeaconChainBlockVerification<PosTable, CI, CSS> {
68    segment_headers_store: SegmentHeadersStore,
69    consensus_constants: ConsensusConstants,
70    pot_verifier: PotVerifier,
71    chain_info: CI,
72    chain_sync_status: CSS,
73    _pos_table: PhantomData<PosTable>,
74}
75
76impl<PosTable, CI, CSS> BlockVerification<OwnedBeaconChainBlock>
77    for BeaconChainBlockVerification<PosTable, CI, CSS>
78where
79    PosTable: Table,
80    CI: ChainInfo<OwnedBeaconChainBlock>,
81    CSS: ChainSyncStatus,
82{
83    #[inline(always)]
84    async fn verify(
85        &self,
86        parent_header: &GenericHeader<'_, OwnedBeaconChainBlock>,
87        parent_block_mmr_root: &Blake3Hash,
88        header: &GenericHeader<'_, OwnedBeaconChainBlock>,
89        body: &GenericBody<'_, OwnedBeaconChainBlock>,
90        origin: BlockOrigin,
91    ) -> Result<(), BlockVerificationError> {
92        self.verify(parent_header, parent_block_mmr_root, header, body, origin)
93            .await
94    }
95}
96
97impl<PosTable, CI, CSS> BeaconChainBlockVerification<PosTable, CI, CSS>
98where
99    PosTable: Table,
100    CI: ChainInfo<OwnedBeaconChainBlock>,
101    CSS: ChainSyncStatus,
102{
103    /// Create a new instance
104    #[inline(always)]
105    pub fn new(
106        segment_headers_store: SegmentHeadersStore,
107        consensus_constants: ConsensusConstants,
108        pot_verifier: PotVerifier,
109        chain_info: CI,
110        chain_sync_status: CSS,
111    ) -> Self {
112        Self {
113            segment_headers_store,
114            consensus_constants,
115            pot_verifier,
116            chain_info,
117            chain_sync_status,
118            _pos_table: PhantomData,
119        }
120    }
121
122    /// Determine if full proof of time verification is needed for this block number
123    fn full_pot_verification(&self, block_number: BlockNumber) -> bool {
124        let sync_target_block_number = self.chain_sync_status.target_block_number();
125        let Some(diff) = sync_target_block_number.checked_sub(block_number) else {
126            return true;
127        };
128        let diff = diff.as_u64();
129
130        let sample_size = match diff {
131            ..=1_581 => {
132                return true;
133            }
134            1_582..=6_234 => 1_581,
135            6_235..=63_240 => 3_162 * (diff - 3_162) / (diff - 1),
136            63_241..=3_162_000 => 3_162,
137            _ => diff / 1_000,
138        };
139
140        let n = rand::rng().random_range(0..=diff);
141
142        n < sample_size
143    }
144
145    fn check_header_prefix(
146        &self,
147        parent_header_prefix: &BlockHeaderPrefix,
148        parent_block_mmr_root: &Blake3Hash,
149        header_prefix: &BlockHeaderPrefix,
150    ) -> Result<(), BlockVerificationError> {
151        let basic_valid = header_prefix.number == parent_header_prefix.number + BlockNumber::ONE
152            && header_prefix.shard_index == parent_header_prefix.shard_index
153            && &header_prefix.mmr_root == parent_block_mmr_root
154            && header_prefix.timestamp > parent_header_prefix.timestamp;
155
156        if !basic_valid {
157            return Err(BlockVerificationError::InvalidHeaderPrefix);
158        }
159
160        let timestamp_now = SystemTime::now()
161            .duration_since(SystemTime::UNIX_EPOCH)
162            .unwrap_or_default()
163            .as_millis();
164        let timestamp_now = BlockTimestamp::new(u64::try_from(timestamp_now).unwrap_or(u64::MAX));
165
166        if header_prefix.timestamp
167            > timestamp_now.saturating_add(self.consensus_constants.max_block_timestamp_drift)
168        {
169            return Err(BlockVerificationError::TimestampTooFarInTheFuture);
170        }
171
172        Ok(())
173    }
174
175    fn check_consensus_parameters(
176        &self,
177        parent_block_root: &BlockRoot,
178        parent_header: &BeaconChainHeader<'_>,
179        header: &BeaconChainHeader<'_>,
180    ) -> Result<(), BeaconChainBlockVerificationError> {
181        let derived_consensus_parameters = derive_consensus_parameters(
182            &self.consensus_constants,
183            &self.chain_info,
184            parent_block_root,
185            parent_header.consensus_parameters(),
186            parent_header.consensus_info.slot,
187            header.prefix.number,
188            header.consensus_info.slot,
189        )?;
190
191        let expected_consensus_parameters = OwnedBlockHeaderConsensusParameters {
192            fixed_parameters: derived_consensus_parameters.fixed_parameters,
193            // TODO: Super segment support
194            super_segment_root: None,
195            next_solution_range: derived_consensus_parameters.next_solution_range,
196            pot_parameters_change: derived_consensus_parameters.pot_parameters_change,
197        };
198
199        if header.consensus_parameters() != &expected_consensus_parameters.as_ref() {
200            return Err(BeaconChainBlockVerificationError::InvalidConsensusParameters);
201        }
202
203        Ok(())
204    }
205
206    // TODO: This is a blocking function, but ideally wouldn't be block an executor
207    /// Checks current/future proof of time in the consensus info for the slot and corresponding
208    /// checkpoints.
209    ///
210    /// `consensus_parameters` is assumed to be correct and needs to be verified separately.
211    ///
212    /// When `verify_checkpoints == false` checkpoints are assumed to be correct and verification
213    /// for them is skipped.
214    #[expect(
215        clippy::too_many_arguments,
216        reason = "Explicit minimal input for better testability"
217    )]
218    fn check_proof_of_time(
219        pot_verifier: &PotVerifier,
220        block_authoring_delay: SlotNumber,
221        parent_slot: SlotNumber,
222        parent_proof_of_time: PotOutput,
223        parent_future_proof_of_time: PotOutput,
224        parent_consensus_parameters: &BlockHeaderConsensusParameters<'_>,
225        slot: SlotNumber,
226        proof_of_time: PotOutput,
227        future_proof_of_time: PotOutput,
228        consensus_parameters: &BlockHeaderConsensusParameters<'_>,
229        checkpoints: &[PotCheckpoints],
230        verify_checkpoints: bool,
231    ) -> Result<(), BeaconChainBlockVerificationError> {
232        let pot_parameters_change = consensus_parameters
233            .pot_parameters_change
234            .copied()
235            .map(PotParametersChange::from);
236
237        let parent_pot_parameters_change = parent_consensus_parameters
238            .pot_parameters_change
239            .copied()
240            .map(PotParametersChange::from);
241
242        // Last checkpoint must be the future proof of time
243        if checkpoints.last().map(PotCheckpoints::output) != Some(future_proof_of_time) {
244            return Err(BeaconChainBlockVerificationError::InvalidPotCheckpoints);
245        }
246
247        let parent_future_slot = if parent_slot == SlotNumber::ZERO {
248            parent_slot
249        } else {
250            parent_slot + block_authoring_delay
251        };
252
253        let slots_between_blocks = slot
254            .checked_sub(parent_slot)
255            .ok_or(BeaconChainBlockVerificationError::InvalidPotCheckpoints)?;
256        // Number of checkpoints must match the difference between parent's and this block's
257        // future slots. This also implicitly checks that there is a non-zero number of slots
258        // between this and parent block because list of checkpoints is already known to be not
259        // empty from the check above.
260        if slots_between_blocks.as_u64() != checkpoints.len() as u64 {
261            return Err(BeaconChainBlockVerificationError::InvalidPotCheckpoints);
262        }
263
264        let mut pot_input = if parent_slot == SlotNumber::ZERO {
265            PotNextSlotInput {
266                slot: parent_slot + SlotNumber::ONE,
267                slot_iterations: parent_consensus_parameters.fixed_parameters.slot_iterations,
268                seed: pot_verifier.genesis_seed(),
269            }
270        } else {
271            // Calculate slot iterations as of parent future slot
272            let slot_iterations = parent_pot_parameters_change
273                .and_then(|parameters_change| {
274                    (parameters_change.slot <= parent_future_slot)
275                        .then_some(parameters_change.slot_iterations)
276                })
277                .unwrap_or(parent_consensus_parameters.fixed_parameters.slot_iterations);
278            // Derive inputs to the slot, which follows parent future slot
279            PotNextSlotInput::derive(
280                slot_iterations,
281                parent_future_slot,
282                parent_future_proof_of_time,
283                &parent_pot_parameters_change,
284            )
285        };
286
287        // Collect all the data we will use for verification so we can process it in parallel
288        let checkpoints_verification_input = iter::once((
289            pot_input,
290            *checkpoints
291                .first()
292                .expect("Not empty, contents was checked above; qed"),
293        ));
294        let checkpoints_verification_input = checkpoints_verification_input
295            .chain(checkpoints.array_windows::<2>().map(|[left, right]| {
296                pot_input = PotNextSlotInput::derive(
297                    pot_input.slot_iterations,
298                    pot_input.slot,
299                    left.output(),
300                    &pot_parameters_change,
301                );
302
303                (pot_input, *right)
304            }))
305            // TODO: Would be nice to avoid extra allocation here
306            .collect::<Vec<_>>();
307
308        // All checkpoints must be valid, search for the first verification failure
309        let all_checkpoints_valid =
310            checkpoints_verification_input
311                .into_par_iter()
312                .all(|(pot_input, checkpoints)| {
313                    if verify_checkpoints {
314                        pot_verifier.verify_checkpoints(
315                            pot_input.seed,
316                            pot_input.slot_iterations,
317                            &checkpoints,
318                        )
319                    } else {
320                        // Store checkpoints as verified when verification is skipped
321                        pot_verifier.inject_verified_checkpoints(
322                            pot_input.seed,
323                            pot_input.slot_iterations,
324                            checkpoints,
325                        );
326                        true
327                    }
328                });
329
330        if !all_checkpoints_valid {
331            return Err(BeaconChainBlockVerificationError::InvalidPotCheckpoints);
332        }
333
334        // Make sure proof of time of this block correctly extends proof of time of the parent block
335        {
336            let pot_input = if parent_slot == SlotNumber::ZERO {
337                PotNextSlotInput {
338                    slot: parent_slot + SlotNumber::ONE,
339                    slot_iterations: parent_consensus_parameters.fixed_parameters.slot_iterations,
340                    seed: pot_verifier.genesis_seed(),
341                }
342            } else {
343                // Calculate slot iterations as of parent slot
344                let slot_iterations = parent_pot_parameters_change
345                    .and_then(|parameters_change| {
346                        (parameters_change.slot <= parent_slot)
347                            .then_some(parameters_change.slot_iterations)
348                    })
349                    .unwrap_or(parent_consensus_parameters.fixed_parameters.slot_iterations);
350                // Derive inputs to the slot, which follows parent slot
351                PotNextSlotInput::derive(
352                    slot_iterations,
353                    parent_slot,
354                    parent_proof_of_time,
355                    &parent_pot_parameters_change,
356                )
357            };
358
359            if pot_verifier.is_output_valid(
360                pot_input,
361                slots_between_blocks,
362                proof_of_time,
363                pot_parameters_change,
364            ) {
365                return Err(BeaconChainBlockVerificationError::InvalidProofOfTime);
366            }
367        }
368
369        Ok(())
370    }
371
372    fn check_body(
373        &self,
374        block_number: BlockNumber,
375        own_segment_roots: &[SegmentRoot],
376        _intermediate_shard_blocks: &IntermediateShardBlocksInfo<'_>,
377    ) -> Result<(), BlockVerificationError> {
378        let expected_segment_headers = self
379            .segment_headers_store
380            .segment_headers_for_block(block_number);
381        let correct_segment_roots = expected_segment_headers
382            .iter()
383            .map(|segment_header| &segment_header.segment_root)
384            .eq(own_segment_roots);
385        if !correct_segment_roots {
386            return Err(BlockVerificationError::InvalidOwnSegmentRoots {
387                expected: expected_segment_headers
388                    .iter()
389                    .map(|segment_header| segment_header.segment_root)
390                    .collect(),
391                actual: own_segment_roots.to_vec(),
392            });
393        }
394
395        // TODO: check intermediate shard blocks
396
397        Ok(())
398    }
399
400    async fn verify(
401        &self,
402        parent_header: &BeaconChainHeader<'_>,
403        parent_block_mmr_root: &Blake3Hash,
404        header: &BeaconChainHeader<'_>,
405        body: &BeaconChainBody<'_>,
406        _origin: BlockOrigin,
407    ) -> Result<(), BlockVerificationError> {
408        trace!(header = ?header, "Verifying");
409
410        let parent_block_root = parent_header.root();
411
412        let block_number = header.prefix.number;
413        let consensus_info = header.consensus_info;
414        let consensus_parameters = header.consensus_parameters();
415        let slot = consensus_info.slot;
416
417        let best_header = self.chain_info.best_header();
418        let best_header = best_header.header();
419        let best_number = best_header.prefix.number;
420
421        // Reject block below archiving point
422        if block_number + self.consensus_constants.confirmation_depth_k < best_number {
423            debug!(
424                ?header,
425                %best_number,
426                "Rejecting block below archiving point"
427            );
428
429            return Err(BlockVerificationError::BelowArchivingPoint);
430        }
431
432        self.check_header_prefix(parent_header.prefix, parent_block_mmr_root, header.prefix)?;
433
434        self.check_consensus_parameters(&parent_block_root, parent_header, header)?;
435
436        if !header.is_sealed_correctly() {
437            return Err(BlockVerificationError::InvalidSeal);
438        }
439
440        // Verify that solution is valid
441        consensus_info
442            .solution
443            .verify::<PosTable>(
444                slot,
445                &SolutionVerifyParams {
446                    proof_of_time: consensus_info.proof_of_time,
447                    solution_range: consensus_parameters.fixed_parameters.solution_range,
448                    // TODO: Piece check parameters
449                    piece_check_params: None,
450                },
451            )
452            .map_err(BeaconChainBlockVerificationError::from)?;
453
454        Self::check_proof_of_time(
455            &self.pot_verifier,
456            self.consensus_constants.block_authoring_delay,
457            parent_header.consensus_info.slot,
458            parent_header.consensus_info.proof_of_time,
459            parent_header.consensus_info.future_proof_of_time,
460            parent_header.consensus_parameters(),
461            consensus_info.slot,
462            consensus_info.proof_of_time,
463            consensus_info.future_proof_of_time,
464            consensus_parameters,
465            body.pot_checkpoints(),
466            self.full_pot_verification(block_number),
467        )?;
468
469        self.check_body(
470            block_number,
471            body.own_segment_roots(),
472            body.intermediate_shard_blocks(),
473        )?;
474
475        // TODO: Do something about equivocation?
476
477        Ok(())
478    }
479}