Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add u32 related hash functions #27

Merged
merged 6 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions blake3/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ license = "MIT OR Apache-2.0"
[dependencies]
p3-symmetric = { path = "../symmetric" }
blake3 = "1.5"
blake3_zkvm = { git = "https://github.com/sp1-patches/BLAKE3.git", branch = "patch-blake3_zkvm/v.1.0.0" }

[features]
neon = ["blake3/neon"]
Expand Down
32 changes: 32 additions & 0 deletions blake3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,35 @@ impl CryptographicHasher<u8, [u8; 32]> for Blake3 {
hasher.finalize().into()
}
}

impl CryptographicHasher<u32, [u32; 8]> for Blake3 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that we should have another struct Blake3zk or something that uses our precompiles, it could even be in the sp1 recursion crate. The reason is that we would eventually want the normal Blake3 to implement hashing on u32 (this might be useful for SIMD utilization. of the prover)

fn hash_iter<I>(&self, input: I) -> [u32; 8]
where
I: IntoIterator<Item = u32>,
{
let mut input = input.into_iter().collect::<Vec<_>>();
if input.len() <= blake3_zkvm::BLOCK_LEN {
let size = input.len();
input.resize(blake3_zkvm::BLOCK_LEN, 0u32);
blake3_zkvm::hash_single_block(input.as_slice().try_into().unwrap(), size)
} else {
let ret = self.hash_iter_slices([input.as_slice()]);
ret
}
}

