Skip to main content

subspace_core_primitives/
segments.rs

1//! Segments-related data structures.
2
3#[cfg(not(feature = "std"))]
4extern crate alloc;
5
6use crate::BlockNumber;
7use crate::hashes::{Blake3Hash, blake3_hash};
8use crate::pieces::{FlatPieces, Piece, PieceIndex, RawRecord};
9#[cfg(not(feature = "std"))]
10use alloc::boxed::Box;
11use core::array::TryFromSliceError;
12use core::fmt;
13use core::iter::Step;
14use core::num::NonZeroU64;
15use derive_more::{
16    Add, AddAssign, Deref, DerefMut, Display, Div, DivAssign, From, Into, Mul, MulAssign, Sub,
17    SubAssign,
18};
19use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
20use scale_info::TypeInfo;
21#[cfg(feature = "serde")]
22use serde::{Deserialize, Serialize};
23#[cfg(feature = "serde")]
24use serde::{Deserializer, Serializer};
25#[cfg(feature = "serde")]
26use serde_big_array::BigArray;
27
28/// Segment index type.
29#[derive(
30    Debug,
31    Display,
32    Default,
33    Copy,
34    Clone,
35    Ord,
36    PartialOrd,
37    Eq,
38    PartialEq,
39    Hash,
40    From,
41    Into,
42    Encode,
43    Decode,
44    Add,
45    AddAssign,
46    Sub,
47    SubAssign,
48    Mul,
49    MulAssign,
50    Div,
51    DivAssign,
52    TypeInfo,
53    MaxEncodedLen,
54    DecodeWithMemTracking,
55)]
56#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
57#[repr(transparent)]
58pub struct SegmentIndex(u64);
59
60impl Step for SegmentIndex {
61    #[inline]
62    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
63        u64::steps_between(&start.0, &end.0)
64    }
65
66    #[inline]
67    fn forward_checked(start: Self, count: usize) -> Option<Self> {
68        u64::forward_checked(start.0, count).map(Self)
69    }
70
71    #[inline]
72    fn forward_overflowing(start: Self, count: usize) -> (Self, bool) {
73        let (n, overflowing) = u64::forward_overflowing(start.0, count);
74        (Self(n), overflowing)
75    }
76
77    #[inline]
78    fn backward_checked(start: Self, count: usize) -> Option<Self> {
79        u64::backward_checked(start.0, count).map(Self)
80    }
81
82    #[inline]
83    fn backward_overflowing(start: Self, count: usize) -> (Self, bool) {
84        let (n, overflowing) = u64::backward_overflowing(start.0, count);
85        (Self(n), overflowing)
86    }
87}
88
89impl SegmentIndex {
90    /// Segment index 0.
91    pub const ZERO: SegmentIndex = SegmentIndex(0);
92    /// Segment index 1.
93    pub const ONE: SegmentIndex = SegmentIndex(1);
94
95    /// Create new instance
96    #[inline]
97    pub const fn new(n: u64) -> Self {
98        Self(n)
99    }
100
101    /// Get the first piece index in this segment.
102    #[inline]
103    pub const fn first_piece_index(&self) -> PieceIndex {
104        PieceIndex::new(self.0 * ArchivedHistorySegment::NUM_PIECES as u64)
105    }
106
107    /// Get the last piece index in this segment.
108    #[inline]
109    pub const fn last_piece_index(&self) -> PieceIndex {
110        PieceIndex::new((self.0 + 1) * ArchivedHistorySegment::NUM_PIECES as u64 - 1)
111    }
112
113    /// List of piece indexes that belong to this segment.
114    pub fn segment_piece_indexes(&self) -> [PieceIndex; ArchivedHistorySegment::NUM_PIECES] {
115        let mut piece_indices = [PieceIndex::ZERO; ArchivedHistorySegment::NUM_PIECES];
116        (self.first_piece_index()..=self.last_piece_index())
117            .zip(&mut piece_indices)
118            .for_each(|(input, output)| {
119                *output = input;
120            });
121
122        piece_indices
123    }
124
125    /// List of piece indexes that belong to this segment with source pieces first.
126    pub fn segment_piece_indexes_source_first(
127        &self,
128    ) -> [PieceIndex; ArchivedHistorySegment::NUM_PIECES] {
129        let mut source_first_piece_indices = [PieceIndex::ZERO; ArchivedHistorySegment::NUM_PIECES];
130
131        let piece_indices = self.segment_piece_indexes();
132        piece_indices
133            .into_iter()
134            .step_by(2)
135            .chain(piece_indices.into_iter().skip(1).step_by(2))
136            .zip(&mut source_first_piece_indices)
137            .for_each(|(input, output)| {
138                *output = input;
139            });
140
141        source_first_piece_indices
142    }
143
144    /// Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred.
145    #[inline]
146    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
147        // TODO: when Option::map becomes const, use it here
148        match self.0.checked_add(rhs.0) {
149            Some(segment_index) => Some(Self(segment_index)),
150            None => None,
151        }
152    }
153
154    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if underflow occurred.
155    #[inline]
156    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
157        // TODO: when Option::map becomes const, use it here
158        match self.0.checked_sub(rhs.0) {
159            Some(segment_index) => Some(Self(segment_index)),
160            None => None,
161        }
162    }
163
164    /// Saturating integer subtraction. Computes `self - rhs`, returning zero if underflow
165    /// occurred.
166    #[inline]
167    pub const fn saturating_sub(self, rhs: Self) -> Self {
168        Self(self.0.saturating_sub(rhs.0))
169    }
170}
171
172/// Segment commitment contained within segment header.
173#[derive(
174    Copy,
175    Clone,
176    Eq,
177    PartialEq,
178    Hash,
179    Deref,
180    DerefMut,
181    From,
182    Into,
183    Encode,
184    Decode,
185    TypeInfo,
186    MaxEncodedLen,
187    DecodeWithMemTracking,
188)]
189#[repr(transparent)]
190pub struct SegmentCommitment([u8; SegmentCommitment::SIZE]);
191
192impl fmt::Debug for SegmentCommitment {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        write!(f, "{}", hex::encode(self.0))
195    }
196}
197
198#[cfg(feature = "serde")]
199#[derive(Serialize, Deserialize)]
200#[serde(transparent)]
201struct SegmentCommitmentBinary(#[serde(with = "BigArray")] [u8; SegmentCommitment::SIZE]);
202
203#[cfg(feature = "serde")]
204#[derive(Serialize, Deserialize)]
205#[serde(transparent)]
206struct SegmentCommitmentHex(#[serde(with = "hex")] [u8; SegmentCommitment::SIZE]);
207
208#[cfg(feature = "serde")]
209impl Serialize for SegmentCommitment {
210    #[inline]
211    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
212    where
213        S: Serializer,
214    {
215        if serializer.is_human_readable() {
216            SegmentCommitmentHex(self.0).serialize(serializer)
217        } else {
218            SegmentCommitmentBinary(self.0).serialize(serializer)
219        }
220    }
221}
222
223#[cfg(feature = "serde")]
224impl<'de> Deserialize<'de> for SegmentCommitment {
225    #[inline]
226    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
227    where
228        D: Deserializer<'de>,
229    {
230        Ok(Self(if deserializer.is_human_readable() {
231            SegmentCommitmentHex::deserialize(deserializer)?.0
232        } else {
233            SegmentCommitmentBinary::deserialize(deserializer)?.0
234        }))
235    }
236}
237
238impl Default for SegmentCommitment {
239    #[inline]
240    fn default() -> Self {
241        Self([0; Self::SIZE])
242    }
243}
244
245impl TryFrom<&[u8]> for SegmentCommitment {
246    type Error = TryFromSliceError;
247
248    #[inline]
249    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
250        <[u8; Self::SIZE]>::try_from(slice).map(Self)
251    }
252}
253
254impl AsRef<[u8]> for SegmentCommitment {
255    #[inline]
256    fn as_ref(&self) -> &[u8] {
257        &self.0
258    }
259}
260
261impl AsMut<[u8]> for SegmentCommitment {
262    #[inline]
263    fn as_mut(&mut self) -> &mut [u8] {
264        &mut self.0
265    }
266}
267
268impl SegmentCommitment {
269    /// Size of segment commitment in bytes.
270    pub const SIZE: usize = 48;
271}
272
273/// Size of blockchain history in segments.
274#[derive(
275    Debug,
276    Display,
277    Copy,
278    Clone,
279    Ord,
280    PartialOrd,
281    Eq,
282    PartialEq,
283    Hash,
284    From,
285    Into,
286    Deref,
287    DerefMut,
288    Encode,
289    Decode,
290    TypeInfo,
291    MaxEncodedLen,
292    DecodeWithMemTracking,
293)]
294#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
295#[repr(transparent)]
296pub struct HistorySize(NonZeroU64);
297
298impl From<SegmentIndex> for HistorySize {
299    #[inline]
300    fn from(value: SegmentIndex) -> Self {
301        Self(NonZeroU64::new(value.0 + 1).expect("Not zero; qed"))
302    }
303}
304
305impl HistorySize {
306    /// History size of one
307    pub const ONE: Self = Self(NonZeroU64::new(1).expect("Not zero; qed"));
308
309    /// Create new instance.
310    pub const fn new(value: NonZeroU64) -> Self {
311        Self(value)
312    }
313
314    /// Size of blockchain history in pieces.
315    pub const fn in_pieces(&self) -> NonZeroU64 {
316        self.0.saturating_mul(
317            NonZeroU64::new(ArchivedHistorySegment::NUM_PIECES as u64).expect("Not zero; qed"),
318        )
319    }
320
321    /// Segment index that corresponds to this history size.
322    pub fn segment_index(&self) -> SegmentIndex {
323        SegmentIndex::from(self.0.get() - 1)
324    }
325
326    /// History size at which expiration check for sector happens.
327    ///
328    /// Returns `None` on overflow.
329    pub fn sector_expiration_check(&self, min_sector_lifetime: Self) -> Option<Self> {
330        self.0.checked_add(min_sector_lifetime.0.get()).map(Self)
331    }
332}
333
334/// Progress of an archived block.
335#[derive(
336    Debug,
337    Copy,
338    Clone,
339    PartialEq,
340    Eq,
341    Ord,
342    PartialOrd,
343    Hash,
344    Encode,
345    Decode,
346    TypeInfo,
347    DecodeWithMemTracking,
348)]
349#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
350#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
351pub enum ArchivedBlockProgress {
352    /// The block has been fully archived.
353    Complete,
354
355    /// Number of partially archived bytes of a block.
356    Partial(u32),
357}
358
359impl Default for ArchivedBlockProgress {
360    /// We assume a block can always fit into the segment initially, but it is definitely possible
361    /// to be transitioned into the partial state after some overflow checking.
362    #[inline]
363    fn default() -> Self {
364        Self::Complete
365    }
366}
367
368impl ArchivedBlockProgress {
369    /// Return the number of partially archived bytes if the progress is not complete.
370    pub fn partial(&self) -> Option<u32> {
371        match self {
372            Self::Complete => None,
373            Self::Partial(number) => Some(*number),
374        }
375    }
376
377    /// Sets new number of partially archived bytes.
378    pub fn set_partial(&mut self, new_partial: u32) {
379        *self = Self::Partial(new_partial);
380    }
381}
382
383/// Last archived block
384#[derive(
385    Debug,
386    Copy,
387    Clone,
388    PartialEq,
389    Eq,
390    Ord,
391    PartialOrd,
392    Hash,
393    Encode,
394    Decode,
395    TypeInfo,
396    DecodeWithMemTracking,
397)]
398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
399#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
400pub struct LastArchivedBlock {
401    /// Block number
402    pub number: BlockNumber,
403    /// Progress of an archived block.
404    pub archived_progress: ArchivedBlockProgress,
405}
406
407impl LastArchivedBlock {
408    /// Returns the number of partially archived bytes for a block.
409    pub fn partial_archived(&self) -> Option<u32> {
410        self.archived_progress.partial()
411    }
412
413    /// Sets new number of partially archived bytes.
414    pub fn set_partial_archived(&mut self, new_partial: u32) {
415        self.archived_progress.set_partial(new_partial);
416    }
417
418    /// Sets the archived state of this block to [`ArchivedBlockProgress::Complete`].
419    pub fn set_complete(&mut self) {
420        self.archived_progress = ArchivedBlockProgress::Complete;
421    }
422}
423
424/// Segment header for a specific segment.
425///
426/// Each segment will have corresponding [`SegmentHeader`] included as the first item in the next
427/// segment. Each `SegmentHeader` includes hash of the previous one and all together form a chain of
428/// segment headers that is used for quick and efficient verification that some [`Piece`]
429/// corresponds to the actual archival history of the blockchain.
430#[derive(
431    Debug, Copy, Clone, PartialEq, Eq, Encode, Decode, TypeInfo, Hash, DecodeWithMemTracking,
432)]
433#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
434#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
435pub enum SegmentHeader {
436    /// V0 of the segment header data structure
437    #[codec(index = 0)]
438    #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
439    V0 {
440        /// Segment index
441        segment_index: SegmentIndex,
442        /// Root of commitments of all records in a segment.
443        segment_commitment: SegmentCommitment,
444        /// Hash of the segment header of the previous segment
445        prev_segment_header_hash: Blake3Hash,
446        /// Last archived block
447        last_archived_block: LastArchivedBlock,
448    },
449}
450
451impl SegmentHeader {
452    /// Hash of the whole segment header
453    pub fn hash(&self) -> Blake3Hash {
454        blake3_hash(&self.encode())
455    }
456
457    /// Segment index
458    pub fn segment_index(&self) -> SegmentIndex {
459        match self {
460            Self::V0 { segment_index, .. } => *segment_index,
461        }
462    }
463
464    /// Segment commitment of the records in a segment.
465    pub fn segment_commitment(&self) -> SegmentCommitment {
466        match self {
467            Self::V0 {
468                segment_commitment, ..
469            } => *segment_commitment,
470        }
471    }
472
473    /// Hash of the segment header of the previous segment
474    pub fn prev_segment_header_hash(&self) -> Blake3Hash {
475        match self {
476            Self::V0 {
477                prev_segment_header_hash,
478                ..
479            } => *prev_segment_header_hash,
480        }
481    }
482
483    /// Last archived block
484    pub fn last_archived_block(&self) -> LastArchivedBlock {
485        match self {
486            Self::V0 {
487                last_archived_block,
488                ..
489            } => *last_archived_block,
490        }
491    }
492}
493
494/// Recorded history segment before archiving is applied.
495///
496/// NOTE: This is a stack-allocated data structure and can cause stack overflow!
497#[derive(Copy, Clone, Eq, PartialEq, Deref, DerefMut)]
498#[repr(transparent)]
499pub struct RecordedHistorySegment([RawRecord; Self::NUM_RAW_RECORDS]);
500
501impl fmt::Debug for RecordedHistorySegment {
502    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503        f.debug_struct("RecordedHistorySegment")
504            .finish_non_exhaustive()
505    }
506}
507
508impl Default for RecordedHistorySegment {
509    #[inline]
510    fn default() -> Self {
511        Self([RawRecord::default(); Self::NUM_RAW_RECORDS])
512    }
513}
514
515impl AsRef<[u8]> for RecordedHistorySegment {
516    #[inline]
517    fn as_ref(&self) -> &[u8] {
518        RawRecord::slice_to_repr(&self.0)
519            .as_flattened()
520            .as_flattened()
521    }
522}
523
524impl AsMut<[u8]> for RecordedHistorySegment {
525    #[inline]
526    fn as_mut(&mut self) -> &mut [u8] {
527        RawRecord::slice_mut_to_repr(&mut self.0)
528            .as_flattened_mut()
529            .as_flattened_mut()
530    }
531}
532
533impl RecordedHistorySegment {
534    /// Number of raw records in one segment of recorded history.
535    pub const NUM_RAW_RECORDS: usize = 128;
536    /// Erasure coding rate for records during archiving process.
537    pub const ERASURE_CODING_RATE: (usize, usize) = (1, 2);
538    /// Size of recorded history segment in bytes.
539    ///
540    /// It includes half of the records (just source records) that will later be erasure coded and
541    /// together with corresponding commitments and witnesses will result in
542    /// [`ArchivedHistorySegment::NUM_PIECES`] [`Piece`]s of archival history.
543    pub const SIZE: usize = RawRecord::SIZE * Self::NUM_RAW_RECORDS;
544
545    /// Create boxed value without hitting stack overflow
546    #[inline]
547    pub fn new_boxed() -> Box<Self> {
548        // TODO: Should have been just `::new()`, but https://github.com/rust-lang/rust/issues/53827
549        // SAFETY: Data structure filled with zeroes is a valid invariant
550        unsafe { Box::<Self>::new_zeroed().assume_init() }
551    }
552}
553
554/// Archived history segment after archiving is applied.
555#[derive(Debug, Clone, Eq, PartialEq, Deref, DerefMut)]
556#[repr(transparent)]
557pub struct ArchivedHistorySegment(FlatPieces);
558
559impl Default for ArchivedHistorySegment {
560    #[inline]
561    fn default() -> Self {
562        Self(FlatPieces::new(Self::NUM_PIECES))
563    }
564}
565
566impl ArchivedHistorySegment {
567    /// Number of pieces in one segment of archived history.
568    pub const NUM_PIECES: usize = RecordedHistorySegment::NUM_RAW_RECORDS
569        * RecordedHistorySegment::ERASURE_CODING_RATE.1
570        / RecordedHistorySegment::ERASURE_CODING_RATE.0;
571    /// Size of archived history segment in bytes.
572    ///
573    /// It includes erasure coded [`crate::pieces::PieceArray`]s (both source and parity) that are
574    /// composed of [`crate::pieces::Record`]s together with corresponding commitments and
575    /// witnesses.
576    pub const SIZE: usize = Piece::SIZE * Self::NUM_PIECES;
577
578    /// Ensure archived history segment contains cheaply cloneable shared data.
579    ///
580    /// Internally archived history segment uses CoW mechanism and can store either mutable owned
581    /// data or data that is cheap to clone, calling this method will ensure further clones and
582    /// returned pieces will not result in additional memory allocations.
583    pub fn to_shared(self) -> Self {
584        Self(self.0.to_shared())
585    }
586}