Skip to main content

ab_farmer_components/
reading.rs

1//! Reading utilities
2//!
3//! This module contains utilities for extracting data from plots/sectors created by functions in
4//! [`plotting`](crate::plotting) module earlier. This is a relatively expensive operation and is
5//! only used for cold storage purposes or when there is a need to prove a solution to consensus.
6
7use crate::sector::{
8    RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed,
9    sector_record_chunks_size,
10};
11use crate::{ReadAt, ReadAtAsync, ReadAtSync};
12use ab_core_primitives::hashes::Blake3Hash;
13use ab_core_primitives::pieces::{ExtendedRecord, Piece, PieceOffset, Record, RecordChunk};
14use ab_core_primitives::sectors::SectorId;
15use ab_direct_io_file::{IoBufError, OwnedPages};
16use ab_erasure_coding::{ErasureCoding, ErasureCodingError, ShardsPresent};
17use ab_proof_of_space::{PosProofs, Table, TableGenerator};
18use futures::{TryStreamExt, stream};
19use parity_scale_codec::Decode;
20use rayon::prelude::*;
21use std::simd::Simd;
22use std::{io, mem};
23use thiserror::Error;
24use tracing::debug;
25
26/// Maximum number of record chunks that are read concurrently with [`ReadAtAsync`].
27///
28/// Enough concurrent reads to hide the latency of individual reads, while bounding the number of
29/// in-flight requests and buffers allocated for them.
30const MAX_CONCURRENT_ASYNC_CHUNK_READS: usize = 16;
31
32/// Errors that happen during reading
33#[derive(Debug, Error)]
34pub enum ReadingError {
35    /// Failed to read chunk.
36    ///
37    /// This is an implementation bug, most likely due to mismatch between sector contents map and
38    /// other farming parameters.
39    #[error("Failed to read chunk at location {chunk_location}: {error}")]
40    FailedToReadChunk {
41        /// Chunk location
42        chunk_location: u64,
43        /// Low-level error
44        error: io::Error,
45    },
46    /// PoS proofs don't match the sector contents map.
47    ///
48    /// Either the sector contents map has no entry for the record, or the record's chunks in it
49    /// are not at exactly the s-buckets that have proofs. There is no entry when the piece offset
50    /// is outside of the sector. Chunks at other s-buckets usually mean that the sector doesn't
51    /// match its metadata, so proofs are created for a different sector ID than the one the sector
52    /// was plotted with.
53    #[error("PoS proofs don't match sector contents map for record at offset {piece_offset}")]
54    PosProofsMismatch {
55        /// Piece offset
56        piece_offset: PieceOffset,
57    },
58    /// Failed to erasure-decode record
59    #[error("Failed to erasure-decode record at offset {piece_offset}: {error}")]
60    FailedToErasureDecodeRecord {
61        /// Piece offset
62        piece_offset: PieceOffset,
63        /// Lower-level error
64        error: ErasureCodingError,
65    },
66    /// Wrong record size after decoding
67    #[error("Wrong record size after decoding: expected {expected}, actual {actual}")]
68    WrongRecordSizeAfterDecoding {
69        /// Expected size in bytes
70        expected: usize,
71        /// Actual size in bytes
72        actual: usize,
73    },
74    /// Failed to decode sector contents map
75    #[error("Failed to decode sector contents map: {0}")]
76    FailedToDecodeSectorContentsMap(#[from] SectorContentsMapFromBytesError),
77    /// I/O error occurred
78    #[error("Reading I/O error: {0}")]
79    Io(#[from] io::Error),
80    /// Checksum mismatch
81    #[error("Checksum mismatch")]
82    ChecksumMismatch,
83}
84
85impl<B> From<IoBufError<B>> for ReadingError {
86    #[inline]
87    fn from(error: IoBufError<B>) -> Self {
88        Self::Io(error.into())
89    }
90}
91
92impl ReadingError {
93    /// Whether this error is fatal and renders farm unusable
94    pub fn is_fatal(&self) -> bool {
95        #[expect(
96            clippy::rest_pattern_accessible_field,
97            reason = "Do not care about fields"
98        )]
99        match self {
100            ReadingError::FailedToReadChunk { .. } => false,
101            ReadingError::PosProofsMismatch { .. } => false,
102            ReadingError::FailedToErasureDecodeRecord { .. } => false,
103            ReadingError::WrongRecordSizeAfterDecoding { .. } => false,
104            ReadingError::FailedToDecodeSectorContentsMap(_) => false,
105            ReadingError::Io(_) => true,
106            ReadingError::ChecksumMismatch => false,
107        }
108    }
109}
110
111/// Record chunks read from a sector.
112///
113/// Contents of chunks that are not present are unspecified.
114#[derive(Debug)]
115pub struct SectorRecordChunks {
116    /// Source and parity chunks
117    pub extended_record: Box<ExtendedRecord>,
118    /// Which chunks are present
119    pub present: ShardsPresent<{ Record::NUM_CHUNKS }>,
120}
121
122/// Read sector record chunks, only plotted s-buckets are marked as present (in decoded form).
123///
124/// Returns [`ReadingError::PosProofsMismatch`] if the sector contents map has no entry for
125/// `piece_offset`, or if the record's chunks in it are not at exactly the s-buckets of
126/// `pos_proofs`. Each chunk was encoded with the proof for its s-bucket, so chunks can't be
127/// decoded correctly otherwise.
128///
129/// NOTE: This is an async function, but it also does CPU-intensive operation internally, while it
130/// is not very long, make sure it is okay to do so in your context.
131pub async fn read_sector_record_chunks<S, A>(
132    piece_offset: PieceOffset,
133    pieces_in_sector: u16,
134    s_bucket_offsets: &[u32; Record::NUM_S_BUCKETS],
135    sector_contents_map: &SectorContentsMap,
136    pos_proofs: &PosProofs,
137    sector: &ReadAt<S, A>,
138) -> Result<SectorRecordChunks, ReadingError>
139where
140    S: ReadAtSync,
141    A: ReadAtAsync,
142{
143    // Chunks are paired with proofs in s-bucket order below, which is only correct when the record
144    // has chunks at exactly the s-buckets with proofs
145    if sector_contents_map
146        .iter_record_chunks_used()
147        .get(usize::from(piece_offset))
148        != Some(&pos_proofs.found_proofs)
149    {
150        return Err(ReadingError::PosProofsMismatch { piece_offset });
151    }
152
153    let mut extended_record = ExtendedRecord::new_boxed();
154    let mut present = ShardsPresent::none();
155
156    let read_chunks_inputs = extended_record
157        .as_s_buckets_mut()
158        .par_iter_mut()
159        .zip(sector_contents_map.par_iter_record_chunk_to_plot(piece_offset))
160        .zip(s_bucket_offsets.par_iter())
161        .enumerate()
162        .map(
163            |(index, ((record_chunk, maybe_chunk_offset), &s_bucket_offset))| {
164                let chunk_offset = maybe_chunk_offset?;
165
166                let chunk_location = chunk_offset as u64 + u64::from(s_bucket_offset);
167
168                Some((index, record_chunk, chunk_location))
169            },
170        )
171        .flatten()
172        .collect::<Vec<_>>();
173
174    for &(index, _, _) in &read_chunks_inputs {
175        if let Some(parity_index) = index.checked_sub(Record::NUM_CHUNKS) {
176            present.parity.set(parity_index);
177        } else {
178            present.source.set(index);
179        }
180    }
181
182    let sector_contents_map_size = u64::from(SectorContentsMap::encoded_size(pieces_in_sector));
183    match sector {
184        ReadAt::Sync(sector) => {
185            read_chunks_inputs
186                .into_par_iter()
187                .zip(&pos_proofs.proofs)
188                .try_for_each_init(
189                    || OwnedPages::EMPTY,
190                    |buffer, ((_index, output_chunk, chunk_location), pos_proof)| {
191                        let record_chunk = sector
192                            .read_at(
193                                mem::take(buffer),
194                                RecordChunk::SIZE as u32,
195                                sector_contents_map_size
196                                    + chunk_location * RecordChunk::SIZE as u64,
197                            )
198                            .map_err(|error| ReadingError::FailedToReadChunk {
199                                chunk_location,
200                                error: error.into(),
201                            })?;
202
203                        let record_chunk_bytes =
204                            <[u8; RecordChunk::SIZE]>::try_from(record_chunk.as_slice())
205                                .expect("Exactly one record chunk was read; qed");
206                        // TODO: Use SIMD for hashing
207                        *output_chunk = RecordChunk::from(Simd::to_array(
208                            Simd::from(record_chunk_bytes) ^ Simd::from(*pos_proof.hash()),
209                        ));
210                        *buffer = record_chunk.into_empty();
211
212                        Ok::<_, ReadingError>(())
213                    },
214                )?;
215        }
216        ReadAt::Async(sector) => {
217            // Each read has its own buffer, so the number of concurrent reads is limited to keep
218            // memory usage low
219            stream::iter(
220                read_chunks_inputs
221                    .into_iter()
222                    .zip(&pos_proofs.proofs)
223                    .map(Ok::<_, ReadingError>),
224            )
225            .try_for_each_concurrent(
226                MAX_CONCURRENT_ASYNC_CHUNK_READS,
227                |((_index, output_chunk, chunk_location), pos_proof)| async move {
228                    let record_chunk = sector
229                        .read_at(
230                            OwnedPages::EMPTY,
231                            RecordChunk::SIZE as u32,
232                            sector_contents_map_size + chunk_location * RecordChunk::SIZE as u64,
233                        )
234                        .await
235                        .map_err(|error| ReadingError::FailedToReadChunk {
236                            chunk_location,
237                            error: error.into(),
238                        })?;
239
240                    let record_chunk_bytes =
241                        <[u8; RecordChunk::SIZE]>::try_from(record_chunk.as_slice())
242                            .expect("Exactly one record chunk was read; qed");
243                    // TODO: Use SIMD for hashing
244                    *output_chunk = RecordChunk::from(Simd::to_array(
245                        Simd::from(record_chunk_bytes) ^ Simd::from(*pos_proof.hash()),
246                    ));
247
248                    Ok(())
249                },
250            )
251            .await?;
252        }
253    }
254
255    Ok(SectorRecordChunks {
256        extended_record,
257        present,
258    })
259}
260
261/// Given sector record chunks recover the source record in place
262pub fn recover_source_record<'a>(
263    sector_record_chunks: &'a mut SectorRecordChunks,
264    piece_offset: PieceOffset,
265    erasure_coding: &ErasureCoding,
266) -> Result<&'a Record, ReadingError> {
267    let SectorRecordChunks {
268        extended_record,
269        present,
270    } = sector_record_chunks;
271    let ExtendedRecord { source, parity } = &mut **extended_record;
272
273    erasure_coding
274        .recover_source(source, parity, present)
275        .map_err(|error| ReadingError::FailedToErasureDecodeRecord {
276            piece_offset,
277            error,
278        })?;
279
280    Ok(source)
281}
282
283/// Read metadata (roots and proof) for record
284pub(crate) async fn read_record_metadata<S, A>(
285    piece_offset: PieceOffset,
286    pieces_in_sector: u16,
287    sector: &ReadAt<S, A>,
288) -> Result<RecordMetadata, ReadingError>
289where
290    S: ReadAtSync,
291    A: ReadAtAsync,
292{
293    let sector_metadata_start = u64::from(SectorContentsMap::encoded_size(pieces_in_sector))
294        + sector_record_chunks_size(pieces_in_sector) as u64;
295    // Move to the beginning of the root and proof we care about
296    let record_metadata_offset =
297        sector_metadata_start + RecordMetadata::encoded_size() as u64 * u64::from(piece_offset);
298
299    let record_metadata_size = RecordMetadata::encoded_size() as u32;
300    let record_metadata_bytes = match sector {
301        ReadAt::Sync(sector) => sector.read_at(
302            OwnedPages::EMPTY,
303            record_metadata_size,
304            record_metadata_offset,
305        ),
306        ReadAt::Async(sector) => {
307            sector
308                .read_at(
309                    OwnedPages::EMPTY,
310                    record_metadata_size,
311                    record_metadata_offset,
312                )
313                .await
314        }
315    }?;
316    let record_metadata = RecordMetadata::decode(&mut record_metadata_bytes.as_slice())
317        .expect("Length is correct, contents doesn't have specific structure to it; qed");
318
319    Ok(record_metadata)
320}
321
322/// Read piece from sector.
323///
324/// NOTE: Even though this function is async, proof of time table generation is expensive and should
325/// be done in a dedicated thread where blocking is allowed.
326pub async fn read_piece<PosTable, S, A>(
327    piece_offset: PieceOffset,
328    sector_id: &SectorId,
329    sector_metadata: &SectorMetadataChecksummed,
330    sector: &ReadAt<S, A>,
331    erasure_coding: &ErasureCoding,
332    table_generator: &PosTable::Generator,
333) -> Result<Piece, ReadingError>
334where
335    PosTable: Table,
336    S: ReadAtSync,
337    A: ReadAtAsync,
338{
339    let pieces_in_sector = sector_metadata.pieces_in_sector;
340
341    let sector_contents_map = {
342        let sector_contents_map_size = SectorContentsMap::encoded_size(pieces_in_sector);
343        let sector_contents_map_bytes = match sector {
344            ReadAt::Sync(sector) => sector.read_at(OwnedPages::EMPTY, sector_contents_map_size, 0),
345            ReadAt::Async(sector) => {
346                sector
347                    .read_at(OwnedPages::EMPTY, sector_contents_map_size, 0)
348                    .await
349            }
350        }?;
351
352        SectorContentsMap::from_bytes(&sector_contents_map_bytes, pieces_in_sector)?
353    };
354
355    let mut sector_record_chunks = read_sector_record_chunks(
356        piece_offset,
357        pieces_in_sector,
358        &sector_metadata.s_bucket_offsets(),
359        &sector_contents_map,
360        &table_generator.create_proofs(&sector_id.derive_evaluation_seed(piece_offset)),
361        sector,
362    )
363    .await?;
364    // Restore source record scalars
365    let record = recover_source_record(&mut sector_record_chunks, piece_offset, erasure_coding)?;
366
367    let RecordMetadata {
368        piece_header,
369        piece_checksum,
370    } = read_record_metadata(piece_offset, pieces_in_sector, sector).await?;
371
372    let piece = Piece::from_parts(&piece_header, record);
373
374    // Verify checksum
375    let actual_checksum = Blake3Hash::from(blake3::hash(piece.as_ref()));
376    if actual_checksum != piece_checksum {
377        debug!(
378            ?sector_id,
379            %piece_offset,
380            %actual_checksum,
381            expected_checksum = %piece_checksum,
382            "Hash doesn't match, plotted piece is corrupted"
383        );
384
385        return Err(ReadingError::ChecksumMismatch);
386    }
387
388    Ok(piece)
389}