Skip to main content

ab_core_primitives/
pieces.rs

1//! Pieces-related data structures.
2
3#![expect(
4    clippy::large_unopt_stack_frames,
5    reason = "Intentional and documented"
6)]
7
8#[cfg(feature = "alloc")]
9mod flat_pieces;
10#[cfg(feature = "alloc")]
11mod piece;
12#[cfg(all(test, feature = "alloc"))]
13mod tests;
14
15#[cfg(feature = "alloc")]
16pub use crate::pieces::flat_pieces::FlatPieces;
17#[cfg(feature = "alloc")]
18pub use crate::pieces::piece::Piece;
19use crate::sectors::SBucket;
20use crate::segments::{
21    LocalSegmentIndex, RecordedHistorySegment, SegmentIndex, SegmentRoot, SuperSegmentRoot,
22};
23use crate::shard::ShardIndex;
24#[cfg(feature = "serde")]
25use ::serde::{Deserialize, Deserializer, Serialize, Serializer};
26use ab_io_type::trivial_type::{AnyBitPattern, TrivialType};
27use ab_io_type::unaligned::Unaligned;
28use ab_merkle_tree::blake3::BalancedMerkleTree;
29#[cfg(feature = "alloc")]
30use alloc::boxed::Box;
31#[cfg(feature = "alloc")]
32use alloc::vec::Vec;
33use array_reshape::{Flatten, Unflatten};
34use blake3::OUT_LEN;
35use core::array::TryFromSliceError;
36use core::hash::Hash;
37use core::iter::Step;
38use core::ops::{Index, IndexMut};
39use core::{fmt, mem};
40use derive_more::{
41    Add, AddAssign, AsMut, AsRef, Deref, DerefMut, Display, Div, DivAssign, From, Into, Mul,
42    MulAssign, Sub, SubAssign,
43};
44#[cfg(feature = "scale-codec")]
45use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
46#[cfg(feature = "serde")]
47use serde_big_array::BigArray;
48use transparent_wrapper::TransparentWrapper;
49
50/// Piece index
51#[derive(
52    Debug,
53    Display,
54    Default,
55    Copy,
56    Clone,
57    Ord,
58    PartialOrd,
59    Eq,
60    PartialEq,
61    Hash,
62    Add,
63    AddAssign,
64    Sub,
65    SubAssign,
66    Mul,
67    MulAssign,
68    Div,
69    DivAssign,
70)]
71#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
72#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
73#[repr(C)]
74pub struct PieceIndex(u64);
75
76impl Step for PieceIndex {
77    #[inline]
78    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
79        u64::steps_between(&start.0, &end.0)
80    }
81
82    #[inline]
83    fn forward_checked(start: Self, count: usize) -> Option<Self> {
84        u64::forward_checked(start.0, count).map(Self)
85    }
86
87    #[inline(always)]
88    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
89        let (n, overflowing) = u64::forward_overflowing(start.0, count);
90        (Self(n), overflowing)
91    }
92
93    #[inline]
94    fn backward_checked(start: Self, count: usize) -> Option<Self> {
95        u64::backward_checked(start.0, count).map(Self)
96    }
97
98    #[inline(always)]
99    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
100        let (n, overflowing) = u64::backward_overflowing(start.0, count);
101        (Self(n), overflowing)
102    }
103}
104
105const impl From<u64> for PieceIndex {
106    #[inline(always)]
107    fn from(value: u64) -> Self {
108        Self(value)
109    }
110}
111
112const impl From<PieceIndex> for u64 {
113    #[inline(always)]
114    fn from(value: PieceIndex) -> Self {
115        value.0
116    }
117}
118
119impl PieceIndex {
120    /// Size in bytes.
121    pub const SIZE: usize = size_of::<u64>();
122    /// Piece index 0.
123    pub const ZERO: PieceIndex = PieceIndex(0);
124    /// Piece index 1.
125    pub const ONE: PieceIndex = PieceIndex(1);
126
127    /// Create a piece index from bytes.
128    #[inline]
129    pub const fn from_bytes(bytes: [u8; Self::SIZE]) -> Self {
130        Self(u64::from_le_bytes(bytes))
131    }
132
133    /// Convert a piece index to bytes.
134    #[inline]
135    pub const fn to_bytes(self) -> [u8; Self::SIZE] {
136        self.0.to_le_bytes()
137    }
138
139    /// Segment index piece index corresponds to
140    #[inline]
141    pub const fn segment_index(&self) -> SegmentIndex {
142        SegmentIndex::from(self.0 / RecordedHistorySegment::NUM_PIECES as u64)
143    }
144
145    /// Position of a piece in a segment
146    #[inline]
147    pub fn position(&self) -> PiecePosition {
148        PiecePosition::from((self.0 % RecordedHistorySegment::NUM_PIECES as u64) as u8)
149    }
150}
151
152const {
153    // Assert that `u8` represents `PiecePosition` perfectly
154    assert!(RecordedHistorySegment::NUM_PIECES == usize::from(u8::MAX) + 1);
155}
156
157/// Piece position in a segment
158#[derive(
159    Debug,
160    Display,
161    Default,
162    Copy,
163    Clone,
164    Ord,
165    PartialOrd,
166    Eq,
167    PartialEq,
168    Hash,
169    From,
170    Into,
171    TrivialType,
172)]
173#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
174#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
175#[repr(C)]
176pub struct PiecePosition(u8);
177
178impl Step for PiecePosition {
179    #[inline]
180    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
181        u8::steps_between(&start.0, &end.0)
182    }
183
184    #[inline]
185    fn forward_checked(start: Self, count: usize) -> Option<Self> {
186        u8::forward_checked(start.0, count).map(Self)
187    }
188
189    #[inline(always)]
190    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
191        let (n, overflowing) = u8::forward_overflowing(start.0, count);
192        (Self(n), overflowing)
193    }
194
195    #[inline]
196    fn backward_checked(start: Self, count: usize) -> Option<Self> {
197        u8::backward_checked(start.0, count).map(Self)
198    }
199
200    #[inline(always)]
201    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
202        let (n, overflowing) = u8::backward_overflowing(start.0, count);
203        (Self(n), overflowing)
204    }
205}
206
207impl From<PiecePosition> for u16 {
208    #[inline]
209    fn from(original: PiecePosition) -> Self {
210        Self::from(original.0)
211    }
212}
213
214impl From<PiecePosition> for u32 {
215    #[inline]
216    fn from(original: PiecePosition) -> Self {
217        Self::from(original.0)
218    }
219}
220
221impl From<PiecePosition> for u64 {
222    #[inline]
223    fn from(original: PiecePosition) -> Self {
224        Self::from(original.0)
225    }
226}
227
228impl From<PiecePosition> for usize {
229    #[inline]
230    fn from(original: PiecePosition) -> Self {
231        usize::from(original.0)
232    }
233}
234
235/// Piece offset in a sector
236#[derive(
237    Debug,
238    Display,
239    Default,
240    Copy,
241    Clone,
242    Ord,
243    PartialOrd,
244    Eq,
245    PartialEq,
246    Hash,
247    From,
248    Into,
249    Add,
250    AddAssign,
251    Sub,
252    SubAssign,
253    Mul,
254    MulAssign,
255    Div,
256    DivAssign,
257    TrivialType,
258)]
259#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
260#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
261#[repr(C)]
262pub struct PieceOffset(u16);
263
264impl Step for PieceOffset {
265    #[inline]
266    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
267        u16::steps_between(&start.0, &end.0)
268    }
269
270    #[inline]
271    fn forward_checked(start: Self, count: usize) -> Option<Self> {
272        u16::forward_checked(start.0, count).map(Self)
273    }
274
275    #[inline(always)]
276    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
277        let (n, overflowing) = u16::forward_overflowing(start.0, count);
278        (Self(n), overflowing)
279    }
280
281    #[inline]
282    fn backward_checked(start: Self, count: usize) -> Option<Self> {
283        u16::backward_checked(start.0, count).map(Self)
284    }
285
286    #[inline(always)]
287    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
288        let (n, overflowing) = u16::backward_overflowing(start.0, count);
289        (Self(n), overflowing)
290    }
291}
292
293impl From<PieceOffset> for u32 {
294    #[inline]
295    fn from(original: PieceOffset) -> Self {
296        Self::from(original.0)
297    }
298}
299
300impl From<PieceOffset> for u64 {
301    #[inline]
302    fn from(original: PieceOffset) -> Self {
303        Self::from(original.0)
304    }
305}
306
307impl From<PieceOffset> for usize {
308    #[inline]
309    fn from(original: PieceOffset) -> Self {
310        usize::from(original.0)
311    }
312}
313
314impl PieceOffset {
315    /// Piece index 0
316    pub const ZERO: Self = Self(0);
317    /// Piece index 1
318    pub const ONE: Self = Self(1);
319    /// Size in bytes
320    pub const SIZE: usize = size_of::<u16>();
321
322    /// Convert piece offset to bytes
323    #[inline]
324    pub const fn to_bytes(self) -> [u8; Self::SIZE] {
325        self.0.to_le_bytes()
326    }
327}
328
329/// Chunk contained in a record
330#[derive(
331    Default,
332    Copy,
333    Clone,
334    Eq,
335    PartialEq,
336    Ord,
337    PartialOrd,
338    Hash,
339    From,
340    Into,
341    AsRef,
342    AsMut,
343    Deref,
344    DerefMut,
345    TrivialType,
346    TransparentWrapper,
347)]
348#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
349#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
350#[cfg_attr(feature = "serde", serde(transparent))]
351#[repr(C)]
352pub struct RecordChunk([u8; RecordChunk::SIZE]);
353
354impl fmt::Debug for RecordChunk {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        for byte in self.0 {
357            write!(f, "{byte:02x}")?;
358        }
359        Ok(())
360    }
361}
362
363impl RecordChunk {
364    /// Size of the chunk in bytes
365    pub const SIZE: usize = 32;
366}
367
368/// Record contained within a piece.
369///
370/// NOTE: This is a stack-allocated data structure and can cause stack overflow!
371#[derive(Copy, Clone, Eq, PartialEq, Deref, DerefMut, TrivialType, TransparentWrapper)]
372#[repr(C)]
373pub struct Record([[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS]);
374
375impl fmt::Debug for Record {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        for byte in self.0.as_flattened() {
378            write!(f, "{byte:02x}")?;
379        }
380        Ok(())
381    }
382}
383
384impl AsRef<[u8]> for Record {
385    #[inline]
386    fn as_ref(&self) -> &[u8] {
387        self.0.as_flattened()
388    }
389}
390
391impl AsRef<[u8; Record::SIZE]> for Record {
392    #[inline(always)]
393    fn as_ref(&self) -> &[u8; Record::SIZE] {
394        self.as_bytes()
395    }
396}
397
398impl AsMut<[u8; Record::SIZE]> for Record {
399    #[inline(always)]
400    fn as_mut(&mut self) -> &mut [u8; Record::SIZE] {
401        self.as_bytes_mut()
402    }
403}
404
405impl AsMut<[u8]> for Record {
406    #[inline]
407    fn as_mut(&mut self) -> &mut [u8] {
408        self.0.as_flattened_mut()
409    }
410}
411
412impl<'a> From<&'a Record> for &'a [[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS] {
413    #[inline]
414    fn from(value: &'a Record) -> Self {
415        value.peel_ref()
416    }
417}
418
419impl<'a> From<&'a [[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS]> for &'a Record {
420    #[inline]
421    fn from(value: &'a [[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS]) -> Self {
422        Record::wrap_ref(value)
423    }
424}
425
426impl<'a> From<&'a mut Record> for &'a mut [[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS] {
427    #[inline]
428    fn from(value: &'a mut Record) -> Self {
429        value.peel_mut()
430    }
431}
432
433impl<'a> From<&'a mut [[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS]> for &'a mut Record {
434    #[inline]
435    fn from(value: &'a mut [[u8; RecordChunk::SIZE]; Record::NUM_CHUNKS]) -> Self {
436        Record::wrap_mut(value)
437    }
438}
439
440impl Record {
441    /// Number of chunks within one record.
442    pub const NUM_CHUNKS: usize = 2usize.pow(15);
443    /// Number of s-buckets contained within one sector record.
444    ///
445    /// Essentially we chunk records and erasure code them.
446    pub const NUM_S_BUCKETS: usize = Record::NUM_CHUNKS
447        * RecordedHistorySegment::ERASURE_CODING_RATE.1
448        / RecordedHistorySegment::ERASURE_CODING_RATE.0;
449    /// Size of a segment record, it is guaranteed to be a multiple of [`RecordChunk::SIZE`]
450    pub const SIZE: usize = RecordChunk::SIZE * Record::NUM_CHUNKS;
451
452    /// Create boxed value without hitting stack overflow
453    #[inline]
454    #[cfg(feature = "alloc")]
455    pub fn new_boxed() -> Box<Self> {
456        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
457        // SAFETY: Data structure filled with zeroes is a valid invariant
458        unsafe { Box::new_zeroed().assume_init() }
459    }
460
461    /// Create vector filled with zeroed records without hitting stack overflow
462    #[inline]
463    #[cfg(feature = "alloc")]
464    pub fn new_zero_vec(length: usize) -> Vec<Self> {
465        // TODO: Should have been just `vec![Self::default(); length]`, but
466        //  https://github.com/rust-lang/rust/issues/53827
467        // SAFETY: Data structure filled with zeroes is a valid invariant
468        unsafe { Box::<[Self]>::new_zeroed_slice(length).assume_init() }.into_vec()
469    }
470
471    /// Derive source chunks root on-demand
472    #[inline(always)]
473    pub fn source_chunks_root(&self) -> RecordChunksRoot {
474        RecordChunksRoot(BalancedMerkleTree::compute_root_only(self))
475    }
476}
477
478/// Source record together with parity chunks produced from it by erasure coding, which together
479/// are all s-buckets of a record.
480///
481/// NOTE: This is a stack-allocated data structure and can cause stack overflow!
482#[derive(Debug, Copy, Clone, Eq, PartialEq)]
483#[repr(C)]
484pub struct ExtendedRecord {
485    /// Source chunks
486    pub source: Record,
487    /// Parity chunks
488    pub parity: Record,
489}
490
491const {
492    // Conversions to and from `[Record; 2]` rely on this
493    assert!(size_of::<ExtendedRecord>() == size_of::<[Record; 2]>());
494    assert!(align_of::<ExtendedRecord>() == align_of::<[Record; 2]>());
495    // The last s-bucket is the last chunk of an extended record, which indexing relies on
496    assert!(usize::from(u16::from(SBucket::MAX)) == Record::NUM_S_BUCKETS - 1);
497}
498
499impl Index<SBucket> for ExtendedRecord {
500    type Output = RecordChunk;
501
502    #[inline(always)]
503    fn index(&self, index: SBucket) -> &Self::Output {
504        self.as_s_buckets()
505            .get(usize::from(index))
506            .expect("S-bucket is at most `SBucket::MAX`, which is within range, checked above; qed")
507    }
508}
509
510impl IndexMut<SBucket> for ExtendedRecord {
511    #[inline(always)]
512    fn index_mut(&mut self, index: SBucket) -> &mut Self::Output {
513        self.as_s_buckets_mut()
514            .get_mut(usize::from(index))
515            .expect("S-bucket is at most `SBucket::MAX`, which is within range, checked above; qed")
516    }
517}
518
519impl ExtendedRecord {
520    /// Create boxed value without hitting stack overflow
521    #[inline]
522    #[cfg(feature = "alloc")]
523    pub fn new_boxed() -> Box<Self> {
524        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
525        // SAFETY: Data structure filled with zeroes is a valid invariant
526        unsafe { Box::new_zeroed().assume_init() }
527    }
528
529    /// Source and parity records as an array
530    #[inline(always)]
531    pub const fn as_records(&self) -> &[Record; 2] {
532        // SAFETY: `#[repr(C)]` struct with two fields of the same type, which has the same size and
533        // alignment as an array of two elements of that type (checked above), hence no padding
534        unsafe { mem::transmute(self) }
535    }
536
537    /// Source and parity records as a mutable array
538    #[inline(always)]
539    pub const fn as_records_mut(&mut self) -> &mut [Record; 2] {
540        // SAFETY: `#[repr(C)]` struct with two fields of the same type, which has the same size and
541        // alignment as an array of two elements of that type (checked above), hence no padding
542        unsafe { mem::transmute(self) }
543    }
544
545    /// Chunks of all s-buckets, source chunks followed by parity chunks
546    #[inline(always)]
547    pub fn as_s_buckets(&self) -> &[RecordChunk; Record::NUM_S_BUCKETS] {
548        <[RecordChunk; _]>::wrap_ref(self.as_records().peel_ref().flatten_ref())
549    }
550
551    /// Mutable chunks of all s-buckets, source chunks followed by parity chunks
552    #[inline(always)]
553    pub fn as_s_buckets_mut(&mut self) -> &mut [RecordChunk; Record::NUM_S_BUCKETS] {
554        <[RecordChunk; _]>::wrap_mut(self.as_records_mut().peel_mut().flatten_mut())
555    }
556}
557
558/// Root of the record contained within a piece.
559///
560/// This is a Merkle Tree root of the roots of source and parity record chunks.
561#[derive(
562    Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType, TransparentWrapper,
563)]
564#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
565#[repr(C)]
566pub struct RecordRoot([u8; RecordRoot::SIZE]);
567
568impl fmt::Debug for RecordRoot {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        for byte in self.0 {
571            write!(f, "{byte:02x}")?;
572        }
573        Ok(())
574    }
575}
576
577#[cfg(feature = "serde")]
578#[derive(Serialize, Deserialize)]
579#[serde(transparent)]
580struct RecordRootBinary(#[serde(with = "BigArray")] [u8; RecordRoot::SIZE]);
581
582#[cfg(feature = "serde")]
583#[derive(Serialize, Deserialize)]
584#[serde(transparent)]
585struct RecordRootHex(#[serde(with = "hex")] [u8; RecordRoot::SIZE]);
586
587#[cfg(feature = "serde")]
588impl Serialize for RecordRoot {
589    #[inline]
590    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
591    where
592        S: Serializer,
593    {
594        if serializer.is_human_readable() {
595            RecordRootHex(self.0).serialize(serializer)
596        } else {
597            RecordRootBinary(self.0).serialize(serializer)
598        }
599    }
600}
601
602#[cfg(feature = "serde")]
603impl<'de> Deserialize<'de> for RecordRoot {
604    #[inline]
605    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
606    where
607        D: Deserializer<'de>,
608    {
609        Ok(Self(if deserializer.is_human_readable() {
610            RecordRootHex::deserialize(deserializer)?.0
611        } else {
612            RecordRootBinary::deserialize(deserializer)?.0
613        }))
614    }
615}
616
617impl Default for RecordRoot {
618    #[inline]
619    fn default() -> Self {
620        Self([0; _])
621    }
622}
623
624impl TryFrom<&[u8]> for RecordRoot {
625    type Error = TryFromSliceError;
626
627    #[inline]
628    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
629        <[u8; Self::SIZE]>::try_from(slice).map(Self)
630    }
631}
632
633impl AsRef<[u8]> for RecordRoot {
634    #[inline]
635    fn as_ref(&self) -> &[u8] {
636        &self.0
637    }
638}
639
640impl AsMut<[u8]> for RecordRoot {
641    #[inline]
642    fn as_mut(&mut self) -> &mut [u8] {
643        &mut self.0
644    }
645}
646
647impl<'a> From<&'a RecordRoot> for &'a [u8; RecordRoot::SIZE] {
648    #[inline]
649    fn from(value: &'a RecordRoot) -> Self {
650        value.peel_ref()
651    }
652}
653
654impl<'a> From<&'a [u8; RecordRoot::SIZE]> for &'a RecordRoot {
655    #[inline]
656    fn from(value: &'a [u8; RecordRoot::SIZE]) -> Self {
657        RecordRoot::wrap_ref(value)
658    }
659}
660
661impl<'a> From<&'a mut RecordRoot> for &'a mut [u8; RecordRoot::SIZE] {
662    #[inline]
663    fn from(value: &'a mut RecordRoot) -> Self {
664        value.peel_mut()
665    }
666}
667
668impl<'a> From<&'a mut [u8; RecordRoot::SIZE]> for &'a mut RecordRoot {
669    #[inline]
670    fn from(value: &'a mut [u8; RecordRoot::SIZE]) -> Self {
671        RecordRoot::wrap_mut(value)
672    }
673}
674
675impl RecordRoot {
676    /// Size of record root in bytes.
677    pub const SIZE: usize = 32;
678
679    /// Validate record root hash produced by the archiver
680    pub fn is_valid(
681        &self,
682        segment_root: &SegmentRoot,
683        record_proof: &RecordProof,
684        position: PiecePosition,
685    ) -> bool {
686        BalancedMerkleTree::<{ RecordedHistorySegment::NUM_PIECES }>::verify(
687            segment_root,
688            record_proof,
689            usize::from(position),
690            self.0,
691        )
692    }
693}
694
695/// Root of source or parity record chunks
696#[derive(
697    Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType, TransparentWrapper,
698)]
699#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
700#[repr(C)]
701pub struct RecordChunksRoot([u8; RecordChunksRoot::SIZE]);
702
703impl fmt::Debug for RecordChunksRoot {
704    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705        for byte in self.0 {
706            write!(f, "{byte:02x}")?;
707        }
708        Ok(())
709    }
710}
711
712#[cfg(feature = "serde")]
713#[derive(Serialize, Deserialize)]
714#[serde(transparent)]
715struct RecordChunksRootBinary(#[serde(with = "BigArray")] [u8; RecordChunksRoot::SIZE]);
716
717#[cfg(feature = "serde")]
718#[derive(Serialize, Deserialize)]
719#[serde(transparent)]
720struct RecordChunksRootHex(#[serde(with = "hex")] [u8; RecordChunksRoot::SIZE]);
721
722#[cfg(feature = "serde")]
723impl Serialize for RecordChunksRoot {
724    #[inline]
725    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
726    where
727        S: Serializer,
728    {
729        if serializer.is_human_readable() {
730            RecordChunksRootHex(self.0).serialize(serializer)
731        } else {
732            RecordChunksRootBinary(self.0).serialize(serializer)
733        }
734    }
735}
736
737#[cfg(feature = "serde")]
738impl<'de> Deserialize<'de> for RecordChunksRoot {
739    #[inline]
740    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
741    where
742        D: Deserializer<'de>,
743    {
744        Ok(Self(if deserializer.is_human_readable() {
745            RecordChunksRootHex::deserialize(deserializer)?.0
746        } else {
747            RecordChunksRootBinary::deserialize(deserializer)?.0
748        }))
749    }
750}
751
752impl Default for RecordChunksRoot {
753    #[inline]
754    fn default() -> Self {
755        Self([0; _])
756    }
757}
758
759impl TryFrom<&[u8]> for RecordChunksRoot {
760    type Error = TryFromSliceError;
761
762    #[inline]
763    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
764        <[u8; Self::SIZE]>::try_from(slice).map(Self)
765    }
766}
767
768impl AsRef<[u8]> for RecordChunksRoot {
769    #[inline]
770    fn as_ref(&self) -> &[u8] {
771        &self.0
772    }
773}
774
775impl AsMut<[u8]> for RecordChunksRoot {
776    #[inline]
777    fn as_mut(&mut self) -> &mut [u8] {
778        &mut self.0
779    }
780}
781
782impl<'a> From<&'a RecordChunksRoot> for &'a [u8; RecordChunksRoot::SIZE] {
783    #[inline]
784    fn from(value: &'a RecordChunksRoot) -> Self {
785        value.peel_ref()
786    }
787}
788
789impl<'a> From<&'a [u8; RecordChunksRoot::SIZE]> for &'a RecordChunksRoot {
790    #[inline]
791    fn from(value: &'a [u8; RecordChunksRoot::SIZE]) -> Self {
792        RecordChunksRoot::wrap_ref(value)
793    }
794}
795
796impl<'a> From<&'a mut RecordChunksRoot> for &'a mut [u8; RecordChunksRoot::SIZE] {
797    #[inline]
798    fn from(value: &'a mut RecordChunksRoot) -> Self {
799        value.peel_mut()
800    }
801}
802
803impl<'a> From<&'a mut [u8; RecordChunksRoot::SIZE]> for &'a mut RecordChunksRoot {
804    #[inline]
805    fn from(value: &'a mut [u8; RecordChunksRoot::SIZE]) -> Self {
806        RecordChunksRoot::wrap_mut(value)
807    }
808}
809
810impl RecordChunksRoot {
811    /// Size of record chunks root in bytes.
812    pub const SIZE: usize = 32;
813}
814
815/// Proof that the record (root) belongs to a segment
816#[derive(
817    Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType, TransparentWrapper,
818)]
819#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
820#[repr(C)]
821pub struct RecordProof([[u8; OUT_LEN]; RecordProof::NUM_HASHES]);
822
823impl fmt::Debug for RecordProof {
824    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
825        write!(f, "[")?;
826        for hash in self.0 {
827            for byte in hash {
828                write!(f, "{byte:02x}")?;
829            }
830            write!(f, ", ")?;
831        }
832        write!(f, "]")?;
833        Ok(())
834    }
835}
836
837#[cfg(feature = "serde")]
838#[derive(Serialize, Deserialize)]
839#[serde(transparent)]
840struct RecordProofBinary([[u8; OUT_LEN]; RecordProof::NUM_HASHES]);
841
842#[cfg(feature = "serde")]
843#[derive(Serialize, Deserialize, TransparentWrapper)]
844#[serde(transparent)]
845#[repr(transparent)]
846struct RecordProofHexHash(#[serde(with = "hex")] [u8; OUT_LEN]);
847
848#[cfg(feature = "serde")]
849#[derive(Serialize, Deserialize)]
850#[serde(transparent)]
851struct RecordProofHex([RecordProofHexHash; RecordProof::NUM_HASHES]);
852
853#[cfg(feature = "serde")]
854impl Serialize for RecordProof {
855    #[inline]
856    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
857    where
858        S: Serializer,
859    {
860        if serializer.is_human_readable() {
861            RecordProofHex(<[RecordProofHexHash; Self::NUM_HASHES]>::wrap(self.0))
862                .serialize(serializer)
863        } else {
864            RecordProofBinary(self.0).serialize(serializer)
865        }
866    }
867}
868
869#[cfg(feature = "serde")]
870impl<'de> Deserialize<'de> for RecordProof {
871    #[inline]
872    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
873    where
874        D: Deserializer<'de>,
875    {
876        Ok(Self(if deserializer.is_human_readable() {
877            RecordProofHex::deserialize(deserializer)?.0.peel()
878        } else {
879            RecordProofBinary::deserialize(deserializer)?.0
880        }))
881    }
882}
883
884impl Default for RecordProof {
885    #[inline]
886    fn default() -> Self {
887        Self([[0; OUT_LEN]; _])
888    }
889}
890
891impl AsRef<[u8]> for RecordProof {
892    #[inline]
893    fn as_ref(&self) -> &[u8] {
894        self.0.as_flattened()
895    }
896}
897
898impl AsMut<[u8]> for RecordProof {
899    #[inline]
900    fn as_mut(&mut self) -> &mut [u8] {
901        self.0.as_flattened_mut()
902    }
903}
904
905impl<'a> From<&'a RecordProof> for &'a [u8; RecordProof::SIZE] {
906    #[inline]
907    fn from(value: &'a RecordProof) -> Self {
908        value.peel_ref().flatten_ref()
909    }
910}
911
912impl<'a> From<&'a [u8; RecordProof::SIZE]> for &'a RecordProof {
913    #[inline]
914    fn from(value: &'a [u8; RecordProof::SIZE]) -> Self {
915        RecordProof::wrap_ref(value.unflatten_ref())
916    }
917}
918
919impl<'a> From<&'a mut RecordProof> for &'a mut [u8; RecordProof::SIZE] {
920    #[inline]
921    fn from(value: &'a mut RecordProof) -> Self {
922        value.peel_mut().flatten_mut()
923    }
924}
925
926impl<'a> From<&'a mut [u8; RecordProof::SIZE]> for &'a mut RecordProof {
927    #[inline]
928    fn from(value: &'a mut [u8; RecordProof::SIZE]) -> Self {
929        RecordProof::wrap_mut(value.unflatten_mut())
930    }
931}
932
933impl RecordProof {
934    /// Size of record proof in bytes
935    pub const SIZE: usize = OUT_LEN * Self::NUM_HASHES;
936    const NUM_HASHES: usize = RecordedHistorySegment::NUM_PIECES.ilog2() as usize;
937}
938
939/// Proof that the segment belongs to a super segment
940#[derive(
941    Copy, Clone, Eq, PartialEq, Hash, Deref, DerefMut, From, Into, TrivialType, TransparentWrapper,
942)]
943#[cfg_attr(feature = "scale-codec", derive(Encode, Decode, MaxEncodedLen))]
944#[repr(C)]
945pub struct SegmentProof([[u8; OUT_LEN]; SegmentProof::NUM_HASHES]);
946
947impl fmt::Debug for SegmentProof {
948    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949        write!(f, "[")?;
950        for hash in self.0 {
951            for byte in hash {
952                write!(f, "{byte:02x}")?;
953            }
954            write!(f, ", ")?;
955        }
956        write!(f, "]")?;
957        Ok(())
958    }
959}
960
961#[cfg(feature = "serde")]
962#[derive(Serialize, Deserialize)]
963#[serde(transparent)]
964struct SegmentProofBinary([[u8; OUT_LEN]; SegmentProof::NUM_HASHES]);
965
966#[cfg(feature = "serde")]
967#[derive(Serialize, Deserialize, TransparentWrapper)]
968#[serde(transparent)]
969#[repr(transparent)]
970struct SegmentProofHexHash(#[serde(with = "hex")] [u8; OUT_LEN]);
971
972#[cfg(feature = "serde")]
973#[derive(Serialize, Deserialize)]
974#[serde(transparent)]
975struct SegmentProofHex([SegmentProofHexHash; SegmentProof::NUM_HASHES]);
976
977#[cfg(feature = "serde")]
978impl Serialize for SegmentProof {
979    #[inline]
980    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
981    where
982        S: Serializer,
983    {
984        if serializer.is_human_readable() {
985            SegmentProofHex(<[SegmentProofHexHash; Self::NUM_HASHES]>::wrap(self.0))
986                .serialize(serializer)
987        } else {
988            SegmentProofBinary(self.0).serialize(serializer)
989        }
990    }
991}
992
993#[cfg(feature = "serde")]
994impl<'de> Deserialize<'de> for SegmentProof {
995    #[inline]
996    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
997    where
998        D: Deserializer<'de>,
999    {
1000        Ok(Self(if deserializer.is_human_readable() {
1001            SegmentProofHex::deserialize(deserializer)?.0.peel()
1002        } else {
1003            SegmentProofBinary::deserialize(deserializer)?.0
1004        }))
1005    }
1006}
1007
1008impl Default for SegmentProof {
1009    #[inline]
1010    fn default() -> Self {
1011        Self([[0; OUT_LEN]; _])
1012    }
1013}
1014
1015impl AsRef<[u8]> for SegmentProof {
1016    #[inline]
1017    fn as_ref(&self) -> &[u8] {
1018        self.0.as_flattened()
1019    }
1020}
1021
1022impl AsMut<[u8]> for SegmentProof {
1023    #[inline]
1024    fn as_mut(&mut self) -> &mut [u8] {
1025        self.0.as_flattened_mut()
1026    }
1027}
1028
1029impl<'a> From<&'a SegmentProof> for &'a [u8; SegmentProof::SIZE] {
1030    #[inline]
1031    fn from(value: &'a SegmentProof) -> Self {
1032        value.peel_ref().flatten_ref()
1033    }
1034}
1035
1036impl<'a> From<&'a [u8; SegmentProof::SIZE]> for &'a SegmentProof {
1037    #[inline]
1038    fn from(value: &'a [u8; SegmentProof::SIZE]) -> Self {
1039        SegmentProof::wrap_ref(value.unflatten_ref())
1040    }
1041}
1042
1043impl<'a> From<&'a mut SegmentProof> for &'a mut [u8; SegmentProof::SIZE] {
1044    #[inline]
1045    fn from(value: &'a mut SegmentProof) -> Self {
1046        value.peel_mut().flatten_mut()
1047    }
1048}
1049
1050impl<'a> From<&'a mut [u8; SegmentProof::SIZE]> for &'a mut SegmentProof {
1051    #[inline]
1052    fn from(value: &'a mut [u8; SegmentProof::SIZE]) -> Self {
1053        SegmentProof::wrap_mut(value.unflatten_mut())
1054    }
1055}
1056
1057impl SegmentProof {
1058    /// Size of segment proof in bytes
1059    pub const SIZE: usize = OUT_LEN * Self::NUM_HASHES;
1060    const NUM_HASHES: usize = SuperSegmentRoot::MAX_SEGMENTS.next_power_of_two().ilog2() as usize;
1061}
1062
1063/// Header for a piece of archival history.
1064///
1065/// Primarily contains information needed for piece verification.
1066#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, TrivialType)]
1067#[cfg_attr(feature = "scale-codec", derive(Encode, Decode))]
1068#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1069#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1070#[repr(C)]
1071pub struct PieceHeader {
1072    /// Shard index
1073    pub shard_index: Unaligned<ShardIndex>,
1074    /// Local segment index
1075    pub local_segment_index: Unaligned<LocalSegmentIndex>,
1076    /// Segment root
1077    pub segment_root: SegmentRoot,
1078    /// Segment proof
1079    pub segment_proof: SegmentProof,
1080    /// Root of parity record chunks.
1081    ///
1082    /// Technically redundant, but helps to avoid repeating erasure coding during verification.
1083    pub parity_chunks_root: RecordChunksRoot,
1084    /// Proof that the record (root) belongs to a segment
1085    pub record_proof: RecordProof,
1086}
1087
1088const {
1089    // Must have minimal alignment for various conversions to/from bytes
1090    assert!(align_of::<PieceHeader>() == 1);
1091}
1092
1093/// A piece of archival history.
1094///
1095/// This version is allocated on the stack, for a heap-allocated piece that can be moved around
1096/// efficiently, see `Piece`.
1097///
1098/// Internally, a piece contains a record, supplementary record chunk root, and a proof proving this
1099/// piece belongs to can be used to verify that a piece belongs to the actual archival history of
1100/// the blockchain.
1101#[derive(Debug, Copy, Clone, Eq, PartialEq, TrivialType)]
1102#[repr(C)]
1103pub struct InnerPiece {
1104    /// Piece header
1105    pub header: PieceHeader,
1106    /// Record contained within a piece
1107    pub record: Record,
1108}
1109
1110const {
1111    const fn assert_any_bit_pattern<T>()
1112    where
1113        T: AnyBitPattern,
1114    {
1115    }
1116
1117    // Must have minimal alignment for various conversions to/from bytes
1118    assert!(align_of::<InnerPiece>() == 1);
1119    // No padding, which `Piece::from_parts()` relies on
1120    assert!(size_of::<InnerPiece>() == size_of::<PieceHeader>() + size_of::<Record>());
1121    // Any bit pattern must be a valid value for various conversions from bytes
1122    assert_any_bit_pattern::<InnerPiece>();
1123}
1124
1125impl InnerPiece {
1126    /// Size of a piece (in bytes)
1127    pub const SIZE: usize = size_of::<Self>();
1128
1129    /// Create boxed value without hitting stack overflow
1130    #[inline]
1131    #[cfg(feature = "alloc")]
1132    pub fn new_boxed() -> Box<Self> {
1133        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
1134        // SAFETY: Data structure filled with zeroes is a valid invariant
1135        unsafe { Box::<Self>::new_zeroed().assume_init() }
1136    }
1137
1138    /// Check whether the piece is the piece at `piece_index` of the global history.
1139    ///
1140    /// `super_segment_root`, `num_segments` and `max_segment_index` are those of the super segment
1141    /// that contains the segment of `piece_index`, which determines the position of the segment in
1142    /// the super segment. Returns `false` if the super segment doesn't contain it.
1143    pub fn is_valid(
1144        &self,
1145        super_segment_root: &SuperSegmentRoot,
1146        num_segments: u32,
1147        max_segment_index: SegmentIndex,
1148        piece_index: PieceIndex,
1149    ) -> bool {
1150        let Some(segment_position) = piece_index
1151            .segment_index()
1152            .position_in_super_segment(max_segment_index, num_segments)
1153        else {
1154            return false;
1155        };
1156
1157        if !self.header.segment_root.is_valid(
1158            self.header.shard_index.as_inner(),
1159            self.header.local_segment_index.as_inner(),
1160            segment_position,
1161            &self.header.segment_proof,
1162            num_segments,
1163            super_segment_root,
1164        ) {
1165            return false;
1166        }
1167        self.record_root().is_valid(
1168            &self.header.segment_root,
1169            &self.header.record_proof,
1170            piece_index.position(),
1171        )
1172    }
1173
1174    /// Root of the record contained within a piece.
1175    ///
1176    /// It is re-derived on every call of this function.
1177    #[inline]
1178    pub fn record_root(&self) -> RecordRoot {
1179        let record_merkle_tree_root = BalancedMerkleTree::compute_root_only(&[
1180            *self.record.source_chunks_root(),
1181            *self.header.parity_chunks_root,
1182        ]);
1183
1184        RecordRoot::from(record_merkle_tree_root)
1185    }
1186}