Skip to main content

ab_client_consensus_common/
consensus_parameters.rs

1#[cfg(test)]
2mod tests;
3
4use crate::{ConsensusConstants, PotConsensusConstants};
5use ab_client_api::{BeaconChainInfo, ChainInfo, ShardSegmentRoot, ShardSegmentRootsError};
6use ab_core_primitives::block::body::OwnSegments;
7use ab_core_primitives::block::header::{
8    BlockHeaderConsensusInfo, BlockHeaderConsensusParameters, BlockHeaderFixedConsensusParameters,
9    BlockHeaderPotParametersChange,
10};
11use ab_core_primitives::block::owned::OwnedBeaconChainBlock;
12use ab_core_primitives::block::{BlockNumber, BlockRoot};
13use ab_core_primitives::hashes::Blake3Hash;
14use ab_core_primitives::pieces::RecordChunk;
15use ab_core_primitives::pot::{PotOutput, PotParametersChange, SlotNumber};
16use ab_core_primitives::segments::{
17    LocalSegmentIndex, SegmentIndex, SegmentPosition, SegmentRoot, ShardSegmentRootWithPosition,
18    SuperSegment, SuperSegmentHeader, SuperSegmentIndex, SuperSegmentRoot,
19};
20use ab_core_primitives::shard::ShardIndex;
21use ab_core_primitives::solutions::{ShardMembershipEntropy, SolutionRange};
22use std::collections::HashMap;
23use std::num::NonZeroU32;
24use std::sync::Arc as StdArc;
25use triomphe::Arc;
26
27struct SolutionRanges {
28    current: SolutionRange,
29    next: Option<SolutionRange>,
30}
31
32struct PotInfo {
33    slot_iterations: NonZeroU32,
34    parameters_change: Option<PotParametersChange>,
35}
36
37/// Derived consensus parameters, to be eventually turned into
38/// [`OwnedBlockHeaderConsensusParameters`]
39///
40/// [`OwnedBlockHeaderConsensusParameters`]: ab_core_primitives::block::header::OwnedBlockHeaderConsensusParameters
41#[derive(Debug, Copy, Clone)]
42pub struct DerivedConsensusParameters {
43    /// Consensus parameters that are always present
44    pub fixed_parameters: BlockHeaderFixedConsensusParameters,
45    /// Solution range for the next block/interval (if any)
46    pub next_solution_range: Option<SolutionRange>,
47    /// Change of parameters to apply to the proof of time chain (if any)
48    pub pot_parameters_change: Option<BlockHeaderPotParametersChange>,
49}
50
51/// Error for [`derive_consensus_parameters()`]
52#[derive(Debug, thiserror::Error)]
53pub enum DeriveConsensusParametersError {
54    /// Failed to get ancestor header
55    #[error("Failed to get ancestor header")]
56    GetAncestorHeader,
57}
58
59/// A limited subset of [`BlockHeaderConsensusInfo`] for [`derive_consensus_parameters()`]
60#[derive(Debug, Clone, Copy)]
61pub struct DeriveConsensusParametersConsensusInfo {
62    /// Slot number
63    pub slot: SlotNumber,
64    /// Proof of time for this slot
65    pub proof_of_time: PotOutput,
66    /// Record chunk used in a solution
67    pub solution_record_chunk: RecordChunk,
68}
69
70impl DeriveConsensusParametersConsensusInfo {
71    pub fn from_consensus_info(consensus_info: &BlockHeaderConsensusInfo) -> Self {
72        Self {
73            slot: consensus_info.slot,
74            proof_of_time: consensus_info.proof_of_time,
75            solution_record_chunk: consensus_info.solution.chunk,
76        }
77    }
78}
79
80/// Chain info for [`derive_consensus_parameters()`].
81///
82/// Must have access to enough parent blocks.
83pub trait DeriveConsensusParametersChainInfo: Send + Sync {
84    /// Get consensus info of the block at `ancestor_block_number` on the chain ending at
85    /// `descendant_block_root`.
86    ///
87    /// If `ancestor_block_number` is the descendant's own number, the descendant's consensus info
88    /// is returned. Returns `None` if `ancestor_block_number` is higher than the descendant's
89    /// number or if either block is not available.
90    fn ancestor_header_consensus_info(
91        &self,
92        ancestor_block_number: BlockNumber,
93        descendant_block_root: &BlockRoot,
94    ) -> Option<DeriveConsensusParametersConsensusInfo>;
95}
96
97impl<T> DeriveConsensusParametersChainInfo for T
98where
99    T: ChainInfo<OwnedBeaconChainBlock>,
100{
101    fn ancestor_header_consensus_info(
102        &self,
103        ancestor_block_number: BlockNumber,
104        descendant_block_root: &BlockRoot,
105    ) -> Option<DeriveConsensusParametersConsensusInfo> {
106        let header = self.ancestor_header(ancestor_block_number, descendant_block_root)?;
107
108        Some(DeriveConsensusParametersConsensusInfo::from_consensus_info(
109            header.header().consensus_info,
110        ))
111    }
112}
113
114pub fn derive_consensus_parameters<BCI>(
115    consensus_constants: &ConsensusConstants,
116    beacon_chain_info: &BCI,
117    parent_block_root: &BlockRoot,
118    parent_consensus_parameters: &BlockHeaderConsensusParameters<'_>,
119    parent_slot: SlotNumber,
120    block_number: BlockNumber,
121    slot: SlotNumber,
122) -> Result<DerivedConsensusParameters, DeriveConsensusParametersError>
123where
124    BCI: DeriveConsensusParametersChainInfo,
125{
126    let solution_ranges = derive_solution_ranges(
127        consensus_constants.retarget_interval,
128        consensus_constants.slot_probability,
129        beacon_chain_info,
130        parent_block_root,
131        parent_consensus_parameters.fixed_parameters.solution_range,
132        parent_consensus_parameters.next_solution_range,
133        block_number,
134        slot,
135    )?;
136    let pot_info = derive_pot_info(
137        &consensus_constants.pot,
138        beacon_chain_info,
139        parent_block_root,
140        parent_slot,
141        parent_consensus_parameters.fixed_parameters.slot_iterations,
142        parent_consensus_parameters
143            .pot_parameters_change
144            .copied()
145            .map(PotParametersChange::from),
146        block_number,
147        slot,
148    )?;
149
150    Ok(DerivedConsensusParameters {
151        fixed_parameters: BlockHeaderFixedConsensusParameters {
152            solution_range: solution_ranges.current,
153            slot_iterations: pot_info.slot_iterations,
154            num_shards: parent_consensus_parameters.fixed_parameters.num_shards,
155        },
156        next_solution_range: solution_ranges.next,
157        pot_parameters_change: pot_info
158            .parameters_change
159            .map(BlockHeaderPotParametersChange::from),
160    })
161}
162
163#[expect(
164    clippy::too_many_arguments,
165    reason = "Explicit minimal input for better testability"
166)]
167fn derive_solution_ranges<BCI>(
168    retarget_interval: BlockNumber,
169    slot_probability: (u64, u64),
170    beacon_chain_info: &BCI,
171    parent_block_root: &BlockRoot,
172    solution_range: SolutionRange,
173    next_solution_range: Option<SolutionRange>,
174    block_number: BlockNumber,
175    slot: SlotNumber,
176) -> Result<SolutionRanges, DeriveConsensusParametersError>
177where
178    BCI: DeriveConsensusParametersChainInfo,
179{
180    if let Some(next_solution_range) = next_solution_range {
181        return Ok(SolutionRanges {
182            current: next_solution_range,
183            next: None,
184        });
185    }
186
187    let next_solution_range = if u64::from(block_number)
188        .is_multiple_of(u64::from(retarget_interval))
189        && block_number > retarget_interval
190    {
191        let interval_start_block = block_number.saturating_sub(retarget_interval);
192        let interval_start_slot = beacon_chain_info
193            .ancestor_header_consensus_info(interval_start_block, parent_block_root)
194            .ok_or(DeriveConsensusParametersError::GetAncestorHeader)?
195            .slot;
196
197        Some(solution_range.derive_next(
198            slot.saturating_sub(interval_start_slot),
199            slot_probability,
200            retarget_interval,
201        ))
202    } else {
203        None
204    };
205
206    Ok(SolutionRanges {
207        current: solution_range,
208        next: next_solution_range,
209    })
210}
211
212#[expect(
213    clippy::too_many_arguments,
214    reason = "Explicit minimal input for better testability"
215)]
216fn derive_pot_info<BCI>(
217    pot_consensus_constants: &PotConsensusConstants,
218    beacon_chain_info: &BCI,
219    parent_block_root: &BlockRoot,
220    parent_slot: SlotNumber,
221    parent_slot_iterations: NonZeroU32,
222    parent_parameters_change: Option<PotParametersChange>,
223    block_number: BlockNumber,
224    slot: SlotNumber,
225) -> Result<PotInfo, DeriveConsensusParametersError>
226where
227    BCI: DeriveConsensusParametersChainInfo,
228{
229    let pot_entropy_injection_interval = pot_consensus_constants.entropy_injection_interval;
230    let pot_entropy_injection_lookback_depth =
231        pot_consensus_constants.entropy_injection_lookback_depth;
232    let pot_entropy_injection_delay = pot_consensus_constants.entropy_injection_delay;
233
234    // Value right after parent block's slot
235    let slot_iterations = if let Some(change) = &parent_parameters_change
236        && change.slot <= parent_slot.saturating_add(SlotNumber::ONE)
237    {
238        change.slot_iterations
239    } else {
240        parent_slot_iterations
241    };
242
243    let parameters_change = if let Some(change) = parent_parameters_change
244        && change.slot > slot
245    {
246        // Retain previous PoT parameters change if it applies after the block's slot
247        Some(change)
248    } else {
249        let lookback_in_blocks = BlockNumber::from(
250            u64::from(pot_entropy_injection_interval)
251                * u64::from(pot_entropy_injection_lookback_depth.get()),
252        );
253        let last_entropy_injection_block_number = BlockNumber::from(
254            u64::from(block_number) / u64::from(pot_entropy_injection_interval)
255                * u64::from(pot_entropy_injection_interval),
256        );
257        let maybe_entropy_source_block_number =
258            last_entropy_injection_block_number.checked_sub(lookback_in_blocks);
259
260        // Inject entropy every `pot_entropy_injection_interval` blocks
261        if last_entropy_injection_block_number == block_number
262            && let Some(entropy_source_block_number) = maybe_entropy_source_block_number
263            && entropy_source_block_number > BlockNumber::ZERO
264        {
265            let entropy = {
266                let consensus_info = beacon_chain_info
267                    .ancestor_header_consensus_info(entropy_source_block_number, parent_block_root)
268                    .ok_or(DeriveConsensusParametersError::GetAncestorHeader)?;
269
270                consensus_info
271                    .proof_of_time
272                    .derive_pot_entropy(&consensus_info.solution_record_chunk)
273            };
274
275            let target_slot = slot
276                .checked_add(pot_entropy_injection_delay)
277                .unwrap_or(SlotNumber::MAX);
278
279            Some(PotParametersChange {
280                slot: target_slot,
281                // TODO: A mechanism to increase (not decrease!) number of iterations if slots
282                //  are created too frequently on long enough timescale, maybe based on the same
283                //  lookback depth as entropy (would be the cleanest and easiest to explain)
284                slot_iterations,
285                entropy,
286            })
287        } else {
288            None
289        }
290    };
291
292    Ok(PotInfo {
293        slot_iterations,
294        parameters_change,
295    })
296}
297
298/// Chain info for [`shard_membership_entropy_source()`].
299///
300/// Must have access to enough parent blocks.
301pub trait ShardMembershipEntropySourceChainInfo: Send + Sync {
302    /// Get proof of time of the block at `ancestor_block_number` on the chain ending at
303    /// `descendant_block_root`.
304    ///
305    /// If `ancestor_block_number` is the descendant's own number, the descendant's proof of time
306    /// is returned. Returns `None` if `ancestor_block_number` is higher than the descendant's
307    /// number or if either block is not available.
308    fn ancestor_header_proof_of_time(
309        &self,
310        ancestor_block_number: BlockNumber,
311        descendant_block_root: &BlockRoot,
312    ) -> Option<PotOutput>;
313}
314
315impl<T> ShardMembershipEntropySourceChainInfo for T
316where
317    T: ChainInfo<OwnedBeaconChainBlock>,
318{
319    fn ancestor_header_proof_of_time(
320        &self,
321        ancestor_block_number: BlockNumber,
322        descendant_block_root: &BlockRoot,
323    ) -> Option<PotOutput> {
324        let header =
325            ChainInfo::ancestor_header(self, ancestor_block_number, descendant_block_root)?;
326        Some(header.header().consensus_info.proof_of_time)
327    }
328}
329
330/// Error for [`shard_membership_entropy_source`]
331#[derive(Debug, thiserror::Error)]
332pub enum ShardMembershipEntropySourceError {
333    /// Failed to find a beacon chain block with the shard membership entropy source
334    #[error(
335        "Failed to find a beacon chain block {block_number} with the shard membership entropy \
336        source"
337    )]
338    FailedToFindBeaconChainBlock {
339        /// Entropy source block number
340        block_number: BlockNumber,
341    },
342}
343
344/// Find shard membership entropy for a block with a specified block number and parent.
345///
346/// The entropy source block is looked up among the ancestors of `parent_block_root`, on the chain
347/// that the block extends.
348pub fn shard_membership_entropy_source<BCI>(
349    block_number: BlockNumber,
350    parent_block_root: &BlockRoot,
351    shard_rotation_interval: BlockNumber,
352    shard_rotation_delay: BlockNumber,
353    beacon_chain_info: &BCI,
354) -> Result<ShardMembershipEntropy, ShardMembershipEntropySourceError>
355where
356    BCI: ShardMembershipEntropySourceChainInfo,
357{
358    let entropy_source_block_number = BlockNumber::from(
359        u64::from(block_number.saturating_sub(shard_rotation_delay))
360            / u64::from(shard_rotation_interval)
361            * u64::from(shard_rotation_interval),
362    );
363
364    let proof_of_time = beacon_chain_info
365        .ancestor_header_proof_of_time(entropy_source_block_number, parent_block_root)
366        .ok_or(
367            ShardMembershipEntropySourceError::FailedToFindBeaconChainBlock {
368                block_number: entropy_source_block_number,
369            },
370        )?;
371
372    Ok(proof_of_time.shard_membership_entropy())
373}
374
375/// Error for [`derive_super_segment_for_block()`]
376#[derive(Debug, thiserror::Error)]
377pub enum DeriveSuperSegmentForBlockError {
378    /// Genesis beacon chain segment header not found
379    #[error("Genesis beacon chain segment header not found")]
380    GenesisBeaconChainSegmentHeaderNotFound,
381    /// Parent super segment header not found
382    #[error("Parent super segment header not found for block {block_number}")]
383    ParentSuperSegmentHeaderNotFound {
384        /// Block number for which the parent super segment header was not found
385        block_number: BlockNumber,
386    },
387    /// Shard segment roots error
388    #[error("Shard segment roots error: {error}")]
389    ShardSegmentRootsError {
390        /// Low-level error
391        #[from]
392        error: ShardSegmentRootsError,
393    },
394    /// Too many segments
395    #[error("Too many segments: {extra_segment_roots} extra segment roots")]
396    TooManySegments {
397        /// Number of extra segment roots
398        extra_segment_roots: usize,
399    },
400}
401
402/// Chain info for [`derive_super_segment_for_block()`].
403///
404/// Must have access to enough parent blocks.
405pub trait DeriveSuperSegmentForBlockChainInfo: Send + Sync {
406    /// Get genesis segment root of the beacon chain
407    fn get_genesis_segment_root(&self) -> Result<SegmentRoot, DeriveSuperSegmentForBlockError>;
408
409    /// Get segment roots that are expected to be included at specified block number
410    fn segment_roots_for_block(
411        &self,
412        block_number: BlockNumber,
413    ) -> impl ExactSizeIterator<Item = ShardSegmentRoot> + Send + Sync + 'static;
414
415    /// Returns the previous super segment header for the block built with the specified number
416    fn previous_super_segment_header(
417        &self,
418        block_number: BlockNumber,
419    ) -> Option<SuperSegmentHeader>;
420
421    /// Returns intermediate and leaf shard segment roots included in the block at
422    /// `ancestor_block_number` on the chain ending at `descendant_block_root`
423    fn shard_segment_roots(
424        &self,
425        ancestor_block_number: BlockNumber,
426        descendant_block_root: &BlockRoot,
427    ) -> Result<Arc<[ShardSegmentRoot]>, ShardSegmentRootsError>;
428}
429
430impl<T> DeriveSuperSegmentForBlockChainInfo for T
431where
432    T: BeaconChainInfo,
433{
434    #[inline]
435    fn get_genesis_segment_root(&self) -> Result<SegmentRoot, DeriveSuperSegmentForBlockError> {
436        Ok(self
437            .get_segment_header(LocalSegmentIndex::ZERO)
438            .ok_or(DeriveSuperSegmentForBlockError::GenesisBeaconChainSegmentHeaderNotFound)?
439            .root)
440    }
441
442    #[inline]
443    fn segment_roots_for_block(
444        &self,
445        block_number: BlockNumber,
446    ) -> impl ExactSizeIterator<Item = ShardSegmentRoot> + Send + Sync + 'static {
447        self.segment_headers_for_block(block_number)
448            .into_iter()
449            .map(|segment_header| ShardSegmentRoot {
450                shard_index: ShardIndex::BEACON_CHAIN,
451                segment_index: segment_header.index.as_inner(),
452                segment_root: segment_header.root,
453            })
454    }
455
456    #[inline(always)]
457    fn previous_super_segment_header(
458        &self,
459        block_number: BlockNumber,
460    ) -> Option<SuperSegmentHeader> {
461        BeaconChainInfo::previous_super_segment_header(self, block_number)
462    }
463
464    #[inline(always)]
465    fn shard_segment_roots(
466        &self,
467        ancestor_block_number: BlockNumber,
468        descendant_block_root: &BlockRoot,
469    ) -> Result<Arc<[ShardSegmentRoot]>, ShardSegmentRootsError> {
470        BeaconChainInfo::shard_segment_roots(self, ancestor_block_number, descendant_block_root)
471    }
472}
473
474/// Shard segment roots included in a base block that the blocks of its shard confirmation window
475/// didn't postpone due to a shard reorg, in the order of the base block.
476///
477/// `shard_segment_roots` are included in the base block, `window_shard_segment_roots` in each block
478/// of its shard confirmation window.
479fn surviving_shard_segment_roots<'a>(
480    shard_segment_roots: &'a [ShardSegmentRoot],
481    window_shard_segment_roots: &[Arc<[ShardSegmentRoot]>],
482) -> impl Iterator<Item = ShardSegmentRoot> + use<'a> {
483    // A shard segment listed again means a shard reorg, which postpones that segment and every
484    // segment of the shard above it
485    let mut min_listed_again_local_segment_indices =
486        HashMap::<ShardIndex, LocalSegmentIndex>::new();
487    for shard_segment_root in window_shard_segment_roots
488        .iter()
489        .flat_map(|roots| roots.iter())
490    {
491        let min_local_segment_index = min_listed_again_local_segment_indices
492            .entry(shard_segment_root.shard_index)
493            .or_insert(shard_segment_root.segment_index);
494        *min_local_segment_index = (*min_local_segment_index).min(shard_segment_root.segment_index);
495    }
496
497    // Keep anything that was not reorged
498    shard_segment_roots
499        .iter()
500        .filter(move |shard_segment_root| {
501            min_listed_again_local_segment_indices
502                .get(&shard_segment_root.shard_index)
503                .is_none_or(|&min_local_segment_index| {
504                    shard_segment_root.segment_index < min_local_segment_index
505                })
506        })
507        .copied()
508}
509
510/// Derive a super segment for a block with a specified parent block number and root.
511///
512/// For block `n` shard segment roots of blocks
513/// `n - block_confirmation_depth - shard_confirmation_depth ..= n - block_confirmation_depth` on
514/// its chain are read (see [`ConsensusConstants::block_confirmation_depth`] and
515/// [`ConsensusConstants::shard_confirmation_depth`]).
516pub fn derive_super_segment_for_block<BCI>(
517    chain_info: &BCI,
518    parent_block_number: BlockNumber,
519    parent_block_root: &BlockRoot,
520    block_confirmation_depth: BlockNumber,
521    shard_confirmation_depth: BlockNumber,
522) -> Result<Option<SuperSegment>, DeriveSuperSegmentForBlockError>
523where
524    BCI: DeriveSuperSegmentForBlockChainInfo,
525{
526    if parent_block_number == BlockNumber::ZERO {
527        let shard_segment_root = ShardSegmentRootWithPosition {
528            shard_index: ShardIndex::BEACON_CHAIN,
529            segment_position: SegmentPosition::from(0),
530            local_segment_index: LocalSegmentIndex::ZERO,
531            segment_root: chain_info.get_genesis_segment_root()?,
532        };
533
534        let mut super_segment = SuperSegment::new(
535            &SuperSegmentHeader {
536                // Placeholder value will be fixed up later
537                index: SuperSegmentIndex::ZERO.into(),
538                root: SuperSegmentRoot::default(),
539                prev_super_segment_header_hash: Blake3Hash::default(),
540                // Placeholder value will be fixed up later
541                max_segment_index: SegmentIndex::ZERO.into(),
542                target_beacon_chain_block_number: BlockNumber::ZERO.into(),
543                num_segments: 0,
544            },
545            BlockNumber::ONE,
546            StdArc::new([shard_segment_root]),
547        )
548        .expect("Genesis super segment is always valid; qed");
549
550        super_segment.header = SuperSegmentHeader {
551            index: SuperSegmentIndex::ZERO.into(),
552            max_segment_index: SegmentIndex::ZERO.into(),
553            prev_super_segment_header_hash: Blake3Hash::default(),
554            ..super_segment.header
555        };
556
557        return Ok(Some(super_segment));
558    }
559
560    let target_block_number = parent_block_number + BlockNumber::ONE;
561
562    let own_segment_roots = chain_info.segment_roots_for_block(target_block_number);
563
564    let shard_segment_roots_with_window = target_block_number
565        .checked_sub(block_confirmation_depth.saturating_add(shard_confirmation_depth))
566        .map(|base_block_number| {
567            let shard_segment_roots =
568                chain_info.shard_segment_roots(base_block_number, parent_block_root)?;
569            let window_shard_segment_roots = (base_block_number + BlockNumber::ONE..)
570                .take(u64::from(shard_confirmation_depth) as usize)
571                .map(|block_number| chain_info.shard_segment_roots(block_number, parent_block_root))
572                .collect::<Result<Vec<_>, _>>()?;
573
574            Ok::<_, ShardSegmentRootsError>((shard_segment_roots, window_shard_segment_roots))
575        })
576        .transpose()?;
577    let shard_segment_roots = shard_segment_roots_with_window.iter().flat_map(
578        |(shard_segment_roots, window_shard_segment_roots)| {
579            surviving_shard_segment_roots(shard_segment_roots, window_shard_segment_roots)
580        },
581    );
582
583    let segment_roots = own_segment_roots
584        .chain(shard_segment_roots)
585        .zip(0..)
586        .map(
587            |(shard_segment_root, segment_position)| ShardSegmentRootWithPosition {
588                shard_index: shard_segment_root.shard_index,
589                segment_position: SegmentPosition::from(segment_position),
590                local_segment_index: shard_segment_root.segment_index,
591                segment_root: shard_segment_root.segment_root,
592            },
593        )
594        .collect::<StdArc<_>>();
595
596    if segment_roots.is_empty() {
597        return Ok(None);
598    }
599
600    let num_segments = segment_roots.len();
601
602    let previous_super_segment_header = chain_info
603        .previous_super_segment_header(target_block_number)
604        .ok_or(
605            DeriveSuperSegmentForBlockError::ParentSuperSegmentHeaderNotFound {
606                block_number: target_block_number,
607            },
608        )?;
609
610    SuperSegment::new(
611        &previous_super_segment_header,
612        target_block_number,
613        segment_roots,
614    )
615    .ok_or_else(|| {
616        // TODO: While very unlikely, this is hypothetically possible and will need to be
617        //  worked around in the block builder by excluding extra block headers, especially since
618        //  the error will happen much later in the life cycle and it might be too late to revert
619        //  once it is actually hit
620        DeriveSuperSegmentForBlockError::TooManySegments {
621            extra_segment_roots: num_segments - SuperSegmentRoot::MAX_SEGMENTS as usize,
622        }
623    })
624    .map(Some)
625}
626
627/// Error for [`check_shard_segments()`]
628#[derive(Debug, thiserror::Error)]
629pub enum CheckShardSegmentsError {
630    /// Shard segment is already confirmed
631    #[error(
632        "Segment {local_segment_index} of shard {shard_index} is already confirmed, max confirmed \
633        local segment index is {max_confirmed_local_segment_index}"
634    )]
635    ShardSegmentAlreadyConfirmed {
636        /// Shard index
637        shard_index: ShardIndex,
638        /// Local segment index listed in the block
639        local_segment_index: LocalSegmentIndex,
640        /// Highest confirmed local segment index of the shard
641        max_confirmed_local_segment_index: LocalSegmentIndex,
642    },
643    /// Shard segment doesn't continue the shard segments listed before it
644    #[error(
645        "Segment {local_segment_index} of shard {shard_index} doesn't continue the shard segments \
646        listed before it, next local segment index is {next_local_segment_index}"
647    )]
648    ShardSegmentNotContinuous {
649        /// Shard index
650        shard_index: ShardIndex,
651        /// Local segment index listed in the block
652        local_segment_index: LocalSegmentIndex,
653        /// Local segment index after the shard segments listed before it
654        next_local_segment_index: LocalSegmentIndex,
655    },
656    /// Shard segment roots error
657    #[error("Shard segment roots error: {error}")]
658    ShardSegmentRootsError {
659        /// Low-level error
660        #[from]
661        error: ShardSegmentRootsError,
662    },
663}
664
665/// Chain info for [`check_shard_segments()`].
666///
667/// Must have access to enough parent blocks.
668pub trait CheckShardSegmentsChainInfo: DeriveSuperSegmentForBlockChainInfo {
669    /// Returns the highest local segment index of a shard that was included in super segments
670    fn shard_max_local_segment_index(&self, shard_index: ShardIndex) -> Option<LocalSegmentIndex>;
671}
672
673impl<T> CheckShardSegmentsChainInfo for T
674where
675    T: BeaconChainInfo,
676{
677    #[inline(always)]
678    fn shard_max_local_segment_index(&self, shard_index: ShardIndex) -> Option<LocalSegmentIndex> {
679        BeaconChainInfo::shard_max_local_segment_index(self, shard_index)
680    }
681}
682
683/// Check shard segments listed in a block with a specified number and parent.
684///
685/// Shard segments of a base block that survive its shard confirmation window (see
686/// [`ConsensusConstants::shard_confirmation_depth`]) are confirmed and will be included in a super
687/// segment, a shard can't reorg them anymore. Such a segment listed again would be included in
688/// super segments twice. Local segment indices of each shard must also continue its most recent
689/// listing without gaps. The first [`OwnSegments`] of a shard in the block may start below that
690/// to list segments again after a shard reorg, later ones must continue the previous one. Shard
691/// segments of base blocks whose super segments are not persisted yet are read through the
692/// ancestry of `parent_block_root`, see [`ConsensusConstants::block_confirmation_depth`].
693///
694/// `shard_segments` are segments of intermediate and leaf shards listed in the block.
695pub fn check_shard_segments<'a, BCI, Iter>(
696    chain_info: &BCI,
697    block_number: BlockNumber,
698    parent_block_root: &BlockRoot,
699    shard_segments: Iter,
700    block_confirmation_depth: BlockNumber,
701    shard_confirmation_depth: BlockNumber,
702) -> Result<(), CheckShardSegmentsError>
703where
704    BCI: CheckShardSegmentsChainInfo,
705    Iter: IntoIterator<Item = (ShardIndex, OwnSegments<'a>)>,
706{
707    let mut shard_segments = shard_segments.into_iter().peekable();
708
709    // Nothing to check, so no blocks need to be read either
710    if shard_segments.peek().is_none() {
711        return Ok(());
712    }
713
714    // The base block of this block's super segment, the first one whose super segment is not
715    // persisted yet. For early blocks it is block 1 instead, the genesis block lists no shard
716    // segments.
717    let first_unpersisted_base_block_number = block_number
718        .checked_sub(block_confirmation_depth)
719        .and_then(|block_number| block_number.checked_sub(shard_confirmation_depth))
720        .unwrap_or_default()
721        .max(BlockNumber::ONE);
722
723    // Each block is read once, as a base block, as a part of shard confirmation windows of earlier
724    // base blocks and for the most recent listing of each shard
725    let mut shard_segment_roots = Vec::new();
726    let mut last_listed_local_segment_indices = HashMap::<ShardIndex, LocalSegmentIndex>::new();
727    for ancestor_block_number in first_unpersisted_base_block_number..block_number {
728        let block_shard_segment_roots =
729            chain_info.shard_segment_roots(ancestor_block_number, parent_block_root)?;
730
731        // Later entries overwrite earlier ones, the last entry of a shard in a block is its highest
732        for shard_segment_root in block_shard_segment_roots.iter() {
733            last_listed_local_segment_indices.insert(
734                shard_segment_root.shard_index,
735                shard_segment_root.segment_index,
736            );
737        }
738
739        shard_segment_roots.push(block_shard_segment_roots);
740    }
741
742    let mut max_confirmed_local_segment_indices = HashMap::<ShardIndex, LocalSegmentIndex>::new();
743    // Nothing is confirmed by base blocks whose super segments are not persisted yet unless the
744    // last base block whose shard confirmation window ends before this block is above the genesis
745    // block, which lists no shard segments
746    if block_number
747        .checked_sub(shard_confirmation_depth)
748        .and_then(|block_number| block_number.checked_sub(BlockNumber::ONE))
749        .is_some_and(|last_confirmed_base_block_number| {
750            last_confirmed_base_block_number != BlockNumber::ZERO
751        })
752    {
753        let shard_confirmation_window_length = usize::try_from(u64::from(shard_confirmation_depth))
754            .ok()
755            .and_then(|shard_confirmation_depth| shard_confirmation_depth.checked_add(1))
756            .expect("At least `shard_confirmation_depth + 1` blocks were read above; qed");
757
758        for blocks_shard_segment_roots in
759            shard_segment_roots.windows(shard_confirmation_window_length)
760        {
761            let (base_shard_segment_roots, window_shard_segment_roots) = blocks_shard_segment_roots
762                .split_first()
763                .expect("Window length is not zero; qed");
764
765            for shard_segment_root in
766                surviving_shard_segment_roots(base_shard_segment_roots, window_shard_segment_roots)
767            {
768                let max_local_segment_index = max_confirmed_local_segment_indices
769                    .entry(shard_segment_root.shard_index)
770                    .or_insert(shard_segment_root.segment_index);
771                *max_local_segment_index =
772                    (*max_local_segment_index).max(shard_segment_root.segment_index);
773            }
774        }
775    }
776
777    // Local segment index after the previous own segments of each shard in this block
778    let mut next_local_segment_indices = HashMap::<ShardIndex, LocalSegmentIndex>::new();
779    for (shard_index, own_segments) in shard_segments {
780        let first_local_segment_index = own_segments.first_local_segment_index;
781        let local_segment_index_after_own_segments = first_local_segment_index
782            .checked_add(LocalSegmentIndex::from(u64::from(
783                own_segments.num_segment_roots().get(),
784            )))
785            .expect(
786                "`OwnSegments::new()` and parsers check that the index after the last root fits \
787                into `u64`; qed",
788            );
789
790        if let Some(next_local_segment_index) =
791            next_local_segment_indices.insert(shard_index, local_segment_index_after_own_segments)
792        {
793            // Own segments of a shard in the same block are sorted and gap-free, a shard reorg
794            // goes into the next block instead
795            if first_local_segment_index != next_local_segment_index {
796                return Err(CheckShardSegmentsError::ShardSegmentNotContinuous {
797                    shard_index,
798                    local_segment_index: first_local_segment_index,
799                    next_local_segment_index,
800                });
801            }
802
803            // Later own segments continue the first ones, so only those need the checks below
804            continue;
805        }
806
807        let max_persisted_local_segment_index =
808            chain_info.shard_max_local_segment_index(shard_index);
809        // `None` is ordered below any local segment index
810        let max_confirmed_local_segment_index = max_persisted_local_segment_index.max(
811            max_confirmed_local_segment_indices
812                .get(&shard_index)
813                .copied(),
814        );
815
816        if let Some(max_confirmed_local_segment_index) = max_confirmed_local_segment_index
817            && first_local_segment_index <= max_confirmed_local_segment_index
818        {
819            return Err(CheckShardSegmentsError::ShardSegmentAlreadyConfirmed {
820                shard_index,
821                local_segment_index: first_local_segment_index,
822                max_confirmed_local_segment_index,
823            });
824        }
825
826        // If the blocks read above don't list the shard, its most recent listing is older than
827        // every base block whose super segment is not persisted yet and nothing was listed after
828        // it, so all of it survived, and nothing above it was confirmed before
829        let next_local_segment_index = match last_listed_local_segment_indices
830            .get(&shard_index)
831            .copied()
832            .or(max_persisted_local_segment_index)
833        {
834            // On overflow nothing can be skipped, no local segment index is above `u64::MAX`
835            Some(last_listed_local_segment_index) => {
836                last_listed_local_segment_index.checked_add(LocalSegmentIndex::ONE)
837            }
838            // The shard didn't create any segments yet
839            None => Some(LocalSegmentIndex::ZERO),
840        };
841
842        // Segments may be listed again after a shard reorg, but none can be skipped
843        if let Some(next_local_segment_index) = next_local_segment_index
844            && first_local_segment_index > next_local_segment_index
845        {
846            return Err(CheckShardSegmentsError::ShardSegmentNotContinuous {
847                shard_index,
848                local_segment_index: first_local_segment_index,
849                next_local_segment_index,
850            });
851        }
852    }
853
854    Ok(())
855}