Skip to main content

ab_farmer_components/
sector.rs

1//! Sector-related data structures
2//!
3//! Sectors and corresponding metadata created by functions in [`plotting`](crate::plotting) module
4//! have a specific structure, represented by data structured in this module.
5//!
6//! It is typically not needed to construct these data structures explicitly outside of this crate,
7//! instead they will be returned as a result of certain operations (like plotting).
8
9#[cfg(test)]
10mod tests;
11
12use ab_core_primitives::checksum::Blake3Checksummed;
13use ab_core_primitives::hashes::Blake3Hash;
14use ab_core_primitives::pieces::{PieceHeader, PieceOffset, Record};
15use ab_core_primitives::sectors::{SBucket, SectorIndex};
16use ab_core_primitives::segments::HistorySize;
17use ab_direct_io_file::OwnedPages;
18use ab_io_type::trivial_type::TrivialType;
19use parity_scale_codec::{Decode, Encode};
20use rayon::prelude::*;
21use std::mem::MaybeUninit;
22use std::ops::{Deref, DerefMut};
23use thiserror::Error;
24use tracing::debug;
25
26/// Size of the part of the plot containing record chunks (s-buckets).
27///
28/// Total size of the plot can be computed with [`sector_size()`].
29#[inline]
30pub const fn sector_record_chunks_size(pieces_in_sector: u16) -> usize {
31    pieces_in_sector as usize * Record::SIZE
32}
33
34/// Size of the part of the plot containing record metadata.
35///
36/// Total size of the plot can be computed with [`sector_size()`].
37#[inline]
38pub const fn sector_record_metadata_size(pieces_in_sector: u16) -> usize {
39    pieces_in_sector as usize * RecordMetadata::encoded_size()
40}
41
42/// Size of the zero padding between record metadata and sector checksum.
43///
44/// Padding makes [`sector_size()`] a multiple of [`OwnedPages::ALIGN`].
45#[inline]
46pub const fn sector_padding_size(pieces_in_sector: u16) -> usize {
47    let unpadded_size = sector_record_chunks_size(pieces_in_sector)
48        + sector_record_metadata_size(pieces_in_sector)
49        + SectorContentsMap::encoded_size(pieces_in_sector) as usize
50        + Blake3Hash::SIZE;
51
52    unpadded_size.next_multiple_of(OwnedPages::ALIGN as usize) - unpadded_size
53}
54
55/// Exact sector plot size (sector contents map, record chunks, record metadata, padding and
56/// checksum).
57///
58/// NOTE: Each sector also has corresponding fixed size metadata whose size can be obtained with
59/// [`SectorMetadataChecksummed::disk_size()`], size of the record chunks (s-buckets) with
60/// [`sector_record_chunks_size()`], size of record roots and proofs with
61/// [`sector_record_metadata_size()`] and size of padding with [`sector_padding_size()`]. This
62/// function just combines those together for convenience.
63#[inline]
64pub const fn sector_size(pieces_in_sector: u16) -> usize {
65    sector_record_chunks_size(pieces_in_sector)
66        + sector_record_metadata_size(pieces_in_sector)
67        + SectorContentsMap::encoded_size(pieces_in_sector) as usize
68        + sector_padding_size(pieces_in_sector)
69        + Blake3Hash::SIZE
70}
71
72/// Metadata of the plotted sector
73#[derive(Debug, Encode, Decode, Clone)]
74pub struct SectorMetadata {
75    /// Sector index
76    pub sector_index: SectorIndex,
77    /// Number of pieces stored in this sector
78    pub pieces_in_sector: u16,
79    /// S-bucket sizes in a sector
80    pub s_bucket_sizes: Box<[u16; Record::NUM_S_BUCKETS]>,
81    // TODO: Should this be constrained to the last segment of the super segment?
82    /// Size of the blockchain history at the time of sector creation
83    pub history_size: HistorySize,
84}
85
86impl SectorMetadata {
87    /// Returns offsets of each s-bucket relatively to the beginning of the sector (in chunks)
88    pub fn s_bucket_offsets(&self) -> Box<[u32; Record::NUM_S_BUCKETS]> {
89        let s_bucket_offsets = self
90            .s_bucket_sizes
91            .iter()
92            .map({
93                let mut base_offset = 0;
94
95                move |s_bucket_size| {
96                    let offset = base_offset;
97                    base_offset += u32::from(*s_bucket_size);
98                    offset
99                }
100            })
101            .collect::<Box<_>>();
102
103        assert_eq!(s_bucket_offsets.len(), Record::NUM_S_BUCKETS);
104        // SAFETY: Number of elements checked above
105        unsafe {
106            Box::from_raw(Box::into_raw(s_bucket_offsets).cast::<[u32; Record::NUM_S_BUCKETS]>())
107        }
108    }
109}
110
111/// Same as [`SectorMetadata`], but with checksums verified during SCALE encoding/decoding
112#[derive(Debug, Clone, Encode, Decode)]
113pub struct SectorMetadataChecksummed(Blake3Checksummed<SectorMetadata>);
114
115impl From<SectorMetadata> for SectorMetadataChecksummed {
116    #[inline]
117    fn from(value: SectorMetadata) -> Self {
118        Self(Blake3Checksummed(value))
119    }
120}
121
122impl Deref for SectorMetadataChecksummed {
123    type Target = SectorMetadata;
124
125    #[inline]
126    fn deref(&self) -> &Self::Target {
127        &self.0.0
128    }
129}
130
131impl DerefMut for SectorMetadataChecksummed {
132    #[inline]
133    fn deref_mut(&mut self) -> &mut Self::Target {
134        &mut self.0.0
135    }
136}
137
138impl SectorMetadataChecksummed {
139    /// Size of checksummed sector metadata on disk in pages of [`OwnedPages::ALIGN`] bytes, see
140    /// [`Self::disk_size()`]
141    pub const DISK_PAGES: u32 = {
142        assert!(Self::disk_size() <= u32::MAX as usize);
143        (Self::disk_size() / OwnedPages::ALIGN as usize) as u32
144    };
145
146    /// Size of checksummed sector metadata on disk.
147    ///
148    /// Sector metadata is padded with zeroes to a multiple of [`OwnedPages::ALIGN`], such that it
149    /// can be written with direct I/O without read-modify-write, see [`Self::encode_for_disk()`].
150    ///
151    /// For sector plot size use [`sector_size()`].
152    #[inline]
153    pub const fn disk_size() -> usize {
154        Self::encoded_size().next_multiple_of(OwnedPages::ALIGN as usize)
155    }
156
157    /// Encode checksummed sector metadata for storing on disk, padded with zeroes to
158    /// [`Self::disk_size()`]
159    pub fn encode_for_disk(&self) -> OwnedPages {
160        let mut bytes = OwnedPages::zeroed(Self::DISK_PAGES * OwnedPages::ALIGN);
161        self.encode_to(&mut bytes.as_mut_slice());
162        bytes
163    }
164
165    /// Decode checksummed sector metadata stored on disk, the inverse of
166    /// [`Self::encode_for_disk()`]
167    pub fn decode_from_disk(
168        bytes: &[u8; Self::disk_size()],
169    ) -> Result<Self, parity_scale_codec::Error> {
170        Self::decode(&mut bytes.as_slice())
171    }
172
173    /// Size of SCALE-encoded checksummed sector metadata
174    const fn encoded_size() -> usize {
175        // Fields of `SectorMetadata` followed by the checksum
176        SectorIndex::SIZE
177            + size_of::<u16>()
178            + size_of::<[u16; Record::NUM_S_BUCKETS]>()
179            + size_of::<HistorySize>()
180            + Blake3Hash::SIZE
181    }
182}
183
184/// Root and proof corresponding to the same record
185#[derive(Debug, Default, Copy, Clone, Encode, Decode)]
186#[repr(C)]
187pub(crate) struct RecordMetadata {
188    /// Piece header
189    pub(crate) piece_header: PieceHeader,
190    /// Checksum (hash) of the whole piece
191    pub(crate) piece_checksum: Blake3Hash,
192}
193
194const {
195    assert!(align_of::<RecordMetadata>() == 1);
196}
197
198impl RecordMetadata {
199    pub(crate) const fn encoded_size() -> usize {
200        size_of::<Self>()
201    }
202}
203
204/// Raw sector before it is transformed and written to plot, used during plotting
205#[derive(Debug, Clone)]
206pub(crate) struct RawSector {
207    /// List of records, likely downloaded from the network
208    pub(crate) records: Vec<Record>,
209    /// Metadata (root and proof) corresponding to the same record
210    pub(crate) metadata: Vec<RecordMetadata>,
211}
212
213impl RawSector {
214    /// Create new raw sector with internal vectors being allocated and filled with default values
215    pub(crate) fn new(pieces_in_sector: u16) -> Self {
216        Self {
217            records: Record::new_zero_vec(usize::from(pieces_in_sector)),
218            metadata: vec![RecordMetadata::default(); usize::from(pieces_in_sector)],
219        }
220    }
221}
222
223/// S-buckets at which proofs were found.
224///
225/// S-buckets are grouped by 8, within each `u8` bits right to left (LSB) indicate the presence
226/// of a proof for corresponding s-bucket, so that the whole array of bytes can be thought as a
227/// large set of bits.
228///
229/// There are always exactly [`Record::NUM_CHUNKS`] proofs produced/bits set to `1`.
230pub type FoundProofs = [u8; Record::NUM_S_BUCKETS / u8::BITS as usize];
231
232/// Error happening when trying to create [`SectorContentsMap`] from bytes
233#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
234pub enum SectorContentsMapFromBytesError {
235    /// Invalid bytes length
236    #[error("Invalid bytes length, expected {expected}, actual {actual}")]
237    InvalidBytesLength {
238        /// Expected length
239        expected: usize,
240        /// Actual length
241        actual: usize,
242    },
243    /// Checksum mismatch
244    #[error("Checksum mismatch")]
245    ChecksumMismatch,
246}
247
248/// Error happening when trying to encode [`SectorContentsMap`] into bytes
249#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
250pub enum SectorContentsMapEncodeIntoError {
251    /// Invalid bytes length
252    #[error("Invalid bytes length, expected {expected}, actual {actual}")]
253    InvalidBytesLength {
254        /// Expected length
255        expected: usize,
256        /// Actual length
257        actual: usize,
258    },
259}
260
261/// Error happening when trying to create [`SectorContentsMap`] from bytes
262#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
263pub enum SectorContentsMapIterationError {
264    /// S-bucket provided is out of range
265    #[error("S-bucket provided {provided} is out of range, max {max}")]
266    SBucketOutOfRange {
267        /// Provided s-bucket
268        provided: usize,
269        /// Max s-bucket
270        max: usize,
271    },
272}
273
274/// Map of sector contents.
275///
276/// Abstraction on top of bitfields that allow making sense of sector contents that contain
277/// encoded (meaning erasure coded and encoded with existing PoSpace proof) chunks used at the same
278/// time both in records (before writing to plot) and s-buckets (written into the plot) format
279#[derive(Debug, Clone, Eq, PartialEq)]
280pub struct SectorContentsMap {
281    /// Bitfields for each record, each bit is `true` if record chunk at corresponding position was
282    /// used
283    record_chunks_used: Vec<FoundProofs>,
284}
285
286impl SectorContentsMap {
287    /// Create new sector contents map initialized with zeroes to store data for `pieces_in_sector`
288    /// records
289    pub fn new(pieces_in_sector: u16) -> Self {
290        Self {
291            record_chunks_used: vec![[0; _]; usize::from(pieces_in_sector)],
292        }
293    }
294
295    /// Reconstruct sector contents map from bytes.
296    ///
297    /// Returns error if length of the vector doesn't match [`Self::encoded_size()`] for
298    /// `pieces_in_sector`.
299    pub fn from_bytes(
300        bytes: &[u8],
301        pieces_in_sector: u16,
302    ) -> Result<Self, SectorContentsMapFromBytesError> {
303        if bytes.len() != Self::encoded_size(pieces_in_sector) as usize {
304            return Err(SectorContentsMapFromBytesError::InvalidBytesLength {
305                expected: Self::encoded_size(pieces_in_sector) as usize,
306                actual: bytes.len(),
307            });
308        }
309
310        let (single_records_bit_arrays, expected_checksum) =
311            bytes.split_at(bytes.len() - Blake3Hash::SIZE);
312        let expected_checksum = Blake3Hash::from_bytes_exact(expected_checksum)
313            .expect("Correct size, no alignment requirements; qed");
314        // Verify checksum
315        let actual_checksum = Blake3Hash::from(blake3::hash(single_records_bit_arrays));
316        if &actual_checksum != expected_checksum {
317            debug!(
318                %actual_checksum,
319                %expected_checksum,
320                "Hash doesn't match, corrupted bytes"
321            );
322
323            return Err(SectorContentsMapFromBytesError::ChecksumMismatch);
324        }
325
326        // Length was checked above, so there is no remainder
327        let record_chunks_used = single_records_bit_arrays.as_chunks().0.to_vec();
328
329        Ok(Self { record_chunks_used })
330    }
331
332    /// Size of sector contents map when encoded and stored in the plot for specified number of
333    /// pieces in sector
334    pub const fn encoded_size(pieces_in_sector: u16) -> u32 {
335        const {
336            assert!(
337                size_of::<FoundProofs>() * usize::from(u16::MAX) + Blake3Hash::SIZE
338                    <= u32::MAX as usize
339            );
340        }
341        // Lossless as checked above
342        size_of::<FoundProofs>() as u32 * u32::from(pieces_in_sector) + Blake3Hash::SIZE as u32
343    }
344
345    /// Encode internal contents into `output`, which doesn't need to be initialized.
346    ///
347    /// Returns `output` that is now fully initialized.
348    pub fn encode_into<'a>(
349        &self,
350        output: &'a mut [MaybeUninit<u8>],
351    ) -> Result<&'a mut [u8], SectorContentsMapEncodeIntoError> {
352        if output.len() != Self::encoded_size(self.record_chunks_used.len() as u16) as usize {
353            return Err(SectorContentsMapEncodeIntoError::InvalidBytesLength {
354                expected: Self::encoded_size(self.record_chunks_used.len() as u16) as usize,
355                actual: output.len(),
356            });
357        }
358
359        let slice = self.record_chunks_used.as_flattened();
360        // Write data and checksum
361        let (data_output, checksum_output) = output.split_at_mut(slice.len());
362        data_output.write_copy_of_slice(slice);
363        checksum_output.write_copy_of_slice(blake3::hash(slice).as_bytes());
364
365        // SAFETY: Data and checksum together cover the whole `output`, both were initialized above
366        Ok(unsafe { output.assume_init_mut() })
367    }
368
369    /// Iterate over individual record chunks (s-buckets) that were used
370    pub fn iter_record_chunks_used(&self) -> &[FoundProofs] {
371        &self.record_chunks_used
372    }
373
374    /// Iterate mutably over individual record chunks (s-buckets) that were used
375    pub fn iter_record_chunks_used_mut(&mut self) -> &mut [FoundProofs] {
376        &mut self.record_chunks_used
377    }
378
379    /// Returns sizes of each s-bucket
380    pub fn s_bucket_sizes(&self) -> Box<[u16; Record::NUM_S_BUCKETS]> {
381        // Rayon doesn't support iteration over custom types yet
382        let s_bucket_sizes = (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX))
383            .into_par_iter()
384            .map(SBucket::from)
385            .map(|s_bucket| {
386                self.iter_s_bucket_piece_offsets(s_bucket)
387                    .expect("S-bucket guaranteed to be in range; qed")
388                    .count() as u16
389            })
390            .collect::<Box<_>>();
391
392        assert_eq!(s_bucket_sizes.len(), Record::NUM_S_BUCKETS);
393
394        // SAFETY: Number of elements checked above
395        unsafe {
396            Box::from_raw(Box::into_raw(s_bucket_sizes).cast::<[u16; Record::NUM_S_BUCKETS]>())
397        }
398    }
399
400    /// Creates an iterator of `(s_bucket, chunk_location)`, where `s_bucket` is the position of the
401    /// chunk in the erasure coded record and `chunk_location` is the offset of the chunk in the
402    /// plot (across all s-buckets).
403    pub fn iter_record_chunk_to_plot(
404        &self,
405        piece_offset: PieceOffset,
406    ) -> impl Iterator<Item = (SBucket, usize)> + '_ {
407        // Iterate over all s-buckets
408        (SBucket::ZERO..=SBucket::MAX)
409            // In each s-bucket map all records used
410            .flat_map(|s_bucket| {
411                self.iter_s_bucket_piece_offsets(s_bucket)
412                    .expect("S-bucket guaranteed to be in range; qed")
413                    .map(move |current_piece_offset| (s_bucket, current_piece_offset))
414            })
415            // We've got contents of all s-buckets in a flat iterator, enumerating them so it is
416            // possible to find in the plot later if desired
417            .enumerate()
418            // Everything about the piece offset we care about
419            .filter_map(move |(chunk_location, (s_bucket, current_piece_offset))| {
420                // In case record for `piece_offset` is found, return necessary information
421                (current_piece_offset == piece_offset).then_some((s_bucket, chunk_location))
422            })
423            // Tiny optimization in case we have found chunks for all records already
424            .take(Record::NUM_CHUNKS)
425    }
426
427    /// Creates an iterator of `Option<chunk_offset>`, where each entry corresponds
428    /// s-bucket/position of the chunk in the erasure coded record, `chunk_offset` is the offset of
429    /// the chunk in the corresponding s-bucket.
430    ///
431    /// Similar to `Self::iter_record_chunk_to_plot()`, but runs in parallel, returns entries for
432    /// all s-buckets and offsets are within corresponding s-buckets rather than the whole plot.
433    pub fn par_iter_record_chunk_to_plot(
434        &self,
435        piece_offset: PieceOffset,
436    ) -> impl IndexedParallelIterator<Item = Option<usize>> + '_ {
437        let piece_offset = usize::from(piece_offset);
438        (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX))
439            .into_par_iter()
440            .map(SBucket::from)
441            // In each s-bucket map all records used
442            .map(move |s_bucket| {
443                let byte_offset = usize::from(s_bucket) / u8::BITS as usize;
444                let bit_mask = 1 << (usize::from(s_bucket) % u8::BITS as usize);
445
446                if self.record_chunks_used[piece_offset][byte_offset] & bit_mask == 0 {
447                    return None;
448                }
449
450                // How many other record chunks we have in s-bucket before piece offset we care
451                // about
452                let chunk_offset = self
453                    .record_chunks_used
454                    .iter()
455                    .take(piece_offset)
456                    .filter(move |record_chunks_used| {
457                        record_chunks_used[byte_offset] & bit_mask != 0
458                    })
459                    .count();
460
461                Some(chunk_offset)
462            })
463    }
464
465    /// Creates an iterator of piece offsets to which corresponding chunks belong.
466    ///
467    /// Returns error if `s_bucket` is outside of [`Record::NUM_S_BUCKETS`] range.
468    pub fn iter_s_bucket_piece_offsets(
469        &self,
470        s_bucket: SBucket,
471    ) -> Result<impl Iterator<Item = PieceOffset> + '_, SectorContentsMapIterationError> {
472        let s_bucket = usize::from(s_bucket);
473
474        if s_bucket >= Record::NUM_S_BUCKETS {
475            return Err(SectorContentsMapIterationError::SBucketOutOfRange {
476                provided: s_bucket,
477                max: Record::NUM_S_BUCKETS,
478            });
479        }
480
481        Ok((PieceOffset::ZERO..)
482            .zip(&self.record_chunks_used)
483            .filter_map(move |(piece_offset, record_chunks_used)| {
484                let byte_offset = s_bucket / u8::BITS as usize;
485                let bit_mask = 1 << (s_bucket % u8::BITS as usize);
486
487                (record_chunks_used[byte_offset] & bit_mask != 0).then_some(piece_offset)
488            }))
489    }
490
491    /// Iterate over chunks of s-bucket indicating if record chunk is used at corresponding
492    /// position.
493    ///
494    /// ## Panics
495    /// Panics if `s_bucket` is outside of [`Record::NUM_S_BUCKETS`] range.
496    pub fn iter_s_bucket_used_record_chunks_used(
497        &self,
498        s_bucket: SBucket,
499    ) -> Result<impl Iterator<Item = bool> + '_, SectorContentsMapIterationError> {
500        let s_bucket = usize::from(s_bucket);
501
502        if s_bucket >= Record::NUM_S_BUCKETS {
503            return Err(SectorContentsMapIterationError::SBucketOutOfRange {
504                provided: s_bucket,
505                max: Record::NUM_S_BUCKETS,
506            });
507        }
508
509        Ok(self
510            .record_chunks_used
511            .iter()
512            .map(move |record_chunks_used| {
513                let byte_offset = s_bucket / u8::BITS as usize;
514                let bit_mask = 1 << (s_bucket % u8::BITS as usize);
515
516                record_chunks_used[byte_offset] & bit_mask != 0
517            }))
518    }
519}