1#[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#[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 pub const ZERO: SegmentIndex = SegmentIndex(0);
92 pub const ONE: SegmentIndex = SegmentIndex(1);
94
95 #[inline]
97 pub const fn new(n: u64) -> Self {
98 Self(n)
99 }
100
101 #[inline]
103 pub const fn first_piece_index(&self) -> PieceIndex {
104 PieceIndex::new(self.0 * ArchivedHistorySegment::NUM_PIECES as u64)
105 }
106
107 #[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 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 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 #[inline]
146 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
147 match self.0.checked_add(rhs.0) {
149 Some(segment_index) => Some(Self(segment_index)),
150 None => None,
151 }
152 }
153
154 #[inline]
156 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
157 match self.0.checked_sub(rhs.0) {
159 Some(segment_index) => Some(Self(segment_index)),
160 None => None,
161 }
162 }
163
164 #[inline]
167 pub const fn saturating_sub(self, rhs: Self) -> Self {
168 Self(self.0.saturating_sub(rhs.0))
169 }
170}
171
172#[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 pub const SIZE: usize = 48;
271}
272
273#[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 pub const ONE: Self = Self(NonZeroU64::new(1).expect("Not zero; qed"));
308
309 pub const fn new(value: NonZeroU64) -> Self {
311 Self(value)
312 }
313
314 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 pub fn segment_index(&self) -> SegmentIndex {
323 SegmentIndex::from(self.0.get() - 1)
324 }
325
326 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#[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 Complete,
354
355 Partial(u32),
357}
358
359impl Default for ArchivedBlockProgress {
360 #[inline]
363 fn default() -> Self {
364 Self::Complete
365 }
366}
367
368impl ArchivedBlockProgress {
369 pub fn partial(&self) -> Option<u32> {
371 match self {
372 Self::Complete => None,
373 Self::Partial(number) => Some(*number),
374 }
375 }
376
377 pub fn set_partial(&mut self, new_partial: u32) {
379 *self = Self::Partial(new_partial);
380 }
381}
382
383#[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 pub number: BlockNumber,
403 pub archived_progress: ArchivedBlockProgress,
405}
406
407impl LastArchivedBlock {
408 pub fn partial_archived(&self) -> Option<u32> {
410 self.archived_progress.partial()
411 }
412
413 pub fn set_partial_archived(&mut self, new_partial: u32) {
415 self.archived_progress.set_partial(new_partial);
416 }
417
418 pub fn set_complete(&mut self) {
420 self.archived_progress = ArchivedBlockProgress::Complete;
421 }
422}
423
424#[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 #[codec(index = 0)]
438 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
439 V0 {
440 segment_index: SegmentIndex,
442 segment_commitment: SegmentCommitment,
444 prev_segment_header_hash: Blake3Hash,
446 last_archived_block: LastArchivedBlock,
448 },
449}
450
451impl SegmentHeader {
452 pub fn hash(&self) -> Blake3Hash {
454 blake3_hash(&self.encode())
455 }
456
457 pub fn segment_index(&self) -> SegmentIndex {
459 match self {
460 Self::V0 { segment_index, .. } => *segment_index,
461 }
462 }
463
464 pub fn segment_commitment(&self) -> SegmentCommitment {
466 match self {
467 Self::V0 {
468 segment_commitment, ..
469 } => *segment_commitment,
470 }
471 }
472
473 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 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#[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 pub const NUM_RAW_RECORDS: usize = 128;
536 pub const ERASURE_CODING_RATE: (usize, usize) = (1, 2);
538 pub const SIZE: usize = RawRecord::SIZE * Self::NUM_RAW_RECORDS;
544
545 #[inline]
547 pub fn new_boxed() -> Box<Self> {
548 unsafe { Box::<Self>::new_zeroed().assume_init() }
551 }
552}
553
554#[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 pub const NUM_PIECES: usize = RecordedHistorySegment::NUM_RAW_RECORDS
569 * RecordedHistorySegment::ERASURE_CODING_RATE.1
570 / RecordedHistorySegment::ERASURE_CODING_RATE.0;
571 pub const SIZE: usize = Piece::SIZE * Self::NUM_PIECES;
577
578 pub fn to_shared(self) -> Self {
584 Self(self.0.to_shared())
585 }
586}