Skip to content

Commit

Permalink
implementing GrindingChallenger, CanSampleBits and CanObserve<T> for …
Browse files Browse the repository at this point in the history
…HashChallenger
  • Loading branch information
olegfomenko committed Jan 14, 2025
1 parent f20425d commit bd33b15
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
27 changes: 26 additions & 1 deletion challenger/src/grinding_challenger.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use core::cmp::min;
use p3_field::{Field, PrimeField, PrimeField32, PrimeField64};
use p3_maybe_rayon::prelude::*;
use p3_symmetric::CryptographicPermutation;
use tracing::instrument;

use crate::{CanObserve, CanSampleBits, DuplexChallenger, MultiField32Challenger};
use crate::{CanObserve, CanSampleBits, DuplexChallenger, HashChallenger, MultiField32Challenger};

pub trait GrindingChallenger:
CanObserve<Self::Witness> + CanSampleBits<usize> + Sync + Clone
Expand Down Expand Up @@ -59,3 +60,27 @@ where
witness
}
}

impl<F, P, const WIDTH: usize> GrindingChallenger for HashChallenger<F, P, WIDTH>
where
F: Field,
P: CryptographicPermutation<[F; WIDTH]>,
{
type Witness = F;

#[instrument(name = "grind for proof-of-work witness", skip_all)]
fn grind(&mut self, bits: usize) -> Self::Witness {
let mut upper_bound = u64::MAX;
if F::bits() < 64 {
upper_bound = *F::order().to_u64_digits().get(0).unwrap();
}

let witness = (0..upper_bound)
.into_par_iter()
.map(|i| F::from_canonical_u64(i))
.find_any(|witness| self.clone().check_witness(bits, *witness))
.expect("failed to find witness");
assert!(self.check_witness(bits, witness));
witness
}
}
24 changes: 22 additions & 2 deletions challenger/src/hash_challenger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ where
}

impl<T, H, const N: usize, const OUT_LEN: usize> CanObserve<[T; N]>
for HashChallenger<T, H, OUT_LEN>
for HashChallenger<T, H, OUT_LEN>
where
T: Clone,
H: CryptographicHasher<T, [T; OUT_LEN]>,
Expand All @@ -81,6 +81,26 @@ where
}
}

impl<F, P, const OUT_LEN: usize> CanSampleBits<usize> for HashChallenger<F, P, OUT_LEN>
where
F: Field,
P: CryptographicPermutation<[F; OUT_LEN]>,
{
fn sample_bits(&mut self, bits: usize) -> usize {
let rand_f: F = self.sample();
let rand_usize = rand_f.as_canonical_u32() as usize;
rand_usize & ((1 << bits) - 1)
}
}
impl<T, P, const OUT_LEN: usize> CanObserve<T> for HashChallenger<T, P, OUT_LEN>
where
P: CryptographicPermutation<[T; OUT_LEN]>,
{
fn observe(&mut self, v: T) {
self.observe(v);
}
}

impl<T, H, const OUT_LEN: usize> CanObserve<Vec<T>> for HashChallenger<T, H, OUT_LEN>
where
T: Clone,
Expand Down Expand Up @@ -199,4 +219,4 @@ mod tests {
[F::from_canonical_u8(new_expected_sum)]
)
}
}
}

0 comments on commit bd33b15

Please sign in to comment.