Skip to main content

ab_farmer_components/
plotting.rs

1//! Plotting utilities
2//!
3//! This module contains functions and data structures that can be used for plotting purposes
4//! (primarily with CPU).
5//!
6//! Plotted sectors can be written to plot and later [`read`](crate::reading) and/or
7//! [`audited`](crate::auditing)/[`proven`](crate::proving) using other modules of this crate.
8
9use crate::FarmerProtocolInfo;
10use crate::sector::{
11    FoundProofs, RawSector, RecordMetadata, SectorContentsMap, SectorMetadata,
12    SectorMetadataChecksummed, sector_padding_size, sector_record_chunks_size,
13    sector_record_metadata_size, sector_size,
14};
15use crate::segment_reconstruction::recover_missing_piece;
16use ab_aligned_buffer::alignment::Align4096;
17use ab_aligned_buffer::{AllocationError, OwnedAlignedBuffer};
18use ab_core_primitives::hashes::Blake3Hash;
19use ab_core_primitives::pieces::{Piece, PieceIndex, PieceOffset, Record, RecordChunk};
20use ab_core_primitives::pos::PosSeed;
21use ab_core_primitives::sectors::{SBucket, SectorId, SectorIndex};
22use ab_core_primitives::segments::HistorySize;
23use ab_core_primitives::solutions::ShardCommitmentHash;
24use ab_data_retrieval::piece_getter::PieceGetter;
25use ab_erasure_coding::ErasureCoding;
26use ab_proof_of_space::{Table, TableGenerator};
27use async_lock::{Mutex as AsyncMutex, Semaphore};
28use backon::{ExponentialBuilder, Retryable};
29use futures::stream::FuturesUnordered;
30use futures::{StreamExt, select};
31use parity_scale_codec::{Decode, Encode};
32use parking_lot::Mutex;
33use std::collections::HashMap;
34use std::simd::Simd;
35use std::sync::Arc;
36use std::sync::atomic::{AtomicBool, Ordering};
37use std::time::Duration;
38use thiserror::Error;
39use tracing::{debug, trace, warn};
40
41const RECONSTRUCTION_CONCURRENCY_LIMIT: usize = 1;
42
43/// Information about sector that was plotted
44#[derive(Debug, Clone, Encode, Decode)]
45pub struct PlottedSector {
46    /// Sector ID
47    pub sector_id: SectorId,
48    /// Sector index
49    pub sector_index: SectorIndex,
50    /// Sector metadata
51    pub sector_metadata: SectorMetadataChecksummed,
52    /// Indexes of pieces that were plotted
53    pub piece_indexes: Vec<PieceIndex>,
54}
55
56/// Plotting status
57#[derive(Debug, Error)]
58pub enum PlottingError {
59    /// Records encoder error
60    #[error("Records encoder error: {error}")]
61    RecordsEncoderError {
62        /// Lower-level error
63        error: anyhow::Error,
64    },
65    /// Records encoder returned sector contents map for a wrong number of records
66    #[error(
67        "Records encoder returned sector contents map for {provided} records, expected {expected}"
68    )]
69    BadSectorContentsMapSize {
70        /// Number of records in the returned map
71        provided: usize,
72        /// Number of records in the sector
73        expected: usize,
74    },
75    /// Records encoder marked a wrong number of chunks as used in a record
76    #[error(
77        "Records encoder marked {provided} chunks of record {piece_offset} as used, expected \
78        {expected}"
79    )]
80    BadRecordChunksUsed {
81        /// Piece offset of the record
82        piece_offset: PieceOffset,
83        /// Number of chunks marked as used
84        provided: u32,
85        /// Expected number of chunks
86        expected: usize,
87    },
88    /// Failed to allocate sector output
89    #[error("Failed to allocate sector output of {sector_size} bytes: {error}")]
90    SectorAllocationFailed {
91        /// Size of the sector
92        sector_size: usize,
93        /// Lower-level error
94        error: AllocationError,
95    },
96    /// Bad sector output size
97    #[error("Bad sector output size: provided {provided}, expected {expected}")]
98    BadSectorOutputSize {
99        /// Actual size
100        provided: usize,
101        /// Expected size
102        expected: usize,
103    },
104    /// Can't recover missing piece
105    #[error("Can't recover missing piece {piece_index}: {error}")]
106    PieceRecoveryFailed {
107        /// Piece index
108        piece_index: PieceIndex,
109        /// Lower-level error
110        error: anyhow::Error,
111    },
112    /// Failed to retrieve piece
113    #[error("Failed to retrieve pieces: {error}")]
114    FailedToRetrievePieces {
115        /// Lower-level error
116        error: anyhow::Error,
117    },
118    /// Abort early
119    #[error("Abort early")]
120    AbortEarly,
121}
122
123/// Options for plotting a sector.
124///
125/// Sector output should be either empty (in which case it'll be resized to correct size
126/// automatically) or correctly sized from the beginning or else error will be returned.
127#[derive(Debug)]
128pub struct PlotSectorOptions<'a, RE, PG> {
129    /// Public key corresponding to sector
130    pub public_key_hash: &'a Blake3Hash,
131    /// Root of the Merkle Tree of shard commitments
132    pub shard_commitments_root: &'a ShardCommitmentHash,
133    /// Sector index
134    pub sector_index: SectorIndex,
135    /// Getter for pieces of archival history
136    pub piece_getter: &'a PG,
137    /// Farmer protocol info
138    pub farmer_protocol_info: FarmerProtocolInfo,
139    /// Erasure coding instance
140    pub erasure_coding: &'a ErasureCoding,
141    /// How many pieces should sector contain
142    pub pieces_in_sector: u16,
143    /// Where plotted sector should be written, buffer must either be empty (in which case it'll be
144    /// resized to correct size automatically) or correctly sized from the beginning.
145    ///
146    /// Contents of the buffer are aligned to the page size, so the sector can be written to disk
147    /// with direct I/O.
148    pub sector_output: &'a mut OwnedAlignedBuffer<Align4096>,
149    /// Semaphore for part of the plotting when farmer downloads new sector, allows to limit memory
150    /// usage of the plotting process, permit will be held until the end of the plotting process
151    pub downloading_semaphore: Option<Arc<Semaphore>>,
152    /// Semaphore for part of the plotting when farmer encodes downloaded sector, should typically
153    /// allow one permit at a time for efficient CPU utilization
154    pub encoding_semaphore: Option<&'a Semaphore>,
155    /// Proof of space table generators
156    pub records_encoder: &'a mut RE,
157    /// Whether encoding should be aborted early
158    pub abort_early: &'a AtomicBool,
159}
160
161/// Plot a single sector.
162///
163/// This is a convenient wrapper around [`download_sector`] and [`encode_sector`] functions.
164///
165/// NOTE: Even though this function is async, it has blocking code inside and must be running in a
166/// separate thread in order to prevent blocking an executor.
167pub async fn plot_sector<RE, PG>(
168    options: PlotSectorOptions<'_, RE, PG>,
169) -> Result<PlottedSector, PlottingError>
170where
171    RE: RecordsEncoder,
172    PG: PieceGetter + Send + Sync,
173{
174    let PlotSectorOptions {
175        public_key_hash,
176        shard_commitments_root,
177        sector_index,
178        piece_getter,
179        farmer_protocol_info,
180        erasure_coding,
181        pieces_in_sector,
182        sector_output,
183        downloading_semaphore,
184        encoding_semaphore,
185        records_encoder,
186        abort_early,
187    } = options;
188
189    let _downloading_permit = match downloading_semaphore {
190        Some(downloading_semaphore) => Some(downloading_semaphore.acquire_arc().await),
191        None => None,
192    };
193
194    let download_sector_fut = download_sector(DownloadSectorOptions {
195        public_key_hash,
196        shard_commitments_root,
197        sector_index,
198        piece_getter,
199        farmer_protocol_info,
200        erasure_coding,
201        pieces_in_sector,
202    });
203
204    let _encoding_permit = match encoding_semaphore {
205        Some(encoding_semaphore) => Some(encoding_semaphore.acquire().await),
206        None => None,
207    };
208
209    let encoded_sector = encode_sector(
210        download_sector_fut.await?,
211        EncodeSectorOptions::<RE> {
212            sector_index,
213            records_encoder,
214            abort_early,
215        },
216    )?;
217
218    write_sector(&encoded_sector, sector_output)?;
219
220    Ok(encoded_sector.plotted_sector)
221}
222
223/// Opaque sector downloading result and ready for writing
224#[derive(Debug)]
225pub struct DownloadedSector {
226    sector_id: SectorId,
227    piece_indices: Vec<PieceIndex>,
228    raw_sector: RawSector,
229    history_size: HistorySize,
230}
231
232/// Options for sector downloading
233#[derive(Debug)]
234pub struct DownloadSectorOptions<'a, PG> {
235    /// Public key corresponding to sector
236    pub public_key_hash: &'a Blake3Hash,
237    /// Root of the Merkle Tree of shard commitments
238    pub shard_commitments_root: &'a ShardCommitmentHash,
239    /// Sector index
240    pub sector_index: SectorIndex,
241    /// Getter for pieces of archival history
242    pub piece_getter: &'a PG,
243    /// Farmer protocol info
244    pub farmer_protocol_info: FarmerProtocolInfo,
245    /// Erasure coding instance
246    pub erasure_coding: &'a ErasureCoding,
247    /// How many pieces should sector contain
248    pub pieces_in_sector: u16,
249}
250
251/// Download sector for plotting.
252///
253/// This will identify necessary pieces and download them using provided piece getter, after which
254/// they can be encoded using [`encode_sector`] and written to the plot.
255pub async fn download_sector<PG>(
256    options: DownloadSectorOptions<'_, PG>,
257) -> Result<DownloadedSector, PlottingError>
258where
259    PG: PieceGetter + Send + Sync,
260{
261    let DownloadSectorOptions {
262        public_key_hash,
263        shard_commitments_root,
264        sector_index,
265        piece_getter,
266        farmer_protocol_info,
267        erasure_coding,
268        pieces_in_sector,
269    } = options;
270
271    let sector_id = SectorId::new(
272        public_key_hash,
273        shard_commitments_root,
274        sector_index,
275        farmer_protocol_info.history_size,
276    );
277
278    let piece_indices = (PieceOffset::ZERO..)
279        .take(pieces_in_sector.into())
280        .map(|piece_offset| {
281            sector_id.derive_piece_index(
282                piece_offset,
283                farmer_protocol_info.history_size,
284                farmer_protocol_info.max_pieces_in_sector,
285                farmer_protocol_info.recent_segments,
286                farmer_protocol_info.recent_history_fraction,
287            )
288        })
289        .collect::<Vec<_>>();
290
291    let raw_sector = {
292        let mut raw_sector = RawSector::new(pieces_in_sector);
293        let mut pieces_to_download =
294            HashMap::<PieceIndex, Vec<_>>::with_capacity(usize::from(pieces_in_sector));
295        for (piece_index, (record, metadata)) in piece_indices
296            .iter()
297            .copied()
298            .zip(raw_sector.records.iter_mut().zip(&mut raw_sector.metadata))
299        {
300            pieces_to_download
301                .entry(piece_index)
302                .or_default()
303                .push((record, metadata));
304        }
305        // This map will be mutated, removing piece indices we have already processed
306        let pieces_to_download = AsyncMutex::new(pieces_to_download);
307
308        (|| async {
309            let mut pieces_to_download = pieces_to_download.lock().await;
310
311            if let Err(error) =
312                download_sector_internal(&mut pieces_to_download, piece_getter, erasure_coding)
313                    .await
314            {
315                warn!(
316                    %sector_index,
317                    %error,
318                    %pieces_in_sector,
319                    remaining_pieces = %pieces_to_download.len(),
320                    "Sector downloading attempt failed, will retry later"
321                );
322
323                return Err(error);
324            }
325
326            debug!(%sector_index, "Sector downloaded successfully");
327
328            Ok(())
329        })
330        .retry(
331            ExponentialBuilder::default()
332                .with_min_delay(Duration::from_secs(15))
333                .with_max_delay(Duration::from_mins(10))
334                // Try until we get a valid piece
335                .without_max_times(),
336        )
337        .await?;
338
339        raw_sector
340    };
341
342    Ok(DownloadedSector {
343        sector_id,
344        piece_indices,
345        raw_sector,
346        history_size: farmer_protocol_info.history_size,
347    })
348}
349
350/// Records encoder for plotting purposes.
351///
352/// Each record is erasure coded and proofs of space are generated for it. The proofs must be the
353/// ones that [`TableGenerator::create_proofs()`] returns for
354/// `sector_id.derive_evaluation_seed(piece_offset)`, because reading and proving create them again
355/// the same way. There are exactly [`Record::NUM_CHUNKS`] of them. The record is then replaced
356/// with the chunks at the s-buckets of those proofs, each XORed with the hash of its proof, in
357/// s-bucket order. The returned sector contents map has one entry per record with a bit set for
358/// each of those s-buckets.
359///
360/// [`encode_sector()`] checks the number of entries and the number of bits in each entry, but not
361/// which bits are set. Bits that don't match the proofs result in a sector that can't be read or
362/// proven.
363pub trait RecordsEncoder {
364    /// Encode provided sector records.
365    ///
366    /// Encoding may stop early once `abort_early` is set. The returned map is not used in that
367    /// case.
368    fn encode_records(
369        &mut self,
370        sector_id: &SectorId,
371        records: &mut [Record],
372        abort_early: &AtomicBool,
373    ) -> anyhow::Result<SectorContentsMap>;
374}
375
376/// CPU implementation of [`RecordsEncoder`]
377#[derive(Debug)]
378pub struct CpuRecordsEncoder<'a, PosTable>
379where
380    PosTable: Table,
381{
382    table_generators: &'a [PosTable::Generator],
383    erasure_coding: &'a ErasureCoding,
384    global_mutex: &'a AsyncMutex<()>,
385}
386
387impl<PosTable> RecordsEncoder for CpuRecordsEncoder<'_, PosTable>
388where
389    PosTable: Table,
390{
391    fn encode_records(
392        &mut self,
393        sector_id: &SectorId,
394        records: &mut [Record],
395        abort_early: &AtomicBool,
396    ) -> anyhow::Result<SectorContentsMap> {
397        if self.table_generators.is_empty() {
398            return Err(anyhow::anyhow!("No table generators"));
399        }
400
401        let pieces_in_sector = records
402            .len()
403            .try_into()
404            .map_err(|error| anyhow::anyhow!("Failed to convert pieces in sector: {error}"))?;
405        let mut sector_contents_map = SectorContentsMap::new(pieces_in_sector);
406
407        {
408            let global_mutex = self.global_mutex;
409            let erasure_coding = self.erasure_coding;
410
411            let iter = Mutex::new(
412                (PieceOffset::ZERO..)
413                    .zip(records.iter_mut())
414                    .zip(sector_contents_map.iter_record_chunks_used_mut()),
415            );
416
417            rayon::scope(|scope| {
418                for table_generator in self.table_generators {
419                    scope.spawn(|_scope| {
420                        // Every record overwrites all parity chunks, so it is allocated just once
421                        let mut parity_record_chunks = Record::new_boxed();
422
423                        loop {
424                            // Take mutex briefly to make sure encoding is allowed right now
425                            global_mutex.lock_blocking();
426
427                            // This instead of `while` above because otherwise mutex will be held
428                            // for the duration of the loop and will limit concurrency to 1 record
429                            let Some(((piece_offset, record), record_chunks_used)) =
430                                iter.lock().next()
431                            else {
432                                return;
433                            };
434                            let pos_seed = sector_id.derive_evaluation_seed(piece_offset);
435
436                            record_encoding::<PosTable>(
437                                &pos_seed,
438                                record,
439                                &mut parity_record_chunks,
440                                record_chunks_used,
441                                table_generator,
442                                erasure_coding,
443                            );
444
445                            if abort_early.load(Ordering::Relaxed) {
446                                return;
447                            }
448                        }
449                    });
450                }
451            });
452        }
453
454        Ok(sector_contents_map)
455    }
456}
457
458impl<'a, PosTable> CpuRecordsEncoder<'a, PosTable>
459where
460    PosTable: Table,
461{
462    /// Create a new instance
463    pub fn new(
464        table_generators: &'a [PosTable::Generator],
465        erasure_coding: &'a ErasureCoding,
466        global_mutex: &'a AsyncMutex<()>,
467    ) -> Self {
468        Self {
469            table_generators,
470            erasure_coding,
471            global_mutex,
472        }
473    }
474}
475
476/// Options for encoding a sector
477#[derive(Debug)]
478pub struct EncodeSectorOptions<'a, RE>
479where
480    RE: RecordsEncoder,
481{
482    /// Sector index
483    pub sector_index: SectorIndex,
484    /// Records encoding instance
485    pub records_encoder: &'a mut RE,
486    /// Whether encoding should be aborted early
487    pub abort_early: &'a AtomicBool,
488}
489
490/// Mostly opaque sector encoding result ready for writing
491#[derive(Debug)]
492#[expect(
493    clippy::partial_pub_fields,
494    reason = "Intentionally hiding some fields such that they can only be used by internal APIs"
495)]
496pub struct EncodedSector {
497    /// Information about sector that was plotted
498    pub plotted_sector: PlottedSector,
499    raw_sector: RawSector,
500    sector_contents_map: SectorContentsMap,
501}
502
503/// Encode downloaded sector.
504///
505/// This function encodes downloaded sector records and returns sector encoding result that can be
506/// written using [`write_sector`].
507///
508/// Returns an error if the records encoder returns a sector contents map with a wrong number of
509/// entries or bits, see [`RecordsEncoder`].
510///
511/// Returns [`PlottingError::AbortEarly`] if `abort_early` is set once all the work is done, so the
512/// caller doesn't need to check it again. It takes precedence over the map errors above, because
513/// the map may be incomplete when encoding stopped early.
514pub fn encode_sector<RE>(
515    downloaded_sector: DownloadedSector,
516    encoding_options: EncodeSectorOptions<'_, RE>,
517) -> Result<EncodedSector, PlottingError>
518where
519    RE: RecordsEncoder,
520{
521    let DownloadedSector {
522        sector_id,
523        piece_indices,
524        mut raw_sector,
525        history_size,
526    } = downloaded_sector;
527    let EncodeSectorOptions {
528        sector_index,
529        records_encoder,
530        abort_early,
531    } = encoding_options;
532
533    let pieces_in_sector = raw_sector.records.len().try_into().expect(
534        "Raw sector can only be created in this crate and it is always done correctly; qed",
535    );
536
537    let sector_contents_map = records_encoder
538        .encode_records(&sector_id, &mut raw_sector.records, abort_early)
539        .map_err(|error| PlottingError::RecordsEncoderError { error })?;
540
541    let sector_metadata = SectorMetadataChecksummed::from(SectorMetadata {
542        sector_index,
543        pieces_in_sector,
544        s_bucket_sizes: sector_contents_map.s_bucket_sizes(),
545        history_size,
546    });
547
548    // An encoder that stopped early returns an incomplete map. That must result in `AbortEarly`
549    // and not in a map error, so the map is checked after this.
550    if abort_early.load(Ordering::Acquire) {
551        return Err(PlottingError::AbortEarly);
552    }
553
554    let record_chunks_used = sector_contents_map.iter_record_chunks_used();
555    if record_chunks_used.len() != raw_sector.records.len() {
556        return Err(PlottingError::BadSectorContentsMapSize {
557            provided: record_chunks_used.len(),
558            expected: raw_sector.records.len(),
559        });
560    }
561    for (record_chunks_used, piece_offset) in record_chunks_used.iter().zip(PieceOffset::ZERO..) {
562        let chunks_used = record_chunks_used
563            .iter()
564            .map(|bits| bits.count_ones())
565            .sum::<u32>();
566        if usize::try_from(chunks_used) != Ok(Record::NUM_CHUNKS) {
567            return Err(PlottingError::BadRecordChunksUsed {
568                piece_offset,
569                provided: chunks_used,
570                expected: Record::NUM_CHUNKS,
571            });
572        }
573    }
574
575    Ok(EncodedSector {
576        plotted_sector: PlottedSector {
577            sector_id,
578            sector_index,
579            sector_metadata,
580            piece_indexes: piece_indices,
581        },
582        raw_sector,
583        sector_contents_map,
584    })
585}
586
587/// Write encoded sector into sector output.
588///
589/// Sector output must either be empty (in which case it'll be resized to correct size
590/// automatically) or correctly sized from the beginning.
591pub fn write_sector(
592    encoded_sector: &EncodedSector,
593    sector_output: &mut OwnedAlignedBuffer<Align4096>,
594) -> Result<(), PlottingError> {
595    let EncodedSector {
596        plotted_sector: _,
597        raw_sector,
598        sector_contents_map,
599    } = encoded_sector;
600
601    let pieces_in_sector = raw_sector.records.len().try_into().expect(
602        "Raw sector can only be created in this crate and it is always done correctly; qed",
603    );
604
605    let sector_size = sector_size(pieces_in_sector);
606    let sector_size_u32 =
607        u32::try_from(sector_size).map_err(|_error| PlottingError::SectorAllocationFailed {
608            sector_size,
609            error: AllocationError::CapacityOverflow,
610        })?;
611
612    if !sector_output.is_empty() && sector_output.len() != sector_size_u32 {
613        return Err(PlottingError::BadSectorOutputSize {
614            provided: sector_output.len() as usize,
615            expected: sector_size,
616        });
617    }
618
619    // Every byte of the sector is written below, there is no need to initialize memory beforehand
620    sector_output.truncate(0);
621    sector_output
622        .try_ensure_capacity(sector_size_u32)
623        .map_err(|error| PlottingError::SectorAllocationFailed { sector_size, error })?;
624
625    // Write sector to disk in as the following regions:
626    // * sector contents map
627    // * record chunks as s-buckets
628    // * record metadata
629    // * zero padding
630    // * checksum
631    {
632        let (sector_contents_map_region, remaining_bytes) = sector_output
633            .spare_capacity_mut()
634            .split_at_mut(SectorContentsMap::encoded_size(pieces_in_sector) as usize);
635        // Slice remaining memory into belonging to s-buckets and metadata
636        let (s_buckets_region, remaining_bytes) =
637            remaining_bytes.split_at_mut(sector_record_chunks_size(pieces_in_sector));
638        let (metadata_region, remaining_bytes) =
639            remaining_bytes.split_at_mut(sector_record_metadata_size(pieces_in_sector));
640        let (padding_region, _remaining_bytes) =
641            remaining_bytes.split_at_mut(sector_padding_size(pieces_in_sector));
642
643        // Write sector contents map so we can decode it later
644        sector_contents_map
645            .encode_into(sector_contents_map_region)
646            .expect("Chunked into correct size above; qed");
647
648        let s_bucket_chunks = s_buckets_region.as_chunks_mut::<{ RecordChunk::SIZE }>().0;
649        let mut num_written_s_bucket_chunks = 0_usize;
650        let mut next_record_chunks_offset = vec![0usize; pieces_in_sector.into()];
651        // Write record chunks, one s-bucket at a time
652        for (piece_offset, output) in (SBucket::ZERO..=SBucket::MAX)
653            .flat_map(|s_bucket| {
654                sector_contents_map
655                    .iter_s_bucket_piece_offsets(s_bucket)
656                    .expect("S-bucket guaranteed to be in range; qed")
657            })
658            .zip(s_bucket_chunks)
659        {
660            let next_record_chunks_offset =
661                &mut next_record_chunks_offset[usize::from(piece_offset)];
662
663            let chunk_position = *next_record_chunks_offset;
664            *next_record_chunks_offset += 1;
665            output.write_copy_of_slice(
666                &raw_sector.records[usize::from(piece_offset)][chunk_position],
667            );
668            num_written_s_bucket_chunks += 1;
669        }
670        // Cheap check before exposing the memory as initialized below
671        assert_eq!(
672            num_written_s_bucket_chunks * RecordChunk::SIZE,
673            s_buckets_region.len(),
674            "Every record of an encoded sector has exactly `Record::NUM_CHUNKS` chunks used, which \
675            is checked in `encode_sector()`, so s-buckets cover all chunks of all records; qed"
676        );
677
678        let metadata_chunks = metadata_region
679            .as_chunks_mut::<{ RecordMetadata::encoded_size() }>()
680            .0;
681        let mut num_written_metadata_chunks = 0_usize;
682        for (record_metadata, output) in raw_sector.metadata.iter().zip(metadata_chunks) {
683            let mut record_metadata_bytes = [0; RecordMetadata::encoded_size()];
684            record_metadata.encode_to(&mut record_metadata_bytes.as_mut_slice());
685            output.write_copy_of_slice(&record_metadata_bytes);
686            num_written_metadata_chunks += 1;
687        }
688        // Cheap check before exposing the memory as initialized below
689        assert_eq!(
690            num_written_metadata_chunks * RecordMetadata::encoded_size(),
691            metadata_region.len(),
692            "Raw sector always has metadata for every record; qed"
693        );
694
695        padding_region.write_filled(0);
696    }
697
698    // SAFETY: The sector contents map is written by `encode_into()`, s-buckets and metadata regions
699    // are covered by contiguous chunks written from their beginning, which is checked above, the
700    // padding region is filled with zeroes, and together they are everything except the checksum.
701    // The capacity was reserved above.
702    unsafe {
703        sector_output.set_len(sector_size_u32 - Blake3Hash::SIZE as u32);
704    }
705
706    // It would be more efficient to not re-read the whole sector again, but it makes above code
707    // significantly more convoluted and most likely not worth it
708    let sector_checksum = {
709        let mut hasher = blake3::Hasher::new();
710        hasher.update_rayon(sector_output.as_slice());
711        hasher.finalize()
712    };
713    // Doesn't reallocate, the capacity was reserved above
714    sector_output
715        .append(sector_checksum.as_bytes())
716        .expect("Capacity for the whole sector was reserved above; qed");
717
718    Ok(())
719}
720
721fn record_encoding<PosTable>(
722    pos_seed: &PosSeed,
723    record: &mut Record,
724    parity_record_chunks: &mut Record,
725    record_chunks_used: &mut FoundProofs,
726    table_generator: &PosTable::Generator,
727    erasure_coding: &ErasureCoding,
728) where
729    PosTable: Table,
730{
731    let pos_proofs = table_generator.create_proofs_parallel(pos_seed);
732
733    // Erasure code source record chunks
734    erasure_coding
735        .extend(record, parity_record_chunks)
736        .expect("Statically guaranteed valid inputs; qed");
737
738    *record_chunks_used = pos_proofs.found_proofs;
739
740    // TODO: This can probably be optimized by using SIMD
741    let mut num_found_proofs = 0_usize;
742    for (s_buckets, found_proofs) in (0..Record::NUM_S_BUCKETS)
743        .array_chunks::<{ u8::BITS as usize }>()
744        .zip(pos_proofs.found_proofs)
745    {
746        for (proof_offset, s_bucket) in s_buckets.into_iter().enumerate() {
747            if (found_proofs & (1 << proof_offset)) != 0 {
748                let record_chunk = if s_bucket < Record::NUM_CHUNKS {
749                    record[s_bucket]
750                } else {
751                    parity_record_chunks[s_bucket - Record::NUM_CHUNKS]
752                };
753                // TODO: SIMD hashing
754                record[num_found_proofs] = (Simd::from(record_chunk)
755                    ^ Simd::from(*pos_proofs.proofs[num_found_proofs].hash()))
756                .to_array();
757                num_found_proofs += 1;
758            }
759        }
760    }
761}
762
763async fn download_sector_internal<PG>(
764    pieces_to_download: &mut HashMap<PieceIndex, Vec<(&mut Record, &mut RecordMetadata)>>,
765    piece_getter: &PG,
766    erasure_coding: &ErasureCoding,
767) -> Result<(), PlottingError>
768where
769    PG: PieceGetter + Send + Sync,
770{
771    // TODO: Make configurable, likely allowing user to specify RAM usage expectations and inferring
772    //  concurrency from there
773    let recovery_semaphore = &Semaphore::new(RECONSTRUCTION_CONCURRENCY_LIMIT);
774
775    // Allocate to decouple lifetime from `pieces_to_download` that will be modified below
776    let piece_indices = pieces_to_download.keys().copied().collect::<Vec<_>>();
777    let mut downloaded_pieces = piece_getter
778        .get_pieces(piece_indices)
779        .await
780        .map_err(|error| PlottingError::FailedToRetrievePieces { error })?
781        .fuse();
782    let mut reconstructed_pieces = FuturesUnordered::new();
783
784    let mut final_result = Ok(());
785
786    loop {
787        let (piece_index, result) = select! {
788            (piece_index, result) = downloaded_pieces.select_next_some() => {
789                match result {
790                    Ok(Some(piece)) => (piece_index, Ok(piece)),
791                    Ok(None) => {
792                        trace!(%piece_index, "Piece was not found, trying reconstruction");
793
794                        reconstructed_pieces.push(reconstruct_piece(
795                            piece_index,
796                            recovery_semaphore,
797                            piece_getter,
798                            erasure_coding,
799                        ));
800                        continue;
801                    }
802                    Err(error) => {
803                        trace!(
804                            %error,
805                            %piece_index,
806                            "Failed to download piece, trying reconstruction"
807                        );
808
809                        reconstructed_pieces.push(reconstruct_piece(
810                            piece_index,
811                            recovery_semaphore,
812                            piece_getter,
813                            erasure_coding,
814                        ));
815                        continue;
816                    }
817                }
818            },
819            (piece_index, result) = reconstructed_pieces.select_next_some() => {
820                (piece_index, result)
821            },
822            complete => {
823                break;
824            }
825        };
826
827        match result {
828            Ok(piece) => {
829                process_piece(piece_index, piece, pieces_to_download);
830            }
831            Err(error) => {
832                trace!(%error, %piece_index, "Failed to download piece");
833
834                if final_result.is_ok() {
835                    final_result = Err(error);
836                }
837            }
838        }
839    }
840
841    if final_result.is_ok() && !pieces_to_download.is_empty() {
842        return Err(PlottingError::FailedToRetrievePieces {
843            error: anyhow::anyhow!(
844                "Successful result, but not all pieces were downloaded, this is likely a piece \
845                getter implementation bug"
846            ),
847        });
848    }
849
850    final_result
851}
852
853async fn reconstruct_piece<PG>(
854    piece_index: PieceIndex,
855    recovery_semaphore: &Semaphore,
856    piece_getter: &PG,
857    erasure_coding: &ErasureCoding,
858) -> (PieceIndex, Result<Piece, PlottingError>)
859where
860    PG: PieceGetter + Send + Sync,
861{
862    let _permit = recovery_semaphore.acquire().await;
863    let recovered_piece_fut =
864        recover_missing_piece(piece_getter, erasure_coding.clone(), piece_index);
865
866    (
867        piece_index,
868        recovered_piece_fut
869            .await
870            .map_err(|error| PlottingError::PieceRecoveryFailed {
871                piece_index,
872                error: error.into(),
873            }),
874    )
875}
876
877fn process_piece(
878    piece_index: PieceIndex,
879    piece: Piece,
880    pieces_to_download: &mut HashMap<PieceIndex, Vec<(&mut Record, &mut RecordMetadata)>>,
881) {
882    for (record, metadata) in pieces_to_download.remove(&piece_index).unwrap_or_default() {
883        *metadata = RecordMetadata {
884            piece_header: piece.header,
885            piece_checksum: blake3::hash(piece.as_ref()).into(),
886        };
887        // Fancy way to insert value to avoid going through stack (if naive dereferencing is used)
888        // and potentially causing stack overflow as the result
889        record.copy_from_slice(&*piece.record);
890    }
891}