Skip to main content

ab_proof_of_space/
lib.rs

1//! Proof of space implementation
2#![no_std]
3#![expect(incomplete_features, reason = "generic_const_*")]
4#![warn(rust_2018_idioms, missing_debug_implementations, missing_docs)]
5#![feature(
6    const_block_items,
7    const_convert,
8    const_trait_impl,
9    gca_const_items,
10    gca_macroless_args,
11    gca_min_const_items,
12    generic_const_items,
13    impl_restriction,
14    inherent_associated_types,
15    mut_restriction,
16    portable_simd,
17    step_trait
18)]
19#![cfg_attr(all(test, feature = "alloc"), feature(float_erf))]
20#![cfg_attr(feature = "parallel", feature(exact_size_is_empty, sync_unsafe_cell))]
21#![cfg_attr(feature = "alloc", feature(maybe_uninit_fill, ptr_as_uninit))]
22
23pub mod chia;
24pub mod chiapos;
25pub mod shim;
26
27#[cfg(feature = "alloc")]
28extern crate alloc;
29
30#[cfg(feature = "alloc")]
31use ab_core_primitives::pieces::Record;
32use ab_core_primitives::pos::{PosProof, PosSeed};
33use ab_core_primitives::sectors::SBucket;
34use ab_core_primitives::solutions::SolutionPotVerifier;
35#[cfg(feature = "alloc")]
36use alloc::boxed::Box;
37#[cfg(feature = "alloc")]
38use core::fmt;
39#[cfg(feature = "alloc")]
40use core::hint;
41
42/// Proof of space table type
43#[derive(Debug, Clone, Copy)]
44pub enum PosTableType {
45    /// Chia table
46    Chia,
47    /// Shim table
48    Shim,
49}
50
51// TODO: Return a single full proof and the rest as hashes instead to optimize memory usage and
52//  parallelize compute more easily
53/// Proof-of-space proofs
54#[derive(Debug)]
55#[cfg(feature = "alloc")]
56#[repr(C)]
57pub struct PosProofs {
58    /// S-buckets at which proofs were found.
59    ///
60    /// S-buckets are grouped by 8, within each `u8` bits right to left (LSB) indicate the presence
61    /// of a proof for corresponding s-bucket, so that the whole array of bytes can be thought as a
62    /// large set of bits.
63    ///
64    /// There are always exactly [`Record::NUM_CHUNKS`] proofs produced/bits set to `1`. This is a
65    /// protected invariant. [`PosProofs::for_s_bucket()`] relies on it, and so does plotting in
66    /// the farmer, which encodes every record chunk with one of these proofs. Some of them may be
67    /// [`PosProofs::PLACEHOLDER_PROOF`].
68    pub mut(self) found_proofs: [u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
69    /// [`Record::NUM_CHUNKS`] proofs, corresponding to set bits of `found_proofs`.
70    pub mut(self) proofs: [PosProof; const { Record::NUM_CHUNKS }],
71}
72
73// TODO: A method that returns hashed proofs (with SIMD) for all s-buckets for plotting
74#[cfg(feature = "alloc")]
75impl PosProofs {
76    /// Proof for s-buckets that are marked as having a proof without actually having one.
77    ///
78    /// Very rarely there are fewer s-buckets with a proof than [`Record::NUM_CHUNKS`]. Then the
79    /// first s-buckets without a proof are marked as having this one instead, which can be used for
80    /// encoding like any other proof, but it is not a valid proof.
81    pub const PLACEHOLDER_PROOF: [u8; PosProof::SIZE] = [0; PosProof::SIZE];
82
83    /// Get proof for specified s-bucket (if exists), which may be [`Self::PLACEHOLDER_PROOF`].
84    ///
85    /// Note that this is not the most efficient API possible, so prefer using the `proofs` field
86    /// directly if the use case allows.
87    #[inline]
88    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
89    pub fn for_s_bucket(&self, s_bucket: SBucket) -> Option<PosProof> {
90        let proof_index = Self::proof_index_for_s_bucket(&self.found_proofs, s_bucket)?;
91
92        // SAFETY: Protected invariant of the data structure
93        unsafe {
94            hint::assert_unchecked(proof_index < Record::NUM_CHUNKS);
95        }
96
97        Some(self.proofs[proof_index])
98    }
99
100    #[inline(always)]
101    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
102    fn proof_index_for_s_bucket(
103        found_proofs: &[u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
104        s_bucket: SBucket,
105    ) -> Option<usize> {
106        let bits_offset = usize::from(s_bucket);
107        let found_proofs_byte_offset = bits_offset / u8::BITS as usize;
108        let found_proofs_bit_offset = bits_offset as u32 % u8::BITS;
109        let (found_proofs_before, found_proofs_after) =
110            found_proofs.split_at(found_proofs_byte_offset);
111        if (found_proofs_after[0] & (1 << found_proofs_bit_offset)) == 0 {
112            return None;
113        }
114        let proof_index = found_proofs_before
115            .iter()
116            .map(|&bits| bits.count_ones())
117            .sum::<u32>()
118            + found_proofs_after[0]
119                .unbounded_shl(u8::BITS - found_proofs_bit_offset)
120                .count_ones();
121
122        Some(proof_index as usize)
123    }
124}
125
126// TODO: Think about redesigning this API now that proofs are the output rather than tables
127/// Stateful table generator with better performance.
128///
129/// Prefer cloning it over creating multiple separate generators.
130#[cfg(feature = "alloc")]
131pub trait TableGenerator<T: Table>:
132    fmt::Debug + Default + Clone + Send + Sync + Sized + 'static
133{
134    /// Create proofs with 32 bytes seed.
135    ///
136    /// There is also `Self::create_proofs_parallel()` that can achieve higher performance and
137    /// lower latency at the cost of lower CPU efficiency and higher memory usage.
138    fn create_proofs(&self, seed: &PosSeed) -> Box<PosProofs>;
139
140    /// Almost the same as [`Self::create_proofs()`], but uses parallelism internally for better
141    /// performance and lower latency at the cost of lower CPU efficiency and higher memory usage
142    #[cfg(feature = "parallel")]
143    fn create_proofs_parallel(&self, seed: &PosSeed) -> Box<PosProofs> {
144        self.create_proofs(seed)
145    }
146}
147
148/// Proof of space kind
149pub trait Table: SolutionPotVerifier + Sized + Send + Sync + 'static {
150    /// Proof of space table type
151    const TABLE_TYPE: PosTableType;
152    /// Instance that can be used to generate tables with better performance
153    #[cfg(feature = "alloc")]
154    type Generator: TableGenerator<Self>;
155
156    /// Check whether proof created earlier is valid
157    fn is_proof_valid(seed: &PosSeed, s_bucket: SBucket, proof: &PosProof) -> bool;
158
159    /// Returns a stateful table generator with better performance
160    #[cfg(feature = "alloc")]
161    fn generator() -> Self::Generator {
162        Self::Generator::default()
163    }
164}