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