fn hash_iter_slices<'a, I>(&self, input: I) -> [u32; 8]
where
I: IntoIterator<Item = &'a [u32]>,
{
let mut zkvm_hasher = blake3_zkvm::Hasher::new();

for chunk in input.into_iter() {
zkvm_hasher.update(chunk);
}
let mut out: [u32; 8] = [0u32; 8];
zkvm_hasher.finalize(&mut out);

out
}
}
127 changes: 93 additions & 34 deletions challenger/src/serializing_challenger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ use crate::{
/// - Samples a field element in a prime field of size `p` by sampling uniformly an element in the
/// range (0..1 << log_2(p)). This avoids modulo bias.
#[derive(Clone, Debug)]
pub struct SerializingChallenger32<F, Inner> {
pub struct SerializingChallenger32<F, T, Inner> {
tamirhemo marked this conversation as resolved.
Show resolved Hide resolved
inner: Inner,
_marker: PhantomData<F>,
_marker: PhantomData<(F, T)>,
}

/// Given a challenger that can observe and sample bytes, produces a challenger that is able to
Expand All @@ -41,7 +41,7 @@ pub struct SerializingChallenger64<F, Inner> {
_marker: PhantomData<F>,
}

impl<F: PrimeField32, Inner: CanObserve<u8>> SerializingChallenger32<F, Inner> {
impl<F: PrimeField32, T, Inner: CanObserve<T>> SerializingChallenger32<F, T, Inner> {
pub fn new(inner: Inner) -> Self {
Self {
inner,
Expand All @@ -50,56 +50,77 @@ impl<F: PrimeField32, Inner: CanObserve<u8>> SerializingChallenger32<F, Inner> {
}
}

impl<F, H> SerializingChallenger32<F, HashChallenger<u8, H, 32>>
impl<F, T, H, const N: usize> SerializingChallenger32<F, T, HashChallenger<T, H, N>>
where
F: PrimeField32,
H: CryptographicHasher<u8, [u8; 32]>,
H: CryptographicHasher<T, [T; N]>,
T: Clone,
{
pub fn from_hasher(initial_state: Vec<u8>, hasher: H) -> Self {
pub fn from_hasher(initial_state: Vec<T>, hasher: H) -> Self {
Self::new(HashChallenger::new(initial_state, hasher))
}
}

impl<F: PrimeField32, Inner: CanObserve<u8>> CanObserve<F> for SerializingChallenger32<F, Inner> {
impl<F: PrimeField32, Inner: CanObserve<u8>> CanObserve<F> for SerializingChallenger32<F, u8, Inner> {
fn observe(&mut self, value: F) {
self.inner
.observe_slice(&value.as_canonical_u32().to_le_bytes());
}
}

impl<F: PrimeField32, const N: usize, Inner: CanObserve<u8>> CanObserve<Hash<F, u8, N>>
for SerializingChallenger32<F, Inner>
impl<F: PrimeField32, Inner: CanObserve<u32>> CanObserve<F> for SerializingChallenger32<F, u32, Inner> {
fn observe(&mut self, value: F) {
self.inner
.observe(value.as_canonical_u32());
}
}

impl<F: PrimeField32, T, const N: usize, Inner: CanObserve<T>> CanObserve<Hash<F, T, N>>
for SerializingChallenger32<F, T, Inner>
{
fn observe(&mut self, values: Hash<F, u8, N>) {
fn observe(&mut self, values: Hash<F, T, N>) {
for value in values {
self.inner.observe(value);
}
}
}

impl<F, EF, Inner> CanSample<EF> for SerializingChallenger32<F, Inner>
impl<F, EF, Inner> CanSample<EF> for SerializingChallenger32<F, u8, Inner>
where
F: PrimeField32,
EF: ExtensionField<F>,
Inner: CanSample<u8>,
{
fn sample(&mut self) -> EF {
let modulus = F::ORDER_U64 as u32;
let log_size = log2_ceil_u64(F::ORDER_U64);
let pow_of_two_bound = (1 << log_size) - 1;
// Perform rejection sampling over the uniform range (0..log2_ceil(p))
let sample_base = |inner: &mut Inner| loop {
let log_size = log2_ceil_u64(F::ORDER_U64).saturating_sub(1);
let bound = (1 << log_size) - 1;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The plonky3 sampling uses rejection sampling (probably changes since the last time you update the branch), so we should keep that in our versions as well

let sample_base = |inner: &mut Inner| {
let value = u32::from_le_bytes(inner.sample_array::<4>());
let value = value & pow_of_two_bound;
if value < modulus {
return F::from_canonical_u32(value);
}
F::from_canonical_u32(value & bound)
};
EF::from_base_fn(|_| sample_base(&mut self.inner))
}
}

impl<F, EF, Inner> CanSample<EF> for SerializingChallenger32<F, u32, Inner>
where
F: PrimeField32,
EF: ExtensionField<F>,
Inner: CanSample<u32>,
{
fn sample(&mut self) -> EF {
let log_size = log2_ceil_u64(F::ORDER_U64).saturating_sub(1);
let bound = (1 << log_size) - 1;
let sample_base = |inner: &mut Inner| {
let value = inner.sample();
F::from_canonical_u32(value & bound)
};
EF::from_base_fn(|_| sample_base(&mut self.inner))
}
}

impl<F, Inner> CanSampleBits<usize> for SerializingChallenger32<F, Inner>

impl<F, Inner> CanSampleBits<usize> for SerializingChallenger32<F, u8, Inner>
where
F: PrimeField32,
Inner: CanSample<u8>,
Expand All @@ -113,15 +134,31 @@ where
}
}

impl<F, Inner> GrindingChallenger for SerializingChallenger32<F, Inner>
impl<F, Inner> CanSampleBits<usize> for SerializingChallenger32<F, u32, Inner>
where
F: PrimeField32,
Inner: CanSample<u32>,
{
fn sample_bits(&mut self, bits: usize) -> usize {
debug_assert!(bits < (usize::BITS as usize));
// Limiting the number of bits to the field size
debug_assert!((1 << bits) <= F::ORDER_U64 as usize);
let rand_usize = self.inner.sample() as usize;
rand_usize & ((1 << bits) - 1)
}
}


impl<F, Inner> GrindingChallenger for SerializingChallenger32<F, u8, Inner>
where
F: PrimeField32,
Inner: CanSample<u8> + CanObserve<u8> + Clone + Send + Sync,
{
type Witness = F;

#[instrument(name = "grind for proof-of-work witness", skip_all)]
fn grind(&mut self, bits: usize) -> Self::Witness {
fn grind(&mut self, bits: usize) -> Self::Witness
{
let witness = (0..F::ORDER_U64)
.into_par_iter()
.map(|i| F::from_canonical_u64(i))
Expand All @@ -132,13 +169,40 @@ where
}
}

impl<F, Inner> FieldChallenger<F> for SerializingChallenger32<F, Inner>
impl<F, Inner> GrindingChallenger for SerializingChallenger32<F, u32, Inner>
where
F: PrimeField32,
Inner: CanSample<u32> + CanObserve<u32> + Clone + Send + Sync,
{
type Witness = F;

#[instrument(name = "grind for proof-of-work witness", skip_all)]
fn grind(&mut self, bits: usize) -> Self::Witness
{
let witness = (0..F::ORDER_U64)
.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
}
}

impl<F, Inner> FieldChallenger<F> for SerializingChallenger32<F, u8, Inner>
where
F: PrimeField32,
Inner: CanSample<u8> + CanObserve<u8> + Clone + Send + Sync,
{
}

impl<F, Inner> FieldChallenger<F> for SerializingChallenger32<F, u32, Inner>
where
F: PrimeField32,
Inner: CanSample<u32> + CanObserve<u32> + Clone + Send + Sync,
{
}

impl<F: PrimeField64, Inner: CanObserve<u8>> SerializingChallenger64<F, Inner> {
pub fn new(inner: Inner) -> Self {
Self {
Expand Down Expand Up @@ -182,16 +246,11 @@ where
Inner: CanSample<u8>,
{
fn sample(&mut self) -> EF {
let modulus = F::ORDER_U64;
let log_size = log2_ceil_u64(F::ORDER_U64);
let pow_of_two_bound = (1 << log_size) - 1;
// Perform rejection sampling over the uniform range (0..log2_ceil(p))
let sample_base = |inner: &mut Inner| loop {
let log_size = log2_ceil_u64(F::ORDER_U64).saturating_sub(1);
let bound = (1 << log_size) - 1;
let sample_base = |inner: &mut Inner| {
let value = u64::from_le_bytes(inner.sample_array::<8>());
let value = value & pow_of_two_bound;
if value < modulus {
return F::from_canonical_u64(value);
}
F::from_canonical_u64(value & bound)
};
EF::from_base_fn(|_| sample_base(&mut self.inner))
}
Expand Down Expand Up @@ -235,4 +294,4 @@ where
F: PrimeField64,
Inner: CanSample<u8> + CanObserve<u8> + Clone + Send + Sync,
{
}
}
2 changes: 1 addition & 1 deletion keccak-air/examples/prove_baby_bear_keccak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn main() -> Result<(), VerificationError> {
type Dft = Radix2DitParallel;
let dft = Dft {};

type Challenger = SerializingChallenger32<Val, HashChallenger<u8, ByteHash, 32>>;
type Challenger = SerializingChallenger32<Val, u8, HashChallenger<u8, ByteHash, 32>>;

let fri_config = FriConfig {
log_blowup: 1,
Expand Down
2 changes: 1 addition & 1 deletion symmetric/src/serializing_hasher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,4 @@ where
.map(|x| PW::from_fn(|i| x.as_slice()[i].as_canonical_u64())),
)
}
}
}
Loading