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    generic_const_args,
10    generic_const_items,
11    inherent_associated_types,
12    min_generic_const_args,
13    step_trait
14)]
15#![cfg_attr(test, feature(float_erf))]
16#![cfg_attr(feature = "parallel", feature(exact_size_is_empty, sync_unsafe_cell))]
17#![cfg_attr(
18    feature = "alloc",
19    feature(iter_array_chunks, maybe_uninit_fill, ptr_as_uninit)
20)]
21#![cfg_attr(any(feature = "alloc", test), feature(portable_simd))]
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
40/// Proof of space table type
41#[derive(Debug, Clone, Copy)]
42pub enum PosTableType {
43    /// Chia table
44    Chia,
45    /// Shim table
46    Shim,
47}
48
49// TODO: Return a single full proof and the rest as hashes instead to optimize memory usage and
50//  parallelize compute more easily
51/// Proof-of-space proofs
52#[derive(Debug)]
53#[cfg(feature = "alloc")]
54#[repr(C)]
55pub struct PosProofs {
56    /// S-buckets at which proofs were found.
57    ///
58    /// S-buckets are grouped by 8, within each `u8` bits right to left (LSB) indicate the presence
59    /// of a proof for corresponding s-bucket, so that the whole array of bytes can be thought as a
60    /// large set of bits.
61    ///
62    /// There will be at most [`Record::NUM_CHUNKS`] proofs produced/bits set to `1`.
63    pub found_proofs: [u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
64    /// [`Record::NUM_CHUNKS`] proofs, corresponding to set bits of `found_proofs`.
65    pub proofs: [PosProof; const { Record::NUM_CHUNKS }],
66}
67
68// TODO: A method that returns hashed proofs (with SIMD) for all s-buckets for plotting
69#[cfg(feature = "alloc")]
70impl PosProofs {
71    /// Get proof for specified s-bucket (if exists).
72    ///
73    /// Note that this is not the most efficient API possible, so prefer using the `proofs` field
74    /// directly if the use case allows.
75    #[inline]
76    pub fn for_s_bucket(&self, s_bucket: SBucket) -> Option<PosProof> {
77        let proof_index = Self::proof_index_for_s_bucket(&self.found_proofs, s_bucket)?;
78
79        Some(self.proofs[proof_index])
80    }
81
82    #[inline(always)]
83    fn proof_index_for_s_bucket(
84        found_proofs: &[u8; Record::NUM_S_BUCKETS / u8::BITS as usize],
85        s_bucket: SBucket,
86    ) -> Option<usize> {
87        let bits_offset = usize::from(s_bucket);
88        let found_proofs_byte_offset = bits_offset / u8::BITS as usize;
89        let found_proofs_bit_offset = bits_offset as u32 % u8::BITS;
90        let (found_proofs_before, found_proofs_after) =
91            found_proofs.split_at(found_proofs_byte_offset);
92        if (found_proofs_after[0] & (1 << found_proofs_bit_offset)) == 0 {
93            return None;
94        }
95        let proof_index = found_proofs_before
96            .iter()
97            .map(|&bits| bits.count_ones())
98            .sum::<u32>()
99            + found_proofs_after[0]
100                .unbounded_shl(u8::BITS - found_proofs_bit_offset)
101                .count_ones();
102
103        Some(proof_index as usize)
104    }
105}
106
107// TODO: Think about redesigning this API now that proofs are the output rather than tables
108/// Stateful table generator with better performance.
109///
110/// Prefer cloning it over creating multiple separate generators.
111#[cfg(feature = "alloc")]
112pub trait TableGenerator<T: Table>:
113    fmt::Debug + Default + Clone + Send + Sync + Sized + 'static
114{
115    /// Create proofs with 32 bytes seed.
116    ///
117    /// There is also `Self::create_proofs_parallel()` that can achieve higher performance and
118    /// lower latency at the cost of lower CPU efficiency and higher memory usage.
119    fn create_proofs(&self, seed: &PosSeed) -> Box<PosProofs>;
120
121    /// Almost the same as [`Self::create_proofs()`], but uses parallelism internally for better
122    /// performance and lower latency at the cost of lower CPU efficiency and higher memory usage
123    #[cfg(feature = "parallel")]
124    fn create_proofs_parallel(&self, seed: &PosSeed) -> Box<PosProofs> {
125        self.create_proofs(seed)
126    }
127}
128
129/// Proof of space kind
130pub trait Table: SolutionPotVerifier + Sized + Send + Sync + 'static {
131    /// Proof of space table type
132    const TABLE_TYPE: PosTableType;
133    /// Instance that can be used to generate tables with better performance
134    #[cfg(feature = "alloc")]
135    type Generator: TableGenerator<Self>;
136
137    /// Check whether proof created earlier is valid
138    fn is_proof_valid(seed: &PosSeed, s_bucket: SBucket, proof: &PosProof) -> bool;
139
140    /// Returns a stateful table generator with better performance
141    #[cfg(feature = "alloc")]
142    fn generator() -> Self::Generator {
143        Self::Generator::default()
144    }
145}