Skip to main content

ab_client_block_verification/
beacon_chain.rs

1#[cfg(test)]
2mod tests;
3
4use crate::shared::{BlockSlots, derive_block_slots};
5use crate::{BlockVerification, BlockVerificationError, GenericHeader};
6use ab_client_api::{BeaconChainInfo, BlockOrigin, ChainSyncStatus};
7use ab_client_consensus_common::ConsensusConstants;
8use ab_client_consensus_common::consensus_parameters::{
9    CheckShardSegmentsError, DeriveConsensusParametersChainInfo, DeriveConsensusParametersError,
10    DeriveSuperSegmentForBlockError, ShardMembershipEntropySourceChainInfo, check_shard_segments,
11    derive_consensus_parameters, derive_super_segment_for_block, shard_membership_entropy_source,
12};
13use ab_client_proof_of_time::PotNextSlotInput;
14use ab_client_proof_of_time::verifier::PotVerifier;
15use ab_core_primitives::block::body::{IntermediateShardBlocksInfo, OwnSegments};
16use ab_core_primitives::block::header::{
17    BeaconChainHeader, BlockHeaderPrefix, OwnedBlockHeaderConsensusParameters,
18};
19use ab_core_primitives::block::owned::OwnedBeaconChainBlock;
20use ab_core_primitives::block::{BlockNumber, BlockRoot, BlockTimestamp};
21use ab_core_primitives::hashes::Blake3Hash;
22use ab_core_primitives::pot::{PotCheckpoints, PotOutput, PotParametersChange, SlotNumber};
23use ab_core_primitives::sectors::SectorId;
24use ab_core_primitives::segments::{HistorySize, SegmentIndex, SuperSegment, SuperSegmentRoot};
25use ab_core_primitives::shard::ShardIndex;
26use ab_core_primitives::solutions::{
27    SolutionVerifyError, SolutionVerifyPieceParams, SolutionVerifyStatelessParams,
28};
29use ab_proof_of_space::Table;
30use rand::prelude::*;
31use rayon::prelude::*;
32use std::future::ready;
33use std::iter;
34use std::marker::PhantomData;
35use std::time::SystemTime;
36use tracing::{debug, trace};
37
38/// Errors for [`BeaconChainBlockVerification`]
39#[derive(Debug, thiserror::Error)]
40pub enum BeaconChainBlockVerificationError {
41    /// Consensus parameters derivation error
42    #[error("Consensus parameters derivation error: {error}")]
43    ConsensusParametersDerivation {
44        /// Consensus parameters derivation error
45        #[from]
46        error: DeriveConsensusParametersError,
47    },
48    /// Super segment derivation error
49    #[error("Super segment derivation error: {error}")]
50    SuperSegmentDerivation {
51        /// Super segment derivation error
52        #[from]
53        error: DeriveSuperSegmentForBlockError,
54    },
55    /// Shard segments check error
56    #[error("Shard segments check error: {error}")]
57    ShardSegmentsCheck {
58        /// Shard segments check error
59        #[from]
60        error: CheckShardSegmentsError,
61    },
62    /// Invalid consensus parameters
63    #[error("Invalid consensus parameters: expected {expected:?}, actual {actual:?}")]
64    InvalidConsensusParameters {
65        /// Expected consensus parameters
66        expected: Box<OwnedBlockHeaderConsensusParameters>,
67        /// Actual consensus parameters
68        actual: Box<OwnedBlockHeaderConsensusParameters>,
69    },
70    /// Missing a super segment in the first block
71    #[error("Missing super segment in the first block")]
72    MissingSuperSegmentInFirstBlock,
73    /// Previous super segment header not found
74    #[error("Previous super segment header not found")]
75    PreviousSuperSegmentHeaderNotFound,
76    /// Super segment of the solution's piece not found
77    #[error("Super segment of the solution's piece in segment {segment_index} not found")]
78    SolutionSuperSegmentNotFound {
79        /// Segment index of the piece the solution's sector requires
80        segment_index: SegmentIndex,
81    },
82    /// Invalid history size
83    #[error("Invalid history size {history_size} (current {current_history_size})")]
84    InvalidHistorySize {
85        /// History size in the solution
86        history_size: HistorySize,
87        /// Current history size
88        current_history_size: HistorySize,
89    },
90    /// Invalid super segment root
91    #[error("Invalid super segment root: expected {expected:?}, actual {actual:?}")]
92    InvalidSuperSegmentRoot {
93        /// Expected super segment root
94        expected: Box<Option<SuperSegmentRoot>>,
95        /// Actual super segment root
96        actual: Box<Option<SuperSegmentRoot>>,
97    },
98    /// Invalid PoT checkpoints
99    #[error("Invalid PoT checkpoints")]
100    InvalidPotCheckpoints,
101    /// Invalid proof of time
102    #[error("Invalid proof of time")]
103    InvalidProofOfTime,
104    /// Solution error
105    #[error("Solution error: {error}")]
106    SolutionError {
107        /// Solution error
108        #[from]
109        error: SolutionVerifyError,
110    },
111}
112
113impl From<BeaconChainBlockVerificationError> for BlockVerificationError {
114    #[inline(always)]
115    fn from(error: BeaconChainBlockVerificationError) -> Self {
116        Self::Custom {
117            error: error.into(),
118        }
119    }
120}
121
122/// Whether a block with `block_number` can't become a part of the best chain anymore.
123///
124/// Importing the next best block (block number `best_number + 1`) confirms the block at
125/// `best_number + 1 - block_confirmation_depth` (see
126/// [`ConsensusConstants::block_confirmation_depth`]). A block being verified at or below that block
127/// number would compete with a block that can't change anymore, the database refuses the same
128/// blocks (see the block lifecycle on `ClientDatabaseOptions` in `ab-client-database`).
129///
130/// With `block_confirmation_depth = 5`:
131///
132/// ```text
133/// block number of the block being verified
134/// best_number + 1                             accepted, the next best block
135/// best_number - 3 ..= best_number             accepted, forks
136/// best_number - 4 and below                   rejected
137/// ```
138fn is_below_archiving_point(
139    block_number: BlockNumber,
140    best_number: BlockNumber,
141    block_confirmation_depth: BlockNumber,
142) -> bool {
143    // The block number of a block being verified is not checked yet, a sum that overflows is
144    // above any best block number
145    block_number
146        .checked_add(block_confirmation_depth)
147        .is_some_and(|sum| sum <= best_number + BlockNumber::ONE)
148}
149
150// TODO: This is a blocking function, but ideally wouldn't be block an executor
151/// Checks current/future proof of time in the consensus info for the slot and corresponding
152/// checkpoints.
153///
154/// `consensus_parameters` is assumed to be correct and needs to be verified separately.
155///
156/// When `verify_checkpoints == false` checkpoints are assumed to be correct and verification
157/// for them is skipped.
158#[expect(
159    clippy::too_many_arguments,
160    reason = "Explicit minimal input for better testability"
161)]
162fn check_proof_of_time(
163    pot_verifier: &PotVerifier,
164    block_authoring_delay: SlotNumber,
165    parent_slot: SlotNumber,
166    parent_proof_of_time: PotOutput,
167    parent_future_proof_of_time: PotOutput,
168    parent_consensus_parameters: &OwnedBlockHeaderConsensusParameters,
169    slot: SlotNumber,
170    proof_of_time: PotOutput,
171    future_proof_of_time: PotOutput,
172    checkpoints: &[PotCheckpoints],
173    verify_checkpoints: bool,
174) -> Result<(), BlockVerificationError> {
175    let BlockSlots {
176        future_slot,
177        parent_future_slot,
178        slots_between_blocks,
179    } = derive_block_slots(block_authoring_delay, parent_slot, slot)?;
180
181    let parent_pot_parameters_change = parent_consensus_parameters
182        .pot_parameters_change
183        .map(PotParametersChange::from);
184
185    // The last checkpoint must be the future proof of time
186    if checkpoints.last().map(PotCheckpoints::output) != Some(future_proof_of_time) {
187        return Err(BlockVerificationError::from(
188            BeaconChainBlockVerificationError::InvalidPotCheckpoints,
189        ));
190    }
191
192    // The number of checkpoints must match the difference between parent's and this block's
193    // future slots.
194    //
195    // The first block after genesis is a special case and is handled separately here.
196    if !(u64::from(slots_between_blocks) == checkpoints.len() as u64
197        || (parent_slot == SlotNumber::ZERO && u64::from(future_slot) == checkpoints.len() as u64))
198    {
199        return Err(BlockVerificationError::from(
200            BeaconChainBlockVerificationError::InvalidPotCheckpoints,
201        ));
202    }
203
204    let mut pot_input = if parent_slot == SlotNumber::ZERO {
205        PotNextSlotInput {
206            slot: parent_slot + SlotNumber::ONE,
207            slot_iterations: parent_consensus_parameters.fixed_parameters.slot_iterations,
208            seed: pot_verifier.genesis_seed(),
209        }
210    } else {
211        // Calculate slot iterations as of parent future slot
212        let slot_iterations = parent_pot_parameters_change
213            .and_then(|parameters_change| {
214                (parameters_change.slot <= parent_future_slot)
215                    .then_some(parameters_change.slot_iterations)
216            })
217            .unwrap_or(parent_consensus_parameters.fixed_parameters.slot_iterations);
218        // Derive inputs to the slot, which follows the parent future slot
219        PotNextSlotInput::derive(
220            slot_iterations,
221            parent_future_slot,
222            parent_future_proof_of_time,
223            &parent_pot_parameters_change,
224        )
225    };
226
227    // Collect all the data we will use for verification so we can process it in parallel
228    let checkpoints_verification_input = iter::once((
229        pot_input,
230        *checkpoints
231            .first()
232            .expect("Not empty, contents was checked above; qed"),
233    ));
234    let checkpoints_verification_input = checkpoints_verification_input
235        .chain(checkpoints.array_windows::<2>().map(|[left, right]| {
236            pot_input = PotNextSlotInput::derive(
237                pot_input.slot_iterations,
238                pot_input.slot,
239                left.output(),
240                &parent_pot_parameters_change,
241            );
242
243            (pot_input, *right)
244        }))
245        // TODO: Would be nice to avoid extra allocation here
246        .collect::<Vec<_>>();
247
248    // All checkpoints must be valid, search for the first verification failure
249    let all_checkpoints_valid =
250        checkpoints_verification_input
251            .into_par_iter()
252            .all(|(pot_input, checkpoints)| {
253                if verify_checkpoints {
254                    pot_verifier.verify_checkpoints(
255                        pot_input.seed,
256                        pot_input.slot_iterations,
257                        &checkpoints,
258                    )
259                } else {
260                    // Store checkpoints as verified when verification is skipped
261                    pot_verifier.inject_verified_checkpoints(
262                        pot_input.seed,
263                        pot_input.slot_iterations,
264                        checkpoints,
265                    );
266                    true
267                }
268            });
269
270    if !all_checkpoints_valid {
271        return Err(BlockVerificationError::from(
272            BeaconChainBlockVerificationError::InvalidPotCheckpoints,
273        ));
274    }
275
276    // Make sure proof of time of this block correctly extends proof of time of the parent block
277    {
278        let pot_input = if parent_slot == SlotNumber::ZERO {
279            PotNextSlotInput {
280                slot: parent_slot + SlotNumber::ONE,
281                slot_iterations: parent_consensus_parameters.fixed_parameters.slot_iterations,
282                seed: pot_verifier.genesis_seed(),
283            }
284        } else {
285            // Calculate slot iterations as of the parent slot
286            let slot_iterations = parent_pot_parameters_change
287                .and_then(|parameters_change| {
288                    (parameters_change.slot <= parent_slot)
289                        .then_some(parameters_change.slot_iterations)
290                })
291                .unwrap_or(parent_consensus_parameters.fixed_parameters.slot_iterations);
292            // Derive inputs to the slot, which follows the parent slot
293            PotNextSlotInput::derive(
294                slot_iterations,
295                parent_slot,
296                parent_proof_of_time,
297                &parent_pot_parameters_change,
298            )
299        };
300
301        if !pot_verifier.is_output_valid(
302            pot_input,
303            slots_between_blocks,
304            proof_of_time,
305            parent_pot_parameters_change,
306        ) {
307            return Err(BlockVerificationError::from(
308                BeaconChainBlockVerificationError::InvalidProofOfTime,
309            ));
310        }
311    }
312
313    Ok(())
314}
315
316#[derive(Debug)]
317pub struct BeaconChainBlockVerification<PosTable, CI, CSS> {
318    consensus_constants: ConsensusConstants,
319    pot_verifier: PotVerifier,
320    chain_info: CI,
321    chain_sync_status: CSS,
322    _pos_table: PhantomData<PosTable>,
323}
324
325impl<PosTable, CI, CSS> BlockVerification<OwnedBeaconChainBlock, Option<SuperSegment>>
326    for BeaconChainBlockVerification<PosTable, CI, CSS>
327where
328    PosTable: Table,
329    CI: BeaconChainInfo,
330    CSS: ChainSyncStatus,
331{
332    #[inline(always)]
333    fn verify_concurrent<BCI>(
334        &self,
335        parent_header: &GenericHeader<'_, OwnedBeaconChainBlock>,
336        parent_block_mmr_root: &Blake3Hash,
337        block: &OwnedBeaconChainBlock,
338        origin: &BlockOrigin,
339        beacon_chain_info: &BCI,
340    ) -> impl Future<Output = Result<(), BlockVerificationError>>
341    where
342        BCI: DeriveConsensusParametersChainInfo + ShardMembershipEntropySourceChainInfo,
343    {
344        ready(self.verify_concurrent(
345            parent_header,
346            parent_block_mmr_root,
347            block,
348            origin,
349            beacon_chain_info,
350        ))
351    }
352
353    #[inline(always)]
354    fn verify_sequential(
355        &self,
356        parent_header: &GenericHeader<'_, OwnedBeaconChainBlock>,
357        block: &OwnedBeaconChainBlock,
358        origin: &BlockOrigin,
359    ) -> impl Future<Output = Result<Option<SuperSegment>, BlockVerificationError>> {
360        ready(self.verify_sequential(parent_header, block, origin))
361    }
362}
363
364impl<PosTable, CI, CSS> BeaconChainBlockVerification<PosTable, CI, CSS>
365where
366    PosTable: Table,
367    CI: BeaconChainInfo,
368    CSS: ChainSyncStatus,
369{
370    /// Create a new instance
371    #[inline(always)]
372    pub fn new(
373        consensus_constants: ConsensusConstants,
374        pot_verifier: PotVerifier,
375        chain_info: CI,
376        chain_sync_status: CSS,
377    ) -> Self {
378        Self {
379            consensus_constants,
380            pot_verifier,
381            chain_info,
382            chain_sync_status,
383            _pos_table: PhantomData,
384        }
385    }
386
387    /// Determine if full proof of time verification is needed for this block number
388    fn full_pot_verification(&self, block_number: BlockNumber) -> bool {
389        let sync_target_block_number = self.chain_sync_status.target_block_number();
390        let Some(diff) = sync_target_block_number.checked_sub(block_number) else {
391            return true;
392        };
393        let diff = u64::from(diff);
394
395        let sample_size = match diff {
396            ..=1_581 => {
397                return true;
398            }
399            1_582..=6_234 => 1_581,
400            6_235..=63_240 => 3_162 * (diff - 3_162) / (diff - 1),
401            63_241..=3_162_000 => 3_162,
402            _ => diff / 1_000,
403        };
404
405        let n = rand::rng().random_range(0..=diff);
406
407        n < sample_size
408    }
409
410    fn check_header_prefix(
411        &self,
412        parent_header_prefix: &BlockHeaderPrefix,
413        parent_block_mmr_root: &Blake3Hash,
414        header_prefix: &BlockHeaderPrefix,
415    ) -> Result<(), BlockVerificationError> {
416        let basic_valid = header_prefix.number == parent_header_prefix.number + BlockNumber::ONE
417            && header_prefix.shard_index == parent_header_prefix.shard_index
418            && &header_prefix.mmr_root == parent_block_mmr_root
419            && header_prefix.timestamp > parent_header_prefix.timestamp;
420
421        if !basic_valid {
422            return Err(BlockVerificationError::InvalidHeaderPrefix);
423        }
424
425        let timestamp_now = SystemTime::now()
426            .duration_since(SystemTime::UNIX_EPOCH)
427            .unwrap_or_default()
428            .as_millis();
429        let timestamp_now =
430            BlockTimestamp::from_millis(u64::try_from(timestamp_now).unwrap_or(u64::MAX));
431
432        if header_prefix.timestamp
433            > timestamp_now.saturating_add(self.consensus_constants.max_block_timestamp_drift)
434        {
435            return Err(BlockVerificationError::TimestampTooFarInTheFuture);
436        }
437
438        Ok(())
439    }
440
441    fn check_consensus_parameters_concurrent<BCI>(
442        &self,
443        parent_block_root: &BlockRoot,
444        parent_header: &BeaconChainHeader<'_>,
445        header: &BeaconChainHeader<'_>,
446        beacon_chain_info: &BCI,
447    ) -> Result<(), BeaconChainBlockVerificationError>
448    where
449        BCI: DeriveConsensusParametersChainInfo,
450    {
451        let derived_consensus_parameters = derive_consensus_parameters(
452            &self.consensus_constants,
453            beacon_chain_info,
454            parent_block_root,
455            parent_header.consensus_parameters(),
456            parent_header.consensus_info.slot,
457            header.prefix.number,
458            header.consensus_info.slot,
459        )?;
460
461        let actual_consensus_parameters =
462            OwnedBlockHeaderConsensusParameters::from(header.consensus_parameters());
463        let expected_consensus_parameters = OwnedBlockHeaderConsensusParameters {
464            fixed_parameters: derived_consensus_parameters.fixed_parameters,
465            // TODO: This field is verified separately in the sequential part
466            super_segment_root: actual_consensus_parameters.super_segment_root,
467            next_solution_range: derived_consensus_parameters.next_solution_range,
468            pot_parameters_change: derived_consensus_parameters.pot_parameters_change,
469        };
470
471        if actual_consensus_parameters != expected_consensus_parameters {
472            return Err(
473                BeaconChainBlockVerificationError::InvalidConsensusParameters {
474                    expected: Box::new(expected_consensus_parameters),
475                    actual: Box::new(actual_consensus_parameters),
476                },
477            );
478        }
479
480        Ok(())
481    }
482
483    fn check_body(
484        &self,
485        block_number: BlockNumber,
486        parent_block_root: &BlockRoot,
487        own_segments: Option<OwnSegments<'_>>,
488        intermediate_shard_blocks: &IntermediateShardBlocksInfo<'_>,
489    ) -> Result<(), BlockVerificationError> {
490        let expected_segment_headers = self.chain_info.segment_headers_for_block(block_number);
491        let expected_first_local_segment_index = expected_segment_headers
492            .first()
493            .map(|segment_header| segment_header.index.as_inner());
494        let correct_first_local_segment_index = expected_first_local_segment_index
495            == own_segments
496                .as_ref()
497                .map(|own_segments| own_segments.first_local_segment_index);
498        let correct_segment_roots = expected_segment_headers
499            .iter()
500            .map(|segment_header| &segment_header.root)
501            .eq(own_segments
502                .as_ref()
503                .map_or_default(|own_segments| own_segments.segment_roots));
504        if !(correct_first_local_segment_index && correct_segment_roots) {
505            return Err(BlockVerificationError::InvalidOwnSegments {
506                expected_first_local_segment_index,
507                expected_segment_roots: expected_segment_headers
508                    .iter()
509                    .map(|segment_header| segment_header.root)
510                    .collect(),
511                actual_first_local_segment_index: own_segments
512                    .as_ref()
513                    .map(|own_segments| own_segments.first_local_segment_index),
514                actual_segment_roots: own_segments
515                    .as_ref()
516                    .map_or_default(|own_segments| own_segments.segment_roots.to_vec()),
517            });
518        }
519
520        // TODO: Check headers of intermediate shard blocks included in the body, like continuity of
521        //  their block numbers and parent links
522
523        check_shard_segments(
524            &self.chain_info,
525            block_number,
526            parent_block_root,
527            intermediate_shard_blocks
528                .iter()
529                .flat_map(|intermediate_shard_block_info| {
530                    let shard_index = intermediate_shard_block_info.header.prefix.shard_index;
531
532                    intermediate_shard_block_info
533                        .own_segments
534                        .map(|own_segments| (shard_index, own_segments))
535                        .into_iter()
536                        .chain(intermediate_shard_block_info.leaf_shards_segments().map(
537                            |(_position, shard_index, own_segments)| (shard_index, own_segments),
538                        ))
539                }),
540            self.consensus_constants.block_confirmation_depth,
541            self.consensus_constants.shard_confirmation_depth,
542        )
543        .map_err(BeaconChainBlockVerificationError::from)?;
544
545        Ok(())
546    }
547
548    fn verify_concurrent<BCI>(
549        &self,
550        parent_header: &BeaconChainHeader<'_>,
551        parent_block_mmr_root: &Blake3Hash,
552        block: &OwnedBeaconChainBlock,
553        _origin: &BlockOrigin,
554        beacon_chain_info: &BCI,
555    ) -> Result<(), BlockVerificationError>
556    where
557        BCI: DeriveConsensusParametersChainInfo + ShardMembershipEntropySourceChainInfo,
558    {
559        let header = block.header.header();
560        let body = block.body.body();
561
562        trace!(header = ?header, "Verify concurrent");
563
564        let parent_block_root = parent_header.root();
565
566        let block_number = header.prefix.number;
567        let consensus_info = header.consensus_info;
568        let consensus_parameters = header.consensus_parameters();
569        let slot = consensus_info.slot;
570
571        let best_header = self.chain_info.best_header();
572        let best_header = best_header.header();
573        let best_number = best_header.prefix.number;
574
575        if is_below_archiving_point(
576            block_number,
577            best_number,
578            self.consensus_constants.block_confirmation_depth,
579        ) {
580            debug!(
581                ?header,
582                %best_number,
583                "Rejecting a block below the archiving point"
584            );
585
586            return Err(BlockVerificationError::BelowArchivingPoint);
587        }
588
589        self.check_header_prefix(parent_header.prefix, parent_block_mmr_root, header.prefix)?;
590
591        self.check_consensus_parameters_concurrent(
592            &parent_block_root,
593            parent_header,
594            header,
595            beacon_chain_info,
596        )?;
597
598        if !header.is_sealed_correctly() {
599            return Err(BlockVerificationError::InvalidSeal);
600        }
601
602        // Find shard membership entropy for the slot
603        let shard_membership_entropy = shard_membership_entropy_source(
604            header.prefix.number,
605            &parent_block_root,
606            self.consensus_constants.shard_rotation_interval,
607            self.consensus_constants.shard_rotation_delay,
608            beacon_chain_info,
609        )?;
610
611        // Verify that the solution is valid (stateless half)
612        consensus_info
613            .solution
614            .verify_stateless::<PosTable>(
615                slot,
616                &SolutionVerifyStatelessParams {
617                    shard_index: ShardIndex::BEACON_CHAIN,
618                    proof_of_time: consensus_info.proof_of_time,
619                    solution_range: consensus_parameters.fixed_parameters.solution_range,
620                    shard_membership_entropy,
621                    num_shards: consensus_parameters.fixed_parameters.num_shards,
622                },
623            )
624            .map_err(BeaconChainBlockVerificationError::from)?;
625
626        check_proof_of_time(
627            &self.pot_verifier,
628            self.consensus_constants.block_authoring_delay,
629            parent_header.consensus_info.slot,
630            parent_header.consensus_info.proof_of_time,
631            parent_header.consensus_info.future_proof_of_time,
632            &OwnedBlockHeaderConsensusParameters::from(parent_header.consensus_parameters()),
633            consensus_info.slot,
634            consensus_info.proof_of_time,
635            consensus_info.future_proof_of_time,
636            body.pot_checkpoints(),
637            self.full_pot_verification(block_number),
638        )?;
639
640        // TODO: Do something about equivocation?
641
642        Ok(())
643    }
644
645    fn verify_sequential(
646        &self,
647        parent_header: &BeaconChainHeader<'_>,
648        block: &OwnedBeaconChainBlock,
649        _origin: &BlockOrigin,
650    ) -> Result<Option<SuperSegment>, BlockVerificationError> {
651        let header = block.header.header();
652        let body = block.body.body();
653
654        trace!(header = ?header, "Verify sequential");
655
656        let block_number = header.prefix.number;
657        let consensus_info = header.consensus_info;
658
659        let best_header = self.chain_info.best_header();
660        let best_header = best_header.header();
661        let best_number = best_header.prefix.number;
662
663        if is_below_archiving_point(
664            block_number,
665            best_number,
666            self.consensus_constants.block_confirmation_depth,
667        ) {
668            debug!(
669                ?header,
670                %best_number,
671                "Rejecting a block below the archiving point"
672            );
673
674            return Err(BlockVerificationError::BelowArchivingPoint);
675        }
676
677        let parent_block_root = parent_header.root();
678
679        let maybe_super_segment = derive_super_segment_for_block(
680            &self.chain_info,
681            parent_header.prefix.number,
682            &parent_block_root,
683            self.consensus_constants.block_confirmation_depth,
684            self.consensus_constants.shard_confirmation_depth,
685        )
686        .map_err(BeaconChainBlockVerificationError::from)?;
687        let maybe_super_segment_root = maybe_super_segment
688            .as_ref()
689            .map(|super_segment| super_segment.header.root);
690
691        if maybe_super_segment_root.as_ref() != header.consensus_parameters().super_segment_root {
692            return Err(BlockVerificationError::from(
693                BeaconChainBlockVerificationError::InvalidSuperSegmentRoot {
694                    expected: Box::new(maybe_super_segment_root),
695                    actual: Box::new(header.consensus_parameters().super_segment_root.copied()),
696                },
697            ));
698        }
699
700        // Verify that the solution is valid (piece verification half)
701        {
702            // TODO: Query it from an actual chain
703            let max_pieces_in_sector = 1000;
704
705            let (current_history_size, solution_super_segment_header) = if block_number
706                == BlockNumber::ONE
707            {
708                // With history size one the piece is in the genesis segment, which is in the super
709                // segment this block creates
710                let latest_super_segment = maybe_super_segment
711                    .as_ref()
712                    .ok_or(BeaconChainBlockVerificationError::MissingSuperSegmentInFirstBlock)?;
713
714                (HistorySize::ONE, latest_super_segment.header)
715            } else {
716                let max_segment_index = self
717                    .chain_info
718                    .previous_super_segment_header(block_number)
719                    .ok_or(BeaconChainBlockVerificationError::PreviousSuperSegmentHeaderNotFound)?
720                    .max_segment_index
721                    .as_inner();
722                let current_history_size = HistorySize::from(max_segment_index);
723
724                let solution = &consensus_info.solution;
725                let segment_index = SectorId::new(
726                    &solution.public_key_hash,
727                    &solution.shard_commitment.root,
728                    solution.sector_index,
729                    solution.history_size,
730                )
731                .derive_piece_index(
732                    solution.piece_offset,
733                    solution.history_size,
734                    max_pieces_in_sector,
735                    self.consensus_constants.recent_segments,
736                    self.consensus_constants.recent_history_fraction,
737                )
738                .segment_index();
739                let solution_super_segment_header = self
740                    .chain_info
741                    .get_super_segment_header_for_segment_index(segment_index)
742                    .ok_or(
743                        BeaconChainBlockVerificationError::SolutionSuperSegmentNotFound {
744                            segment_index,
745                        },
746                    )?;
747
748                (current_history_size, solution_super_segment_header)
749            };
750
751            let sector_expiration_check_super_segment_root = self
752                .chain_info
753                .get_super_segment_header_for_segment_index(
754                    consensus_info
755                        .solution
756                        .history_size
757                        .sector_expiration_check(self.consensus_constants.min_sector_lifetime)
758                        .ok_or(BeaconChainBlockVerificationError::InvalidHistorySize {
759                            history_size: consensus_info.solution.history_size,
760                            current_history_size,
761                        })?
762                        .segment_index(),
763                )
764                .map(|super_segment_header| super_segment_header.root);
765
766            consensus_info
767                .solution
768                .verify_piece(&SolutionVerifyPieceParams {
769                    max_pieces_in_sector,
770                    super_segment_root: solution_super_segment_header.root,
771                    num_segments: solution_super_segment_header.num_segments,
772                    max_segment_index: solution_super_segment_header.max_segment_index.as_inner(),
773                    recent_segments: self.consensus_constants.recent_segments,
774                    recent_history_fraction: self.consensus_constants.recent_history_fraction,
775                    min_sector_lifetime: self.consensus_constants.min_sector_lifetime,
776                    current_history_size,
777                    sector_expiration_check_super_segment_root,
778                })
779                .map_err(BeaconChainBlockVerificationError::from)?;
780        }
781
782        self.check_body(
783            block_number,
784            &parent_block_root,
785            body.own_segments(),
786            body.intermediate_shard_blocks(),
787        )?;
788
789        Ok(maybe_super_segment)
790    }
791}