Skip to main content

ab_proof_of_space/
chiapos.rs

1//! Chia proof of space reimplementation in Rust
2
3mod constants;
4mod table;
5#[cfg(all(feature = "alloc", test))]
6mod tests;
7
8#[cfg(feature = "alloc")]
9use crate::PosProofs;
10use crate::chiapos::constants::NUM_TABLES;
11#[cfg(feature = "alloc")]
12use crate::chiapos::table::types::Position;
13use crate::chiapos::table::types::{Metadata, X, Y};
14#[cfg(feature = "alloc")]
15use crate::chiapos::table::{PrunedTable, Table};
16use crate::chiapos::table::{compute_f1, compute_fn, has_match};
17#[cfg(feature = "alloc")]
18use ab_core_primitives::pieces::Record;
19#[cfg(feature = "alloc")]
20use ab_core_primitives::pos::PosProof;
21#[cfg(feature = "alloc")]
22use ab_core_primitives::sectors::SBucket;
23#[cfg(feature = "alloc")]
24use alloc::boxed::Box;
25#[cfg(feature = "alloc")]
26use array_reshape::Flatten;
27use core::mem::MaybeUninit;
28#[cfg(feature = "alloc")]
29use core::mem::offset_of;
30use core::{array, hint};
31#[cfg(feature = "parallel")]
32use rayon::prelude::*;
33#[cfg(any(feature = "full-chiapos", test))]
34use sha2::{Digest, Sha256};
35
36/// Supported K values for Chia proof of space tables
37pub impl(self) trait SupportedKValue {}
38
39/// Size of the proof in bytes for a given `K` value
40pub const PROOF_SIZE<const K: u8>: usize =
41    2usize.pow(u32::from(NUM_TABLES - 1)) * usize::from(K) / u8::BITS as usize;
42
43/// Proof-of-space proofs
44#[derive(Debug)]
45#[cfg(feature = "alloc")]
46#[repr(C)]
47pub struct Proofs<const K: u8> {
48    /// S-buckets at which proofs were found.
49    ///
50    /// S-buckets are grouped by 8, within each `u8` bits right to left (LSB) indicate the presence
51    /// of a proof for corresponding s-bucket, so that the whole array of bytes can be thought as a
52    /// large set of bits.
53    ///
54    /// There are always exactly [`Record::NUM_CHUNKS`] proofs produced/bits set to `1`. This is a
55    /// protected invariant. [`Proofs::for_s_bucket()`] relies on it, and so does plotting in the
56    /// farmer, which encodes every record chunk with one of these proofs. Some of them may be
57    /// [`Proofs::PLACEHOLDER_PROOF`].
58    pub mut(self) found_proofs: [u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
59    /// [`Record::NUM_CHUNKS`] proofs, corresponding to set bits of `found_proofs`.
60    pub mut(self) proofs: [[u8; PROOF_SIZE::<K>]; const { Record::NUM_CHUNKS }],
61}
62
63#[cfg(feature = "alloc")]
64impl From<Box<Proofs<const { PosProof::K }>>> for Box<PosProofs> {
65    // TODO: `no_panic::no_panic` fails to parse const generic arguments
66    // #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
67    fn from(proofs: Box<Proofs<const { PosProof::K }>>) -> Self {
68        // Statically ensure types are the same
69        const {
70            assert!(size_of::<Proofs<const { PosProof::K }>>() == size_of::<PosProofs>());
71            assert!(align_of::<Proofs<const { PosProof::K }>>() == align_of::<PosProofs>());
72            assert!(
73                offset_of!(Proofs<const { PosProof::K }>, found_proofs)
74                    == offset_of!(PosProofs, found_proofs)
75            );
76            assert!(
77                offset_of!(Proofs<const { PosProof::K }>, proofs) == offset_of!(PosProofs, proofs)
78            );
79        }
80        // SAFETY: Both structs have an identical layout with `#[repr(C)]` internals
81        unsafe { Box::from_raw(Box::into_raw(proofs).cast()) }
82    }
83}
84
85#[cfg(feature = "alloc")]
86impl<const K: u8> Proofs<K> {
87    /// Proof for s-buckets that are marked as having a proof without actually having one.
88    ///
89    /// There are always exactly [`Record::NUM_CHUNKS`] proofs, but very rarely fewer s-buckets have
90    /// a proof (roughly once in `2^40` seeds for `K = 20`). Then the first s-buckets without a
91    /// proof are marked as having this all-zero one instead. It can be used for encoding like any
92    /// other proof, but it is not a valid proof.
93    pub const PLACEHOLDER_PROOF: [u8; PROOF_SIZE::<K>] = [0; PROOF_SIZE::<K>];
94
95    /// Get proof for specified s-bucket (if exists).
96    ///
97    /// Note that this is not the most efficient API possible, so prefer using the `proofs` field
98    /// directly if the use case allows.
99    #[inline]
100    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
101    pub fn for_s_bucket(&self, s_bucket: SBucket) -> Option<[u8; PROOF_SIZE::<K>]> {
102        let proof_index = PosProofs::proof_index_for_s_bucket(&self.found_proofs, s_bucket)?;
103
104        // SAFETY: Protected invariant of the data structure
105        unsafe {
106            hint::assert_unchecked(proof_index < Record::NUM_CHUNKS);
107        }
108
109        Some(self.proofs[proof_index])
110    }
111
112    /// Initialize `found_proofs` with zeroes and return both fields separately so that proofs can
113    /// be written into still uninitialized `proofs`
114    #[inline(always)]
115    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
116    fn split_uninit(
117        proofs: &mut MaybeUninit<Self>,
118    ) -> (
119        &mut [u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
120        &mut [MaybeUninit<[u8; PROOF_SIZE::<K>]>; const { Record::NUM_CHUNKS }],
121    ) {
122        let proofs_ptr = proofs.as_mut_ptr();
123        // SAFETY: This is the correct way to access uninit reference to the inner field
124        let found_proofs = unsafe {
125            (&raw mut (*proofs_ptr).found_proofs)
126                .as_uninit_mut()
127                .expect("Not null; qed")
128        };
129        let found_proofs = found_proofs.write([0; _]);
130        // SAFETY: This is the correct way to access uninit reference to the inner field
131        let proofs = unsafe {
132            (&raw mut (*proofs_ptr).proofs)
133                .cast::<[MaybeUninit<_>; const { Record::NUM_CHUNKS }]>()
134                .as_mut_unchecked()
135        };
136
137        (found_proofs, proofs)
138    }
139}
140
141type Seed = [u8; 32];
142#[cfg(any(feature = "full-chiapos", test))]
143type Challenge = [u8; 32];
144#[cfg(any(feature = "full-chiapos", test))]
145type Quality = [u8; 32];
146
147/// Pick position in `table_number` based on challenge bits
148#[cfg(all(feature = "alloc", any(feature = "full-chiapos", test)))]
149const fn pick_position(
150    [left_position, right_position]: [Position; 2],
151    last_5_challenge_bits: u8,
152    table_number: u8,
153) -> Position {
154    if ((last_5_challenge_bits >> (table_number - 2)) & 1) == 0 {
155        left_position
156    } else {
157        right_position
158    }
159}
160
161/// Number of positions after expanding each of `N` positions into a pair
162#[cfg(feature = "alloc")]
163const EXPANDED_POSITIONS<const N: usize>: usize = N * 2;
164
165/// Expand each position into the pair of positions in the parent table it was derived from
166#[cfg(feature = "alloc")]
167#[inline(always)]
168#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
169fn expand_positions<const N: usize>(
170    positions: [Position; N],
171    expand: impl Fn(Position) -> [Position; 2],
172) -> [Position; EXPANDED_POSITIONS::<N>] {
173    positions.map(expand).flatten()
174}
175
176/// Number of s-buckets without a target in the last table that get [`Proofs::PLACEHOLDER_PROOF`],
177/// such that there are exactly [`Record::NUM_CHUNKS`] proofs in total
178#[cfg(feature = "alloc")]
179#[inline(always)]
180#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
181fn num_placeholder_proofs(
182    table_6_proof_targets: &[[Position; 2]; const { Record::NUM_S_BUCKETS }],
183) -> usize {
184    let num_targets = table_6_proof_targets
185        .iter()
186        .filter(|&table_6_proof_targets| table_6_proof_targets != &[Position::ZERO; 2])
187        .count();
188
189    Record::NUM_CHUNKS.saturating_sub(num_targets)
190}
191
192/// Collection of Chia tables
193#[derive(Debug)]
194pub struct Tables<const K: u8>
195where
196    Self: SupportedKValue,
197{
198    #[cfg(feature = "alloc")]
199    table_2: PrunedTable<K, 2>,
200    #[cfg(feature = "alloc")]
201    table_3: PrunedTable<K, 3>,
202    #[cfg(feature = "alloc")]
203    table_4: PrunedTable<K, 4>,
204    #[cfg(feature = "alloc")]
205    table_5: PrunedTable<K, 5>,
206    #[cfg(feature = "alloc")]
207    table_6: PrunedTable<K, 6>,
208    #[cfg(feature = "alloc")]
209    table_7: Table<K, 7>,
210}
211
212impl<const K: u8> Tables<K>
213where
214    Self: SupportedKValue,
215{
216    /// Create Chia proof of space tables.
217    ///
218    /// There is also `Self::create_parallel()` that can achieve higher performance and lower
219    /// latency at the cost of lower CPU efficiency and higher memory usage.
220    #[cfg(all(feature = "alloc", any(feature = "full-chiapos", test)))]
221    pub fn create(seed: Seed) -> Self {
222        let table_1 = Table::<K, 1>::create(seed);
223        let (table_2, _) = Table::<K, 2>::create(table_1);
224        let (table_3, table_2) = Table::<K, 3>::create(table_2);
225        let (table_4, table_3) = Table::<K, 4>::create(table_3);
226        let (table_5, table_4) = Table::<K, 5>::create(table_4);
227        let (table_6, table_5) = Table::<K, 6>::create(table_5);
228        let (table_7, table_6) = Table::<K, 7>::create(table_6);
229
230        Self {
231            table_2,
232            table_3,
233            table_4,
234            table_5,
235            table_6,
236            table_7,
237        }
238    }
239
240    /// Create proofs.
241    ///
242    /// This is an optimized combination of `Self::create()` and `Self::find_proof()`.
243    ///
244    /// There is also `Self::create_proofs_parallel()` that can achieve higher performance and lower
245    /// latency at the cost of lower CPU efficiency and higher memory usage.
246    #[cfg(feature = "alloc")]
247    pub fn create_proofs(seed: Seed) -> Box<Proofs<K>> {
248        let table_1 = Table::<K, 1>::create(seed);
249        let (table_2, _) = Table::<K, 2>::create(table_1);
250        let (table_3, table_2) = Table::<K, 3>::create(table_2);
251        let (table_4, table_3) = Table::<K, 4>::create(table_3);
252        let (table_5, table_4) = Table::<K, 5>::create(table_4);
253        let (table_6, table_5) = Table::<K, 6>::create(table_5);
254        let (table_6_proof_targets, table_6) = Table::<K, 7>::create_proof_targets(table_6);
255
256        let mut proofs = Box::<Proofs<K>>::new_uninit();
257        Self::find_proofs_internal(
258            &table_2,
259            &table_3,
260            &table_4,
261            &table_5,
262            &table_6,
263            &table_6_proof_targets,
264            &mut proofs,
265        );
266
267        // SAFETY: `Proofs::split_uninit()` initialized `found_proofs`, and
268        // `Self::find_proofs_internal()` wrote all `Record::NUM_CHUNKS` proofs
269        unsafe { proofs.assume_init() }
270    }
271
272    /// Find a proof for each s-bucket that has a target in the last table, using
273    /// [`Proofs::PLACEHOLDER_PROOF`] where necessary to always write exactly [`Record::NUM_CHUNKS`]
274    /// proofs
275    // TODO: Rewrite this more efficiently
276    #[cfg(feature = "alloc")]
277    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
278    fn find_proofs_internal(
279        table_2: &PrunedTable<K, 2>,
280        table_3: &PrunedTable<K, 3>,
281        table_4: &PrunedTable<K, 4>,
282        table_5: &PrunedTable<K, 5>,
283        table_6: &PrunedTable<K, 6>,
284        table_6_proof_targets: &[[Position; 2]; const { Record::NUM_S_BUCKETS }],
285        proofs: &mut MaybeUninit<Proofs<K>>,
286    ) {
287        let (found_proofs, proofs) = Proofs::<K>::split_uninit(proofs);
288
289        let mut num_placeholder_proofs = num_placeholder_proofs(table_6_proof_targets);
290        let mut num_found_proofs = 0_usize;
291        'outer: for (table_6_proof_targets, found_proofs) in table_6_proof_targets
292            .as_chunks::<{ u8::BITS as usize }>()
293            .0
294            .iter()
295            .zip(found_proofs)
296        {
297            for (proof_offset, table_6_proof_targets) in table_6_proof_targets.iter().enumerate() {
298                let proof = if table_6_proof_targets != &[Position::ZERO; 2] {
299                    Self::find_proof_raw_internal(
300                        table_2,
301                        table_3,
302                        table_4,
303                        table_5,
304                        table_6,
305                        *table_6_proof_targets,
306                    )
307                } else if let Some(remaining) = num_placeholder_proofs.checked_sub(1) {
308                    num_placeholder_proofs = remaining;
309                    Proofs::<K>::PLACEHOLDER_PROOF
310                } else {
311                    continue;
312                };
313
314                *found_proofs |= 1 << proof_offset;
315
316                // TODO: Remove once https://github.com/rust-lang/rust/issues/162834 is resolved
317                // SAFETY: The loop is stopped as soon as `Record::NUM_CHUNKS` proofs are found
318                unsafe {
319                    hint::assert_unchecked(num_found_proofs < Record::NUM_CHUNKS);
320                }
321                proofs[num_found_proofs].write(proof);
322                num_found_proofs += 1;
323
324                if num_found_proofs == Record::NUM_CHUNKS {
325                    break 'outer;
326                }
327            }
328        }
329
330        // Targets and placeholders add up to at least `Record::NUM_CHUNKS`
331        debug_assert_eq!(num_found_proofs, Record::NUM_CHUNKS);
332    }
333
334    /// Almost the same as [`Self::create()`], but uses parallelism internally for better
335    /// performance and lower latency at the cost of lower CPU efficiency and higher memory usage
336    #[cfg(all(feature = "parallel", any(feature = "full-chiapos", test)))]
337    pub fn create_parallel(seed: Seed) -> Self {
338        let table_1 = Table::<K, 1>::create_parallel(seed);
339        let (table_2, _) = Table::<K, 2>::create_parallel(table_1);
340        let (table_3, table_2) = Table::<K, 3>::create_parallel(table_2);
341        let (table_4, table_3) = Table::<K, 4>::create_parallel(table_3);
342        let (table_5, table_4) = Table::<K, 5>::create_parallel(table_4);
343        let (table_6, table_5) = Table::<K, 6>::create_parallel(table_5);
344        let (table_7, table_6) = Table::<K, 7>::create_parallel(table_6);
345
346        Self {
347            table_2,
348            table_3,
349            table_4,
350            table_5,
351            table_6,
352            table_7,
353        }
354    }
355
356    /// Almost the same as [`Self::create_proofs()`], but uses parallelism internally for better
357    /// performance and lower latency at the cost of lower CPU efficiency and higher memory usage
358    #[cfg(feature = "parallel")]
359    pub fn create_proofs_parallel(seed: Seed) -> Box<Proofs<K>> {
360        let table_1 = Table::<K, 1>::create_parallel(seed);
361        let (table_2, _) = Table::<K, 2>::create_parallel(table_1);
362        let (table_3, table_2) = Table::<K, 3>::create_parallel(table_2);
363        let (table_4, table_3) = Table::<K, 4>::create_parallel(table_3);
364        let (table_5, table_4) = Table::<K, 5>::create_parallel(table_4);
365        let (table_6, table_5) = Table::<K, 6>::create_parallel(table_5);
366        let (table_6_proof_targets, table_6) =
367            Table::<K, 7>::create_proof_targets_parallel(table_6);
368
369        let mut proofs = Box::<Proofs<K>>::new_uninit();
370        // SAFETY: Contents is `MaybeUninit`
371        let mut targets = unsafe {
372            Box::<[MaybeUninit<[Position; 2]>; const { Record::NUM_CHUNKS }]>::new_uninit()
373                .assume_init()
374        };
375        {
376            let (found_proofs, proofs) = Proofs::<K>::split_uninit(&mut proofs);
377
378            // Deciding which s-buckets have a proof is cheap, so it is done sequentially, leaving
379            // only the expensive part below to do in parallel
380            let targets =
381                Self::collect_proof_targets(&table_6_proof_targets, found_proofs, &mut targets);
382
383            // Work items here are large enough that `rayon::broadcast()` with manual batching (as
384            // used elsewhere in this crate) measures the same, so the safe version is used
385            proofs
386                .par_iter_mut()
387                .zip(targets)
388                .for_each(|(proof, &table_6_proof_targets)| {
389                    proof.write(if table_6_proof_targets == [Position::ZERO; 2] {
390                        Proofs::<K>::PLACEHOLDER_PROOF
391                    } else {
392                        Self::find_proof_raw_internal(
393                            &table_2,
394                            &table_3,
395                            &table_4,
396                            &table_5,
397                            &table_6,
398                            table_6_proof_targets,
399                        )
400                    });
401                });
402        }
403
404        // SAFETY: `Proofs::split_uninit()` initialized `found_proofs`, and a proof was written for
405        // each of `Record::NUM_CHUNKS` collected targets
406        unsafe { proofs.assume_init() }
407    }
408
409    /// Collect targets in the last table for s-buckets that have a proof, which is the cheap
410    /// sequential part of [`Self::create_proofs_parallel()`].
411    ///
412    /// Exactly [`Record::NUM_CHUNKS`] targets are collected, s-buckets that get
413    /// [`Proofs::PLACEHOLDER_PROOF`] have `[Position::ZERO; 2]` as the target.
414    #[cfg(feature = "parallel")]
415    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
416    fn collect_proof_targets<'a>(
417        table_6_proof_targets: &[[Position; 2]; const { Record::NUM_S_BUCKETS }],
418        found_proofs: &mut [u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
419        targets: &'a mut [MaybeUninit<[Position; 2]>; const { Record::NUM_CHUNKS }],
420    ) -> &'a [[Position; 2]] {
421        let mut num_placeholder_proofs = num_placeholder_proofs(table_6_proof_targets);
422        let mut num_found_proofs = 0_usize;
423
424        'outer: for (table_6_proof_targets, found_proofs) in table_6_proof_targets
425            .as_chunks::<{ u8::BITS as usize }>()
426            .0
427            .iter()
428            .zip(found_proofs)
429        {
430            for (proof_offset, table_6_proof_targets) in table_6_proof_targets.iter().enumerate() {
431                if table_6_proof_targets == &[Position::ZERO; 2] {
432                    let Some(remaining) = num_placeholder_proofs.checked_sub(1) else {
433                        continue;
434                    };
435                    num_placeholder_proofs = remaining;
436                }
437
438                *found_proofs |= 1 << proof_offset;
439
440                // TODO: Remove once https://github.com/rust-lang/rust/issues/162834 is resolved
441                // SAFETY: The loop is stopped as soon as `Record::NUM_CHUNKS` targets are collected
442                unsafe {
443                    hint::assert_unchecked(num_found_proofs < Record::NUM_CHUNKS);
444                }
445                targets[num_found_proofs].write(*table_6_proof_targets);
446                num_found_proofs += 1;
447
448                if num_found_proofs == Record::NUM_CHUNKS {
449                    break 'outer;
450                }
451            }
452        }
453
454        // Targets and placeholders add up to at least `Record::NUM_CHUNKS`
455        debug_assert_eq!(num_found_proofs, Record::NUM_CHUNKS);
456
457        // SAFETY: Targets and placeholders add up to at least `Record::NUM_CHUNKS`, so all
458        // elements were initialized above
459        unsafe { targets.assume_init_ref() }
460    }
461
462    /// Find proof of space quality for a given challenge
463    #[cfg(all(feature = "alloc", any(feature = "full-chiapos", test)))]
464    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
465    pub fn find_quality<'a>(
466        &'a self,
467        challenge: &'a Challenge,
468    ) -> impl Iterator<Item = Quality> + 'a {
469        let last_5_challenge_bits = challenge[challenge.len() - 1] & 0b0001_1111;
470
471        let first_k_challenge_bits = u32::from_be_bytes(
472            challenge[..size_of::<u32>()]
473                .try_into()
474                .expect("Challenge is known to statically have enough bytes; qed"),
475        ) >> (u32::BITS as usize - usize::from(K));
476
477        // SAFETY: Bucket range is by definition in bounds
478        let bucket = unsafe {
479            self.table_7
480                .buckets()
481                .get_unchecked(Y::bucket_range_from_first_k_bits(first_k_challenge_bits))
482        };
483        // Iterate just over elements that are matching `first_k_challenge_bits` prefix
484        bucket
485            .iter()
486            .flat_map(move |positions| {
487                positions
488                    .iter()
489                    .take_while(|&&(position, _y)| position != Position::SENTINEL)
490                    .filter(move |&&(_position, y)| y.first_k_bits() == first_k_challenge_bits)
491            })
492            .map(move |&(position, _y)| {
493                // SAFETY: Internally generated positions that come from the parent table
494                let positions = unsafe { self.table_7.position(position) };
495                // SAFETY: Internally generated positions that come from the parent table
496                let positions = unsafe {
497                    self.table_6
498                        .position(pick_position(positions, last_5_challenge_bits, 6))
499                };
500                // SAFETY: Internally generated positions that come from the parent table
501                let positions = unsafe {
502                    self.table_5
503                        .position(pick_position(positions, last_5_challenge_bits, 5))
504                };
505                // SAFETY: Internally generated positions that come from the parent table
506                let positions = unsafe {
507                    self.table_4
508                        .position(pick_position(positions, last_5_challenge_bits, 4))
509                };
510                // SAFETY: Internally generated positions that come from the parent table
511                let positions = unsafe {
512                    self.table_3
513                        .position(pick_position(positions, last_5_challenge_bits, 3))
514                };
515                // SAFETY: Internally generated positions that come from the parent table
516                let [left_position, right_position] = unsafe {
517                    self.table_2
518                        .position(pick_position(positions, last_5_challenge_bits, 2))
519                };
520
521                // X matches position
522                let left_x = X::from(u32::from(left_position));
523                let right_x = X::from(u32::from(right_position));
524
525                let mut hasher = Sha256::new();
526                hasher.update(challenge);
527                let left_right_xs = (u64::from(left_x) << (u64::BITS as usize - usize::from(K)))
528                    | (u64::from(right_x) << (u64::BITS as usize - usize::from(K * 2)));
529                hasher.update(
530                    &left_right_xs.to_be_bytes()
531                        [..(usize::from(K) * 2).div_ceil(u8::BITS as usize)],
532                );
533                hasher.finalize().into()
534            })
535    }
536
537    /// Similar to `Self::find_proof()`, but takes the first `k` challenge bits in the least
538    /// significant bits of `u32` as a challenge instead
539    #[cfg(feature = "alloc")]
540    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
541    pub fn find_proof_raw(
542        &self,
543        first_k_challenge_bits: u32,
544    ) -> impl Iterator<Item = [u8; PROOF_SIZE::<K>]> + '_ {
545        // Iterate just over elements that are matching `first_k_challenge_bits` prefix
546        self.table_7
547            .buckets()
548            .get(Y::bucket_range_from_first_k_bits(first_k_challenge_bits))
549            .unwrap_or(&[])
550            .iter()
551            .flat_map(move |positions| {
552                positions
553                    .iter()
554                    .take_while(|&&(position, _y)| position != Position::SENTINEL)
555                    .filter(move |&&(_position, y)| y.first_k_bits() == first_k_challenge_bits)
556            })
557            .map(move |&(position, _y)| {
558                // SAFETY: Internally generated positions that come from the parent table
559                let table_6_proof_targets = unsafe { self.table_7.position(position) };
560
561                Self::find_proof_raw_internal(
562                    &self.table_2,
563                    &self.table_3,
564                    &self.table_4,
565                    &self.table_5,
566                    &self.table_6,
567                    table_6_proof_targets,
568                )
569            })
570    }
571
572    #[cfg(feature = "alloc")]
573    #[inline(always)]
574    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
575    fn find_proof_raw_internal(
576        table_2: &PrunedTable<K, 2>,
577        table_3: &PrunedTable<K, 3>,
578        table_4: &PrunedTable<K, 4>,
579        table_5: &PrunedTable<K, 5>,
580        table_6: &PrunedTable<K, 6>,
581        table_6_proof_targets: [Position; 2],
582    ) -> [u8; PROOF_SIZE::<K>] {
583        let mut proof = [0u8; _];
584
585        // Positions are expanded one table at a time rather than by walking the tree of positions
586        // depth-first. All lookups within a single table are independent of each other, which
587        // allows many of these cache misses to be in flight at the same time instead of waiting
588        // for each other. This mirrors [`Self::verify_only_raw()`], which walks the same tree in
589        // the opposite direction a table at a time for the same reason.
590        let positions = expand_positions(table_6_proof_targets, |position| {
591            // SAFETY: Internally generated positions that come from the parent table
592            unsafe { table_6.position(position) }
593        });
594        let positions = expand_positions(positions, |position| {
595            // SAFETY: Internally generated positions that come from the parent table
596            unsafe { table_5.position(position) }
597        });
598        let positions = expand_positions(positions, |position| {
599            // SAFETY: Internally generated positions that come from the parent table
600            unsafe { table_4.position(position) }
601        });
602        let positions = expand_positions(positions, |position| {
603            // SAFETY: Internally generated positions that come from the parent table
604            unsafe { table_3.position(position) }
605        });
606        let positions = expand_positions(positions, |position| {
607            // SAFETY: Internally generated positions that come from the parent table
608            unsafe { table_2.position(position) }
609        });
610
611        positions
612            .iter()
613            .map(|&position| {
614                // X matches position
615                X::from(u32::from(position))
616            })
617            .enumerate()
618            .for_each(|(offset, x)| {
619                let x_offset_in_bits = usize::from(K) * offset;
620                // Collect bytes where bits of `x` will be written
621                let proof_bytes = &mut proof[x_offset_in_bits / u8::BITS as usize..]
622                    [..(x_offset_in_bits % u8::BITS as usize + usize::from(K))
623                        .div_ceil(u8::BITS as usize)];
624
625                // Bits of `x` already shifted to the correct location as they will appear
626                // in `proof`
627                let x_shifted = u32::from(x)
628                    << (u32::BITS as usize
629                        - (usize::from(K) + x_offset_in_bits % u8::BITS as usize));
630
631                // TODO: Store proofs in words, like GPU version does
632                // Copy `x` bits into proof
633                x_shifted
634                    .to_be_bytes()
635                    .iter()
636                    .zip(proof_bytes)
637                    .for_each(|(from, to)| {
638                        *to |= from;
639                    });
640            });
641
642        proof
643    }
644
645    /// Find proof of space for a given challenge
646    #[cfg(all(feature = "alloc", any(feature = "full-chiapos", test)))]
647    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
648    pub fn find_proof(
649        &self,
650        first_challenge_bytes: [u8; 4],
651    ) -> impl Iterator<Item = [u8; PROOF_SIZE::<K>]> + '_ {
652        let first_k_challenge_bits =
653            u32::from_be_bytes(first_challenge_bytes) >> (u32::BITS as usize - usize::from(K));
654
655        self.find_proof_raw(first_k_challenge_bits)
656    }
657
658    /// Similar to `Self::verify()`, but takes the first `k` challenge bits in the least significant
659    /// bits of `u32` as a challenge instead and doesn't compute quality
660    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
661    pub fn verify_only_raw(
662        seed: &Seed,
663        first_k_challenge_bits: u32,
664        proof_of_space: &[u8; PROOF_SIZE::<K>],
665    ) -> bool {
666        let ys_and_metadata = array::from_fn::<_, 64, _>(|offset| {
667            let mut pre_x_bytes = 0u64.to_be_bytes();
668            let offset_in_bits = usize::from(K) * offset;
669            let bytes_to_copy =
670                (offset_in_bits % u8::BITS as usize + usize::from(K)).div_ceil(u8::BITS as usize);
671            // Copy full bytes that contain bits of `x`
672            pre_x_bytes[..bytes_to_copy].copy_from_slice(
673                &proof_of_space[offset_in_bits / u8::BITS as usize..][..bytes_to_copy],
674            );
675            // Extract `pre_x` whose last `K` bits start with `x`
676            let pre_x = u64::from_be_bytes(pre_x_bytes)
677                >> (u64::BITS as usize - (usize::from(K) + offset_in_bits % u8::BITS as usize));
678            // Convert to the desired type and clear extra bits
679            let x = X::from(pre_x as u32 & (u32::MAX >> (u32::BITS as usize - usize::from(K))));
680
681            let y = compute_f1::<K>(x, seed);
682
683            (y, Metadata::from(x))
684        });
685
686        let mut next_ys_and_metadata = [MaybeUninit::uninit(); _];
687        let ys_and_metadata =
688            Self::collect_ys_and_metadata::<2, 1, 64>(&ys_and_metadata, &mut next_ys_and_metadata);
689        let mut next_ys_and_metadata = [MaybeUninit::uninit(); _];
690        let ys_and_metadata =
691            Self::collect_ys_and_metadata::<3, 2, 32>(ys_and_metadata, &mut next_ys_and_metadata);
692        let mut next_ys_and_metadata = [MaybeUninit::uninit(); _];
693        let ys_and_metadata =
694            Self::collect_ys_and_metadata::<4, 3, 16>(ys_and_metadata, &mut next_ys_and_metadata);
695        let mut next_ys_and_metadata = [MaybeUninit::uninit(); _];
696        let ys_and_metadata =
697            Self::collect_ys_and_metadata::<5, 4, 8>(ys_and_metadata, &mut next_ys_and_metadata);
698        let mut next_ys_and_metadata = [MaybeUninit::uninit(); _];
699        let ys_and_metadata =
700            Self::collect_ys_and_metadata::<6, 5, 4>(ys_and_metadata, &mut next_ys_and_metadata);
701        let mut next_ys_and_metadata = [MaybeUninit::uninit(); _];
702        let ys_and_metadata =
703            Self::collect_ys_and_metadata::<7, 6, 2>(ys_and_metadata, &mut next_ys_and_metadata);
704
705        let Some((y, _metadata)) = ys_and_metadata.first() else {
706            return false;
707        };
708
709        // Check if the first K bits of `y` match
710        y.first_k_bits() == first_k_challenge_bits
711    }
712
713    /// Verify proof of space for a given seed and challenge
714    // TODO: `no_panic::no_panic` can't prove lack of panics in `sha2`
715    // #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
716    #[cfg(any(feature = "full-chiapos", test))]
717    pub fn verify(
718        seed: &Seed,
719        challenge: &Challenge,
720        proof_of_space: &[u8; PROOF_SIZE::<K>],
721    ) -> Option<Quality> {
722        let first_k_challenge_bits =
723            u32::from_be_bytes([challenge[0], challenge[1], challenge[2], challenge[3]])
724                >> (u32::BITS as usize - usize::from(K));
725
726        if !Self::verify_only_raw(seed, first_k_challenge_bits, proof_of_space) {
727            return None;
728        }
729
730        let last_5_challenge_bits = challenge[challenge.len() - 1] & 0b0001_1111;
731
732        let mut quality_index = 0_usize.to_be_bytes();
733        quality_index[0] = last_5_challenge_bits;
734        let quality_index = usize::from_be_bytes(quality_index);
735
736        // NOTE: this works correctly but may overflow if `quality_index` is changed to
737        // not be zero-initialized anymore
738        let left_right_xs_bit_offset = quality_index * usize::from(K * 2);
739        // Collect `left_x` and `right_x` bits, potentially with extra bits at the beginning
740        // and the end
741        let left_right_xs_bytes = &proof_of_space[left_right_xs_bit_offset / u8::BITS as usize..]
742            [..(left_right_xs_bit_offset % u8::BITS as usize + usize::from(K * 2))
743                .div_ceil(u8::BITS as usize)];
744
745        let mut left_right_xs = 0u64.to_be_bytes();
746        left_right_xs[..left_right_xs_bytes.len()].copy_from_slice(left_right_xs_bytes);
747        // Move `left_x` and `right_x` bits to most significant bits
748        let left_right_xs =
749            u64::from_be_bytes(left_right_xs) << (left_right_xs_bit_offset % u8::BITS as usize);
750        // Clear extra bits
751        let left_right_xs_mask = u64::MAX << (u64::BITS as usize - usize::from(K * 2));
752        let left_right_xs = left_right_xs & left_right_xs_mask;
753
754        let mut hasher = Sha256::new();
755        hasher.update(challenge);
756        hasher
757            .update(&left_right_xs.to_be_bytes()[..usize::from(K * 2).div_ceil(u8::BITS as usize)]);
758        Some(hasher.finalize().into())
759    }
760
761    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
762    fn collect_ys_and_metadata<
763        'a,
764        const TABLE_NUMBER: u8,
765        const PARENT_TABLE_NUMBER: u8,
766        const N: usize,
767    >(
768        ys_and_metadata: &[(Y, Metadata<K, PARENT_TABLE_NUMBER>)],
769        next_ys_and_metadata: &'a mut [MaybeUninit<(Y, Metadata<K, TABLE_NUMBER>)>; N],
770    ) -> &'a [(Y, Metadata<K, TABLE_NUMBER>)] {
771        let mut next_offset = 0_usize;
772        for &[(left_y, left_metadata), (right_y, right_metadata)] in
773            ys_and_metadata.as_chunks::<2>().0
774        {
775            if !has_match(left_y, right_y) {
776                continue;
777            }
778
779            // SAFETY: Inputs are limited to `N * 2` elements, and at most one match is produced for
780            // every two of them
781            unsafe {
782                hint::assert_unchecked(next_offset < N);
783            }
784            next_ys_and_metadata[next_offset].write(compute_fn::<
785                K,
786                TABLE_NUMBER,
787                PARENT_TABLE_NUMBER,
788            >(
789                left_y, left_metadata, right_metadata
790            ));
791            next_offset += 1;
792        }
793
794        // TODO: Remove once https://github.com/rust-lang/rust/issues/162834 is resolved
795        // SAFETY: Inputs are limited to `N * 2` elements, and at most one match is produced for
796        // every two of them
797        unsafe {
798            hint::assert_unchecked(next_offset <= N);
799        }
800
801        // SAFETY: Initialized `next_offset` elements
802        unsafe { next_ys_and_metadata[..next_offset].assume_init_ref() }
803    }
804}
805
806macro_rules! impl_supported {
807    ($($k: expr$(,)? )*) => {
808        $(
809impl SupportedKValue for Tables<$k> {}
810        )*
811    }
812}
813
814// Only these k values are supported by the current implementation
815#[cfg(feature = "full-chiapos")]
816impl_supported!(15, 16, 18, 19, 21, 22, 23, 24, 25);
817#[cfg(any(feature = "full-chiapos", test))]
818impl_supported!(17);
819impl_supported!(20);