Skip to main content

ab_core_primitives/
segments.rs

1//! Segments-related data structures
2
3#![expect(
4    clippy::large_unopt_stack_frames,
5    reason = "Intentional and documented"
6)]
7
8#[cfg(feature = "alloc")]
9mod archival_history_segment;
10#[cfg(all(test, feature = "alloc"))]
11mod tests;
12
13use crate::block::BlockNumber;
14use crate::hashes::Blake3Hash;
15use crate::pieces::{PieceIndex, Record, SegmentProof};
16#[cfg(feature = "alloc")]
17pub use crate::segments::archival_history_segment::ArchivedHistorySegment;
18use crate::shard::ShardIndex;
19use crate::trees::SuperSegmentMerkleTree;
20use ab_blake3::{single_block_hash, single_chunk_hash};
21use ab_io_type::trivial_type::TrivialType;
22use ab_io_type::unaligned::Unaligned;
23#[cfg(feature = "alloc")]
24use alloc::boxed::Box;
25#[cfg(feature = "alloc")]
26use alloc::sync::Arc as StdArc;
27use blake3::{CHUNK_LEN, OUT_LEN};
28use core::fmt;
29use core::iter::Step;
30#[cfg(feature = "alloc")]
31use core::mem::MaybeUninit;
32use core::num::{NonZeroU32, NonZeroU64};
33use derive_more::{
34    Add, AddAssign, Deref, DerefMut, Display, Div, DivAssign, From, Into, Mul, MulAssign, Sub,
35    SubAssign,
36};
37#[cfg(feature = "scale-codec")]
38use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
39#[cfg(feature = "serde")]
40use serde::{Deserialize, Deserializer, Serialize, Serializer};
41#[cfg(feature = "serde")]
42use serde_big_array::BigArray;
43use transparent_wrapper::TransparentWrapper;
44
45/// Super segment index
46#[derive(
47    Debug,
48    Display,
49    Default,
50    Copy,
51    Clone,
52    Ord,
53    PartialOrd,
54    Eq,
55    PartialEq,
56    Hash,
57    Add,
58    AddAssign,
59    Sub,
60    SubAssign,
61    Mul,
62    MulAssign,
63    Div,
64    DivAssign,
65    TrivialType,
66)]
67#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
68#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
69#[repr(C)]
70pub struct SuperSegmentIndex(u64);
71
72impl Step for SuperSegmentIndex {
73    #[inline]
74    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
75        u64::steps_between(&start.0, &end.0)
76    }
77
78    #[inline]
79    fn forward_checked(start: Self, count: usize) -> Option<Self> {
80        u64::forward_checked(start.0, count).map(Self)
81    }
82
83    #[inline(always)]
84    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
85        let (n, overflowing) = u64::forward_overflowing(start.0, count);
86        (Self(n), overflowing)
87    }
88
89    #[inline]
90    fn backward_checked(start: Self, count: usize) -> Option<Self> {
91        u64::backward_checked(start.0, count).map(Self)
92    }
93
94    #[inline(always)]
95    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
96        let (n, overflowing) = u64::backward_overflowing(start.0, count);
97        (Self(n), overflowing)
98    }
99}
100
101const impl From<u64> for SuperSegmentIndex {
102    #[inline(always)]
103    fn from(value: u64) -> Self {
104        Self(value)
105    }
106}
107
108const impl From<SuperSegmentIndex> for u64 {
109    #[inline(always)]
110    fn from(value: SuperSegmentIndex) -> Self {
111        value.0
112    }
113}
114
115impl SuperSegmentIndex {
116    /// Super segment index 0
117    pub const ZERO: Self = Self(0);
118    /// Super segment index 1
119    pub const ONE: Self = Self(1);
120
121    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if underflow occurred
122    #[inline]
123    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
124        self.0.checked_sub(rhs.0).map(Self)
125    }
126
127    /// Saturating integer subtraction. Computes `self - rhs`, returning zero if underflow
128    /// occurred
129    #[inline]
130    pub const fn saturating_sub(self, rhs: Self) -> Self {
131        Self(self.0.saturating_sub(rhs.0))
132    }
133}
134
135/// Super segment root contained within a beacon chain block
136#[derive(Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType)]
137#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
138#[repr(C)]
139pub struct SuperSegmentRoot([u8; SuperSegmentRoot::SIZE]);
140
141impl fmt::Debug for SuperSegmentRoot {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        for byte in self.0 {
144            write!(f, "{byte:02x}")?;
145        }
146        Ok(())
147    }
148}
149
150const impl Default for SuperSegmentRoot {
151    #[inline]
152    fn default() -> Self {
153        Self([0; _])
154    }
155}
156
157#[cfg(feature = "serde")]
158#[derive(Serialize, Deserialize)]
159#[serde(transparent)]
160struct SuperSegmentRootBinary(#[serde(with = "BigArray")] [u8; SuperSegmentRoot::SIZE]);
161
162#[cfg(feature = "serde")]
163#[derive(Serialize, Deserialize)]
164#[serde(transparent)]
165struct SuperSegmentRootHex(#[serde(with = "hex")] [u8; SuperSegmentRoot::SIZE]);
166
167#[cfg(feature = "serde")]
168impl Serialize for SuperSegmentRoot {
169    #[inline]
170    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
171    where
172        S: Serializer,
173    {
174        if serializer.is_human_readable() {
175            SuperSegmentRootHex(self.0).serialize(serializer)
176        } else {
177            SuperSegmentRootBinary(self.0).serialize(serializer)
178        }
179    }
180}
181
182#[cfg(feature = "serde")]
183impl<'de> Deserialize<'de> for SuperSegmentRoot {
184    #[inline]
185    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
186    where
187        D: Deserializer<'de>,
188    {
189        Ok(Self(if deserializer.is_human_readable() {
190            SuperSegmentRootHex::deserialize(deserializer)?.0
191        } else {
192            SuperSegmentRootBinary::deserialize(deserializer)?.0
193        }))
194    }
195}
196
197impl AsRef<[u8]> for SuperSegmentRoot {
198    #[inline]
199    fn as_ref(&self) -> &[u8] {
200        &self.0
201    }
202}
203
204impl AsMut<[u8]> for SuperSegmentRoot {
205    #[inline]
206    fn as_mut(&mut self) -> &mut [u8] {
207        &mut self.0
208    }
209}
210
211impl SuperSegmentRoot {
212    /// Size in bytes
213    pub const SIZE: usize = 32;
214    /// The maximum number of segments in a super segment's Merkle Tree.
215    ///
216    /// `-1` to minimize the number of bits needed to represent it (exactly 20).
217    pub const MAX_SEGMENTS: u32 = 2u32.pow(20) - 1;
218}
219
220/// Segment position in a super segment
221#[derive(
222    Debug,
223    Display,
224    Default,
225    Copy,
226    Clone,
227    Ord,
228    PartialOrd,
229    Eq,
230    PartialEq,
231    Hash,
232    From,
233    Into,
234    TrivialType,
235)]
236#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
237#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
238#[repr(C)]
239pub struct SegmentPosition(u32);
240
241impl From<SegmentPosition> for u64 {
242    #[inline]
243    fn from(original: SegmentPosition) -> Self {
244        Self::from(original.0)
245    }
246}
247
248impl SegmentPosition {
249    /// Zero position
250    pub const ZERO: Self = Self(0);
251}
252
253/// Shard segment root with position
254#[derive(Debug, Clone, Copy, TrivialType)]
255#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
256#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
257#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
258#[repr(C)]
259pub struct ShardSegmentRootWithPosition {
260    /// Shard index
261    pub shard_index: ShardIndex,
262    /// Position of the segment in the super segment
263    pub segment_position: SegmentPosition,
264    /// Local segment index
265    pub local_segment_index: LocalSegmentIndex,
266    /// Segment root
267    pub segment_root: SegmentRoot,
268}
269
270impl ShardSegmentRootWithPosition {
271    /// Hash for super segment creation
272    #[inline(always)]
273    pub fn hash(&self) -> [u8; OUT_LEN] {
274        single_block_hash(self.as_bytes()).expect("Less than a single block worth of bytes; qed")
275    }
276}
277
278/// Super segment header
279#[derive(Debug, Clone, Copy, Eq, PartialEq, TrivialType)]
280#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
281#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
282#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
283#[repr(C)]
284pub struct SuperSegmentHeader {
285    /// Super segment index
286    pub index: Unaligned<SuperSegmentIndex>,
287    /// Super segment root
288    pub root: SuperSegmentRoot,
289    /// Hash of the previous super segment header
290    pub prev_super_segment_header_hash: Blake3Hash,
291    /// Max index of the segment in the super segment
292    pub max_segment_index: Unaligned<SegmentIndex>,
293    /// Target beacon chain block number for the super segment
294    pub target_beacon_chain_block_number: Unaligned<BlockNumber>,
295    // TODO: New type?
296    /// Number of segments in the super segment
297    pub num_segments: u32,
298}
299
300impl SuperSegmentHeader {
301    /// Position of a segment in the super segment.
302    ///
303    /// Returns `None` if the segment is not in the super segment, see
304    /// [`SegmentIndex::position_in_super_segment()`].
305    #[inline(always)]
306    pub const fn segment_position(&self, segment_index: SegmentIndex) -> Option<SegmentPosition> {
307        segment_index
308            .position_in_super_segment(self.max_segment_index.as_inner(), self.num_segments)
309    }
310}
311
312/// Super segment
313#[cfg(feature = "alloc")]
314#[derive(Debug, Clone)]
315// TODO: Implement SCALE serialization/deserialization manually (if necessary at all)
316// #[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
317#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
318#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
319pub struct SuperSegment {
320    /// Super segment root
321    pub header: SuperSegmentHeader,
322    /// Segment roots that are included in the super segment
323    pub segment_roots: StdArc<[ShardSegmentRootWithPosition]>,
324}
325
326#[cfg(feature = "alloc")]
327impl SuperSegment {
328    /// Create a new instance and derive super segment root.
329    ///
330    /// Returns `None` if the list of segment roots is empty or there are too many of them.
331    pub fn new(
332        previous_header: &SuperSegmentHeader,
333        target_beacon_chain_block_number: BlockNumber,
334        segment_roots: StdArc<[ShardSegmentRootWithPosition]>,
335    ) -> Option<Self> {
336        let num_segments = u32::try_from(segment_roots.len()).ok()?;
337        let max_segment_index = SegmentIndex::from(
338            u64::from(previous_header.max_segment_index.as_inner()) + u64::from(num_segments),
339        );
340
341        let maybe_super_segment_root = SuperSegmentMerkleTree::compute_root_only::<
342            { u64::from(SuperSegmentRoot::MAX_SEGMENTS) },
343            _,
344            _,
345        >(
346            // TODO: Hash multiple entries at once with SIMD once
347            //  https://github.com/BLAKE3-team/BLAKE3/issues/478 is resolved
348            segment_roots.iter().map(ShardSegmentRootWithPosition::hash),
349        )?;
350
351        Some(Self {
352            header: SuperSegmentHeader {
353                index: (previous_header.index.as_inner() + SuperSegmentIndex::ONE).into(),
354                root: SuperSegmentRoot::from(maybe_super_segment_root),
355                prev_super_segment_header_hash: Blake3Hash::from(
356                    single_chunk_hash(previous_header.as_bytes())
357                        .expect("Less than a single chunk worth of bytes; qed"),
358                ),
359                max_segment_index: max_segment_index.into(),
360                target_beacon_chain_block_number: target_beacon_chain_block_number.into(),
361                num_segments,
362            },
363            segment_roots,
364        })
365    }
366
367    /// Produce a proof for a segment in the super segment at a given position
368    pub fn proof_for_segment(&self, segment_position: SegmentPosition) -> Option<SegmentProof> {
369        let mut segment_proof = [MaybeUninit::uninit(); _];
370        let (_root, proof_hashes) = SuperSegmentMerkleTree::compute_root_and_proof_in::<
371            { u64::from(SuperSegmentRoot::MAX_SEGMENTS) },
372            _,
373            _,
374        >(
375            // TODO: Hash multiple entries at once with SIMD once
376            //  https://github.com/BLAKE3-team/BLAKE3/issues/478 is resolved
377            self.segment_roots
378                .iter()
379                .map(ShardSegmentRootWithPosition::hash),
380            u32::from(segment_position) as usize,
381            &mut segment_proof,
382        )?;
383        let proof_length = proof_hashes.len();
384
385        // Unused hashes must be zeroed
386        segment_proof
387            .get_mut(proof_length..)
388            .expect("Proof is a prefix of the provided memory; qed")
389            .write_filled([0; OUT_LEN]);
390        // SAFETY: The first `proof_length` hashes were initialized by proof generation above, the
391        // rest were just zeroed
392        let segment_proof = unsafe { MaybeUninit::from(segment_proof).assume_init() };
393
394        Some(SegmentProof::from(segment_proof))
395    }
396}
397
398/// Local segment index of a shard
399#[derive(
400    Debug,
401    Display,
402    Default,
403    Copy,
404    Clone,
405    Ord,
406    PartialOrd,
407    Eq,
408    PartialEq,
409    Hash,
410    Add,
411    AddAssign,
412    Sub,
413    SubAssign,
414    Mul,
415    MulAssign,
416    Div,
417    DivAssign,
418    TrivialType,
419)]
420#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
421#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
422#[repr(C)]
423pub struct LocalSegmentIndex(u64);
424
425impl Step for LocalSegmentIndex {
426    #[inline]
427    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
428        u64::steps_between(&start.0, &end.0)
429    }
430
431    #[inline]
432    fn forward_checked(start: Self, count: usize) -> Option<Self> {
433        u64::forward_checked(start.0, count).map(Self)
434    }
435
436    #[inline(always)]
437    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
438        let (n, overflowing) = u64::forward_overflowing(start.0, count);
439        (Self(n), overflowing)
440    }
441
442    #[inline]
443    fn backward_checked(start: Self, count: usize) -> Option<Self> {
444        u64::backward_checked(start.0, count).map(Self)
445    }
446
447    #[inline(always)]
448    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
449        let (n, overflowing) = u64::backward_overflowing(start.0, count);
450        (Self(n), overflowing)
451    }
452}
453
454const impl From<u64> for LocalSegmentIndex {
455    #[inline(always)]
456    fn from(value: u64) -> Self {
457        Self(value)
458    }
459}
460
461const impl From<LocalSegmentIndex> for u64 {
462    #[inline(always)]
463    fn from(value: LocalSegmentIndex) -> Self {
464        value.0
465    }
466}
467
468impl LocalSegmentIndex {
469    /// Local segment index 0
470    pub const ZERO: Self = Self(0);
471    /// Local segment index 1
472    pub const ONE: Self = Self(1);
473
474    /// Checked addition, returns `None` on overflow
475    #[inline(always)]
476    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
477        if let Some(n) = self.0.checked_add(rhs.0) {
478            Some(Self(n))
479        } else {
480            None
481        }
482    }
483
484    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if underflow occurred
485    #[inline]
486    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
487        self.0.checked_sub(rhs.0).map(Self)
488    }
489
490    /// Saturating integer subtraction. Computes `self - rhs`, returning zero if underflow
491    /// occurred
492    #[inline]
493    pub const fn saturating_sub(self, rhs: Self) -> Self {
494        Self(self.0.saturating_sub(rhs.0))
495    }
496}
497
498/// Segment index
499#[derive(
500    Debug,
501    Display,
502    Default,
503    Copy,
504    Clone,
505    Ord,
506    PartialOrd,
507    Eq,
508    PartialEq,
509    Hash,
510    Add,
511    AddAssign,
512    Sub,
513    SubAssign,
514    Mul,
515    MulAssign,
516    Div,
517    DivAssign,
518    TrivialType,
519)]
520#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
521#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
522#[repr(C)]
523pub struct SegmentIndex(u64);
524
525impl Step for SegmentIndex {
526    #[inline]
527    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
528        u64::steps_between(&start.0, &end.0)
529    }
530
531    #[inline]
532    fn forward_checked(start: Self, count: usize) -> Option<Self> {
533        u64::forward_checked(start.0, count).map(Self)
534    }
535
536    #[inline(always)]
537    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
538        let (n, overflowing) = u64::forward_overflowing(start.0, count);
539        (Self(n), overflowing)
540    }
541
542    #[inline]
543    fn backward_checked(start: Self, count: usize) -> Option<Self> {
544        u64::backward_checked(start.0, count).map(Self)
545    }
546
547    #[inline(always)]
548    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
549        let (n, overflowing) = u64::backward_overflowing(start.0, count);
550        (Self(n), overflowing)
551    }
552}
553
554const impl From<u64> for SegmentIndex {
555    #[inline(always)]
556    fn from(value: u64) -> Self {
557        Self(value)
558    }
559}
560
561const impl From<SegmentIndex> for u64 {
562    #[inline(always)]
563    fn from(value: SegmentIndex) -> Self {
564        value.0
565    }
566}
567
568impl SegmentIndex {
569    /// Segment index 0
570    pub const ZERO: Self = Self(0);
571    /// Segment index 1
572    pub const ONE: Self = Self(1);
573
574    /// Get the first piece index in this segment
575    #[inline]
576    pub const fn first_piece_index(&self) -> PieceIndex {
577        PieceIndex::from(self.0 * RecordedHistorySegment::NUM_PIECES as u64)
578    }
579
580    /// Get the last piece index in this segment
581    #[inline]
582    pub const fn last_piece_index(&self) -> PieceIndex {
583        PieceIndex::from((self.0 + 1) * RecordedHistorySegment::NUM_PIECES as u64 - 1)
584    }
585
586    /// List of piece indexes that belong to this segment
587    #[inline]
588    pub fn segment_piece_indexes(&self) -> [PieceIndex; RecordedHistorySegment::NUM_PIECES] {
589        let mut piece_indices = [PieceIndex::ZERO; RecordedHistorySegment::NUM_PIECES];
590        (self.first_piece_index()..=self.last_piece_index())
591            .zip(&mut piece_indices)
592            .for_each(|(input, output)| {
593                *output = input;
594            });
595
596        piece_indices
597    }
598
599    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if underflow occurred
600    #[inline]
601    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
602        self.0.checked_sub(rhs.0).map(Self)
603    }
604
605    /// Saturating integer subtraction. Computes `self - rhs`, returning zero if underflow
606    /// occurred
607    #[inline]
608    pub const fn saturating_sub(self, rhs: Self) -> Self {
609        Self(self.0.saturating_sub(rhs.0))
610    }
611
612    /// Position of this segment in a super segment with `num_segments` segments and
613    /// `max_segment_index`.
614    ///
615    /// A super segment contains segments with consecutive indices ending with `max_segment_index`,
616    /// in the order of their positions. Returns `None` if this segment is not in the super segment.
617    #[inline]
618    pub const fn position_in_super_segment(
619        self,
620        max_segment_index: Self,
621        num_segments: u32,
622    ) -> Option<SegmentPosition> {
623        let segments_after = max_segment_index.0.checked_sub(self.0)?;
624        let Ok(segments_after) = u32::try_from(segments_after) else {
625            return None;
626        };
627        let position = num_segments.checked_sub(segments_after)?.checked_sub(1)?;
628
629        Some(SegmentPosition(position))
630    }
631}
632
633/// Segment root contained within a segment
634#[derive(
635    Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType, TransparentWrapper,
636)]
637#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
638#[repr(C)]
639pub struct SegmentRoot([u8; SegmentRoot::SIZE]);
640
641impl fmt::Debug for SegmentRoot {
642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643        for byte in self.0 {
644            write!(f, "{byte:02x}")?;
645        }
646        Ok(())
647    }
648}
649
650#[cfg(feature = "serde")]
651#[derive(Serialize, Deserialize)]
652#[serde(transparent)]
653struct SegmentRootBinary(#[serde(with = "BigArray")] [u8; SegmentRoot::SIZE]);
654
655#[cfg(feature = "serde")]
656#[derive(Serialize, Deserialize)]
657#[serde(transparent)]
658struct SegmentRootHex(#[serde(with = "hex")] [u8; SegmentRoot::SIZE]);
659
660#[cfg(feature = "serde")]
661impl Serialize for SegmentRoot {
662    #[inline]
663    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
664    where
665        S: Serializer,
666    {
667        if serializer.is_human_readable() {
668            SegmentRootHex(self.0).serialize(serializer)
669        } else {
670            SegmentRootBinary(self.0).serialize(serializer)
671        }
672    }
673}
674
675#[cfg(feature = "serde")]
676impl<'de> Deserialize<'de> for SegmentRoot {
677    #[inline]
678    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
679    where
680        D: Deserializer<'de>,
681    {
682        Ok(Self(if deserializer.is_human_readable() {
683            SegmentRootHex::deserialize(deserializer)?.0
684        } else {
685            SegmentRootBinary::deserialize(deserializer)?.0
686        }))
687    }
688}
689
690impl Default for SegmentRoot {
691    #[inline(always)]
692    fn default() -> Self {
693        Self([0; _])
694    }
695}
696
697impl AsRef<[u8]> for SegmentRoot {
698    #[inline(always)]
699    fn as_ref(&self) -> &[u8] {
700        &self.0
701    }
702}
703
704impl AsMut<[u8]> for SegmentRoot {
705    #[inline(always)]
706    fn as_mut(&mut self) -> &mut [u8] {
707        &mut self.0
708    }
709}
710
711impl SegmentRoot {
712    /// Size in bytes
713    pub const SIZE: usize = 32;
714
715    /// Check whether a segment root is a part of the super segment
716    pub fn is_valid(
717        &self,
718        shard_index: ShardIndex,
719        local_segment_index: LocalSegmentIndex,
720        segment_position: SegmentPosition,
721        segment_proof: &SegmentProof,
722        num_segments: u32,
723        super_segment_root: &SuperSegmentRoot,
724    ) -> bool {
725        let shard_segment_root = ShardSegmentRootWithPosition {
726            shard_index,
727            segment_position,
728            local_segment_index,
729            segment_root: *self,
730        };
731        // The proof is fixed size and contains zero padding elements, which must be skipped for
732        // verification purposes
733        let (segment_proof, padding) = segment_proof
734            .split_once(|hash| hash == &[0; _])
735            .unwrap_or((segment_proof.as_slice(), &[]));
736        // Padding must only contain zeroes, so that a proof has a single encoding
737        if padding.iter().any(|hash| hash != &[0; _]) {
738            return false;
739        }
740        SuperSegmentMerkleTree::verify(
741            super_segment_root,
742            segment_proof,
743            u64::from(segment_position),
744            shard_segment_root.hash(),
745            u64::from(num_segments),
746        )
747    }
748}
749
750/// Size of blockchain history in segments
751#[derive(
752    Debug,
753    Display,
754    Copy,
755    Clone,
756    Ord,
757    PartialOrd,
758    Eq,
759    PartialEq,
760    Hash,
761    From,
762    Into,
763    Deref,
764    DerefMut,
765    TrivialType,
766)]
767#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
768#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
769#[repr(C)]
770// Storing `SegmentIndex` to make all invariants valid
771pub struct HistorySize(SegmentIndex);
772
773impl HistorySize {
774    /// History size of one
775    pub const ONE: Self = Self(SegmentIndex::ZERO);
776
777    /// Create a new instance
778    #[inline(always)]
779    pub const fn new(value: NonZeroU64) -> Self {
780        Self(SegmentIndex::from(value.get() - 1))
781    }
782
783    /// Get internal representation
784    pub const fn as_segment_index(&self) -> SegmentIndex {
785        self.0
786    }
787
788    /// Get internal representation
789    pub const fn as_non_zero_u64(&self) -> NonZeroU64 {
790        NonZeroU64::new(u64::from(self.0).saturating_add(1)).expect("Not zero; qed")
791    }
792
793    /// Size of blockchain history in pieces
794    #[inline(always)]
795    pub const fn in_pieces(&self) -> NonZeroU64 {
796        NonZeroU64::new(
797            u64::from(self.0)
798                .saturating_add(1)
799                .saturating_mul(RecordedHistorySegment::NUM_PIECES as u64),
800        )
801        .expect("Not zero; qed")
802    }
803
804    /// Segment index that corresponds to this history size
805    #[inline(always)]
806    pub fn segment_index(&self) -> SegmentIndex {
807        self.0
808    }
809
810    /// History size at which expiration check for a sector happens.
811    ///
812    /// Returns `None` on overflow.
813    #[inline(always)]
814    pub fn sector_expiration_check(&self, min_sector_lifetime: Self) -> Option<Self> {
815        self.as_non_zero_u64()
816            .checked_add(min_sector_lifetime.as_non_zero_u64().get())
817            .map(Self::new)
818    }
819}
820
821/// Progress of an archived block.
822#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, TrivialType)]
823#[cfg_attr(feature = "scale-codec", derive(Encode, Decode))]
824#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
825#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
826#[repr(C)]
827pub struct ArchivedBlockProgress {
828    /// Number of partially archived bytes of a block, `0` for a full block
829    bytes: u32,
830}
831
832impl Default for ArchivedBlockProgress {
833    /// We assume a block can always fit into the segment initially, but it is definitely possible
834    /// to be transitioned into the partial state after some overflow checking.
835    #[inline(always)]
836    fn default() -> Self {
837        Self::new_complete()
838    }
839}
840
841impl ArchivedBlockProgress {
842    /// Block is archived fully
843    #[inline(always)]
844    pub const fn new_complete() -> Self {
845        Self { bytes: 0 }
846    }
847
848    /// Block is partially archived with the provided number of bytes
849    #[inline(always)]
850    pub const fn new_partial(new_partial: NonZeroU32) -> Self {
851        Self {
852            bytes: new_partial.get(),
853        }
854    }
855
856    /// Return the number of partially archived bytes if the progress is not complete
857    #[inline(always)]
858    pub const fn partial(&self) -> Option<NonZeroU32> {
859        NonZeroU32::new(self.bytes)
860    }
861}
862
863/// Last archived block
864#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, TrivialType)]
865#[cfg_attr(feature = "scale-codec", derive(Encode, Decode))]
866#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
867#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
868#[repr(C)]
869pub struct LastArchivedBlock {
870    /// Block number
871    pub number: Unaligned<BlockNumber>,
872    /// Progress of an archived block
873    pub archived_progress: ArchivedBlockProgress,
874}
875
876impl LastArchivedBlock {
877    /// Returns the number of partially archived bytes for a block
878    #[inline(always)]
879    pub fn partial_archived(&self) -> Option<NonZeroU32> {
880        self.archived_progress.partial()
881    }
882
883    /// Sets the number of partially archived bytes if block progress was archived partially
884    #[inline(always)]
885    pub fn set_partial_archived(&mut self, new_partial: NonZeroU32) {
886        self.archived_progress = ArchivedBlockProgress::new_partial(new_partial);
887    }
888
889    /// Indicate the last archived block was archived fully
890    #[inline(always)]
891    pub fn set_complete(&mut self) {
892        self.archived_progress = ArchivedBlockProgress::new_complete();
893    }
894
895    /// Get the block number (unwrap `Unaligned`)
896    pub const fn number(&self) -> BlockNumber {
897        self.number.as_inner()
898    }
899}
900
901/// Segment header for a specific segment of a shard
902#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, TrivialType)]
903#[cfg_attr(feature = "scale-codec", derive(Encode, Decode))]
904#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
905#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
906#[repr(C)]
907pub struct SegmentHeader {
908    /// Local segment index
909    pub index: Unaligned<LocalSegmentIndex>,
910    /// Root of roots of all records in a segment.
911    pub root: SegmentRoot,
912    /// Hash of the segment header of the previous segment
913    pub prev_segment_header_hash: Blake3Hash,
914    /// Last archived block
915    pub last_archived_block: LastArchivedBlock,
916}
917
918impl SegmentHeader {
919    /// Hash of the whole segment header
920    #[inline(always)]
921    pub fn hash(&self) -> Blake3Hash {
922        const {
923            assert!(size_of::<Self>() <= CHUNK_LEN);
924        }
925        Blake3Hash::new(
926            single_chunk_hash(self.as_bytes())
927                .expect("Less than a single chunk worth of bytes; qed"),
928        )
929    }
930}
931
932/// Recorded history segment before archiving is applied.
933///
934/// NOTE: This is a stack-allocated data structure and can cause stack overflow!
935#[derive(Copy, Clone, Eq, PartialEq, Deref, DerefMut)]
936#[repr(C)]
937pub struct RecordedHistorySegment([Record; Self::NUM_RAW_RECORDS]);
938
939impl fmt::Debug for RecordedHistorySegment {
940    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941        f.debug_struct("RecordedHistorySegment")
942            .finish_non_exhaustive()
943    }
944}
945
946impl AsRef<[u8]> for RecordedHistorySegment {
947    #[inline]
948    fn as_ref(&self) -> &[u8] {
949        self.0.peel_ref().as_flattened().as_flattened()
950    }
951}
952
953impl AsMut<[u8]> for RecordedHistorySegment {
954    #[inline]
955    fn as_mut(&mut self) -> &mut [u8] {
956        self.0.peel_mut().as_flattened_mut().as_flattened_mut()
957    }
958}
959
960impl RecordedHistorySegment {
961    /// Number of raw records in one segment of recorded history
962    pub const NUM_RAW_RECORDS: usize = 128;
963    /// Erasure coding rate for records during the archiving process
964    pub const ERASURE_CODING_RATE: (usize, usize) = (1, 2);
965    /// Number of pieces in one segment of archived history (taking erasure coding rate into
966    /// account)
967    pub const NUM_PIECES: usize =
968        Self::NUM_RAW_RECORDS * Self::ERASURE_CODING_RATE.1 / Self::ERASURE_CODING_RATE.0;
969    /// Size of recorded history segment in bytes.
970    ///
971    /// It includes half of the records (just source records) that will later be erasure coded and
972    /// together with corresponding roots and proofs will result in
973    /// [`Self::NUM_PIECES`] `Piece`s of archival history.
974    pub const SIZE: usize = Record::SIZE * Self::NUM_RAW_RECORDS;
975
976    /// Create boxed value without hitting stack overflow
977    #[inline]
978    #[cfg(feature = "alloc")]
979    pub fn new_boxed() -> Box<Self> {
980        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
981        // SAFETY: Data structure filled with zeroes is a valid invariant
982        unsafe { Box::<Self>::new_zeroed().assume_init() }
983    }
984}