Skip to main content

ab_farmer_components/
auditing.rs

1//! Auditing utilities
2//!
3//! There is a way to both audit a single sector (primarily helpful for testing purposes) and the
4//! whole plot (which is heavily parallelized and much more efficient) created by functions in
5//! [`plotting`](crate::plotting) module earlier.
6
7use crate::proving::SolutionCandidates;
8use crate::sector::{SectorContentsMap, SectorMetadataChecksummed, sector_size};
9use crate::shard_commitment::ShardCommitmentsRootsCache;
10use crate::{ReadAtOffset, ReadAtSync};
11use ab_core_primitives::hashes::Blake3Hash;
12use ab_core_primitives::pieces::RecordChunk;
13use ab_core_primitives::sectors::{SBucket, SectorId, SectorIndex, SectorSlotChallenge};
14use ab_core_primitives::shard::NumShards;
15use ab_core_primitives::solutions::{ShardMembershipEntropy, SolutionDistance, SolutionRange};
16use ab_direct_io_file::OwnedPages;
17use rayon::prelude::*;
18use std::collections::HashSet;
19use std::{io, mem};
20use thiserror::Error;
21
22/// Errors that happen during proving
23#[derive(Debug, Error)]
24pub enum AuditingError {
25    /// Failed read s-bucket
26    #[error("Failed read s-bucket {s_bucket_audit_index} of sector {sector_index}: {error}")]
27    SBucketReading {
28        /// Sector index
29        sector_index: SectorIndex,
30        /// S-bucket audit index
31        s_bucket_audit_index: SBucket,
32        /// Low-level error
33        error: io::Error,
34    },
35}
36
37/// Result of sector audit
38#[derive(Debug, Clone)]
39pub struct AuditResult<'a, Sector> {
40    /// Sector index
41    pub sector_index: SectorIndex,
42    /// Solution candidates
43    pub solution_candidates: SolutionCandidates<'a, Sector>,
44}
45
46/// Chunk candidate, contains one or more winning audit chunks
47#[derive(Debug, Clone)]
48pub(crate) struct ChunkCandidate {
49    /// Chunk offset within s-bucket
50    pub(crate) chunk_offset: u32,
51    /// Solution distance of this chunk, which can be used to prioritize higher quality solutions
52    pub(crate) solution_distance: SolutionDistance,
53}
54
55/// Audit a single sector and generate a stream of solutions.
56///
57/// This is primarily helpful in test environment, prefer [`audit_plot_sync`] for auditing real
58/// plots.
59// TODO: Struct for arguments
60#[expect(clippy::too_many_arguments, reason = "TODO")]
61pub fn audit_sector_sync<'a, Sector>(
62    public_key_hash: &'a Blake3Hash,
63    shard_commitments_roots_cache: &'a ShardCommitmentsRootsCache,
64    shard_membership_entropy: ShardMembershipEntropy,
65    num_shards: NumShards,
66    global_challenge: &Blake3Hash,
67    solution_range: SolutionRange,
68    sector: Sector,
69    sector_metadata: &'a SectorMetadataChecksummed,
70) -> Result<Option<AuditResult<'a, Sector>>, AuditingError>
71where
72    Sector: ReadAtSync + 'a,
73{
74    let SectorAuditingDetails {
75        sector_id,
76        sector_slot_challenge,
77        s_bucket_audit_index,
78        s_bucket_audit_size,
79        s_bucket_audit_offset_in_sector,
80    } = collect_sector_auditing_details(
81        public_key_hash,
82        shard_commitments_roots_cache,
83        global_challenge,
84        sector_metadata,
85    );
86
87    let s_bucket = sector
88        .read_at(
89            OwnedPages::EMPTY,
90            s_bucket_audit_size,
91            s_bucket_audit_offset_in_sector,
92        )
93        .map_err(|error| AuditingError::SBucketReading {
94            sector_index: sector_metadata.sector_index,
95            s_bucket_audit_index,
96            error: error.into(),
97        })?;
98
99    let Some(winning_chunks) = map_winning_chunks(
100        &s_bucket,
101        global_challenge,
102        &sector_slot_challenge,
103        solution_range,
104    ) else {
105        return Ok(None);
106    };
107
108    Ok(Some(AuditResult {
109        sector_index: sector_metadata.sector_index,
110        solution_candidates: SolutionCandidates::new(
111            public_key_hash,
112            sector_id,
113            shard_commitments_roots_cache,
114            shard_membership_entropy,
115            num_shards,
116            s_bucket_audit_index,
117            sector,
118            sector_metadata,
119            winning_chunks.into(),
120        ),
121    }))
122}
123
124/// Audit the whole plot and generate streams of results.
125///
126/// Each audit result contains a solution candidate that might be converted into solution (but will
127/// not necessarily succeed, auditing only does quick checks and can't know for sure).
128///
129/// Plot is assumed to contain concatenated series of sectors as created by functions in
130/// [`plotting`](crate::plotting) module earlier.
131// TODO: Struct for arguments
132#[expect(clippy::too_many_arguments, reason = "TODO")]
133pub fn audit_plot_sync<'a, 'b, Plot>(
134    public_key_hash: &'a Blake3Hash,
135    shard_commitments_roots_cache: &'a ShardCommitmentsRootsCache,
136    shard_membership_entropy: ShardMembershipEntropy,
137    num_shards: NumShards,
138    global_challenge: &Blake3Hash,
139    solution_range: SolutionRange,
140    plot: &'a Plot,
141    sectors_metadata: &'a [SectorMetadataChecksummed],
142    sectors_being_modified: &'b HashSet<SectorIndex>,
143) -> Result<Vec<AuditResult<'a, ReadAtOffset<'a, Plot>>>, AuditingError>
144where
145    Plot: ReadAtSync + 'a,
146{
147    // Create auditing info for all sectors in parallel
148    sectors_metadata
149        .par_iter()
150        .map(|sector_metadata| {
151            (
152                collect_sector_auditing_details(
153                    public_key_hash,
154                    shard_commitments_roots_cache,
155                    global_challenge,
156                    sector_metadata,
157                ),
158                sector_metadata,
159            )
160        })
161        // Read s-buckets of all sectors, map to winning chunks and then to audit results, all in
162        // parallel, reusing a buffer for reads within each rayon job
163        .map_init(
164            || OwnedPages::EMPTY,
165            |buffer, (sector_auditing_info, sector_metadata)| {
166                if sectors_being_modified.contains(&sector_metadata.sector_index) {
167                    // Skip sector that is being modified right now
168                    return Ok(None);
169                }
170
171                if sector_auditing_info.s_bucket_audit_size == 0 {
172                    // S-bucket is empty
173                    return Ok(None);
174                }
175
176                let sector = plot.offset(
177                    u64::from(sector_metadata.sector_index)
178                        * sector_size(sector_metadata.pieces_in_sector) as u64,
179                );
180
181                let s_bucket = sector
182                    .read_at(
183                        mem::take(buffer),
184                        sector_auditing_info.s_bucket_audit_size,
185                        sector_auditing_info.s_bucket_audit_offset_in_sector,
186                    )
187                    .map_err(|error| {
188                        *buffer = error.buffer;
189                        AuditingError::SBucketReading {
190                            sector_index: sector_metadata.sector_index,
191                            s_bucket_audit_index: sector_auditing_info.s_bucket_audit_index,
192                            error: error.error.into(),
193                        }
194                    })?;
195
196                let maybe_winning_chunks = map_winning_chunks(
197                    &s_bucket,
198                    global_challenge,
199                    &sector_auditing_info.sector_slot_challenge,
200                    solution_range,
201                );
202                *buffer = s_bucket.into_empty();
203                let Some(winning_chunks) = maybe_winning_chunks else {
204                    return Ok(None);
205                };
206
207                Ok(Some(AuditResult {
208                    sector_index: sector_metadata.sector_index,
209                    solution_candidates: SolutionCandidates::new(
210                        public_key_hash,
211                        sector_auditing_info.sector_id,
212                        shard_commitments_roots_cache,
213                        shard_membership_entropy,
214                        num_shards,
215                        sector_auditing_info.s_bucket_audit_index,
216                        sector,
217                        sector_metadata,
218                        winning_chunks.into(),
219                    ),
220                }))
221            },
222        )
223        .filter_map(Result::transpose)
224        .collect()
225}
226
227struct SectorAuditingDetails {
228    sector_id: SectorId,
229    sector_slot_challenge: SectorSlotChallenge,
230    s_bucket_audit_index: SBucket,
231    /// Size in bytes
232    s_bucket_audit_size: u32,
233    /// Offset in bytes
234    s_bucket_audit_offset_in_sector: u64,
235}
236
237fn collect_sector_auditing_details(
238    public_key_hash: &Blake3Hash,
239    shard_commitments_roots_cache: &ShardCommitmentsRootsCache,
240    global_challenge: &Blake3Hash,
241    sector_metadata: &SectorMetadataChecksummed,
242) -> SectorAuditingDetails {
243    let sector_id = SectorId::new(
244        public_key_hash,
245        &shard_commitments_roots_cache.get(sector_metadata.history_size),
246        sector_metadata.sector_index,
247        sector_metadata.history_size,
248    );
249
250    let sector_slot_challenge = sector_id.derive_sector_slot_challenge(global_challenge);
251    let s_bucket_audit_index = sector_slot_challenge.s_bucket_audit_index();
252    let s_bucket_audit_size = RecordChunk::SIZE as u32
253        * u32::from(sector_metadata.s_bucket_sizes[usize::from(s_bucket_audit_index)]);
254    let s_bucket_audit_offset = RecordChunk::SIZE as u64
255        * sector_metadata
256            .s_bucket_sizes
257            .iter()
258            .take(s_bucket_audit_index.into())
259            .copied()
260            .map(u64::from)
261            .sum::<u64>();
262
263    let sector_contents_map_size =
264        SectorContentsMap::encoded_size(sector_metadata.pieces_in_sector);
265
266    let s_bucket_audit_offset_in_sector =
267        u64::from(sector_contents_map_size) + s_bucket_audit_offset;
268
269    SectorAuditingDetails {
270        sector_id,
271        sector_slot_challenge,
272        s_bucket_audit_index,
273        s_bucket_audit_size,
274        s_bucket_audit_offset_in_sector,
275    }
276}
277
278/// Map all winning chunks
279fn map_winning_chunks(
280    s_bucket: &[u8],
281    global_challenge: &Blake3Hash,
282    sector_slot_challenge: &SectorSlotChallenge,
283    solution_range: SolutionRange,
284) -> Option<Vec<ChunkCandidate>> {
285    // Map all winning chunks
286    let mut chunk_candidates = s_bucket
287        .as_chunks::<{ RecordChunk::SIZE }>()
288        .0
289        .iter()
290        .enumerate()
291        .filter_map(|(chunk_offset, chunk)| {
292            let solution_distance =
293                SolutionDistance::calculate(global_challenge, chunk, sector_slot_challenge);
294            solution_distance
295                .is_within(solution_range)
296                .then_some(ChunkCandidate {
297                    chunk_offset: chunk_offset as u32,
298                    solution_distance,
299                })
300        })
301        .collect::<Vec<_>>();
302
303    // Check if there are any solutions possible
304    if chunk_candidates.is_empty() {
305        return None;
306    }
307
308    chunk_candidates.sort_by_key(|chunk_candidate| chunk_candidate.solution_distance);
309
310    Some(chunk_candidates)
311}