Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
9 changes: 6 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ edition = "2021"
ark-crypto-primitives = { version = "0.5.0", features = [
"merkle_tree",
"crh",
"r1cs",
"constraints",
"sponge",
] }
ark-ff = "0.5.0"
Expand All @@ -29,10 +29,13 @@ ark-codes = { git = "https://github.com/dmpierre/ark-codes.git" }


[patch.crates-io]
ark-crypto-primitives = { git = "https://github.com/benbencik/crypto-primitives.git", branch = "smallfp-absorb-trait" }
ark-crypto-primitives = { git = "https://github.com/benbencik/crypto-primitives.git", branch = "smallfp-absorb-clean" }
ark-ff = { git = "https://github.com/arkworks-rs/algebra.git" }
ark-poly = { git = "https://github.com/arkworks-rs/algebra.git" }
ark-serialize = { git = "https://github.com/arkworks-rs/algebra.git" }
ark-r1cs-std = { git = "https://github.com/arkworks-rs/r1cs-std" }
ark-relations = { git = "https://github.com/arkworks-rs/snark.git" }
ark-snark = { git = "https://github.com/arkworks-rs/snark.git" }

# resolve transitive pull of spongefish from efficient-sumcheck
[patch."https://github.com/arkworks-rs/spongefish"]
Expand All @@ -41,7 +44,7 @@ spongefish = { git = "https://github.com/z-tech/spongefish.git", branch = "small
[dev-dependencies]
ark-bls12-381 = "0.5.0"
ark-bn254 = "0.5.0"
criterion = "0.7"
criterion = "0.8"

[features]
default = ["asm"]
Expand Down
35 changes: 35 additions & 0 deletions src/crypto/blake3_crh/fields.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use ark_ff::Field;
use ark_serialize::CanonicalSerialize;
use ark_std::rand::RngCore;
use core::borrow::Borrow;
use core::marker::PhantomData;

use ark_crypto_primitives::{crh::CRHScheme, Error};

use super::GenericDigest;

/// Blake3 leaf hash that takes field elements as input.
#[derive(Clone)]
pub struct Blake3F<F: Field> {
_f: PhantomData<F>,
}

impl<F: Field> CRHScheme for Blake3F<F> {
type Input = [F];
type Output = GenericDigest<32>;
type Parameters = ();

fn setup<R: RngCore>(_: &mut R) -> Result<Self::Parameters, Error> {
Ok(())
}

fn evaluate<T: Borrow<Self::Input>>(
(): &Self::Parameters,
input: T,
) -> Result<Self::Output, Error> {
let mut buf = Vec::new();
input.borrow().serialize_compressed(&mut buf)?;
let output: [_; 32] = blake3::hash(&buf).into();
Ok(output.into())
}
}
70 changes: 70 additions & 0 deletions src/crypto/blake3_crh/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
pub mod fields;

use ark_crypto_primitives::{crh::TwoToOneCRHScheme, sponge::Absorb, Error};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::rand::RngCore;
use core::borrow::Borrow;

/// A generic fixed-size digest (copied from whir).
#[derive(Clone, Debug, Eq, PartialEq, Hash, CanonicalSerialize, CanonicalDeserialize)]
pub struct GenericDigest<const N: usize>(pub [u8; N]);

impl<const N: usize> Default for GenericDigest<N> {
fn default() -> Self {
Self([0; N])
}
}

impl<const N: usize> AsRef<[u8]> for GenericDigest<N> {
fn as_ref(&self) -> &[u8] {
&self.0
}
}

impl<const N: usize> From<[u8; N]> for GenericDigest<N> {
fn from(value: [u8; N]) -> Self {
Self(value)
}
}

impl<const N: usize> Absorb for GenericDigest<N> {
fn to_sponge_bytes(&self, dest: &mut Vec<u8>) {
dest.extend_from_slice(&self.0);
}

fn to_sponge_field_elements<F: ark_ff::PrimeField>(&self, dest: &mut Vec<F>) {
dest.push(F::from_be_bytes_mod_order(&self.0));
}
}

/// Blake3 two-to-one hash for internal Merkle tree nodes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Blake3;

impl TwoToOneCRHScheme for Blake3 {
type Input = GenericDigest<32>;
type Output = GenericDigest<32>;
type Parameters = ();

fn setup<R: RngCore>(_: &mut R) -> Result<Self::Parameters, Error> {
Ok(())
}

fn evaluate<T: Borrow<Self::Input>>(
(): &Self::Parameters,
left_input: T,
right_input: T,
) -> Result<Self::Output, Error> {
let output: [_; 32] =
blake3::hash(&[left_input.borrow().0, right_input.borrow().0].concat()).into();
Ok(output.into())
}

fn compress<T: Borrow<Self::Output>>(
parameters: &Self::Parameters,
left_input: T,
right_input: T,
) -> Result<Self::Output, Error> {
Self::evaluate(parameters, left_input, right_input)
}
}
5 changes: 2 additions & 3 deletions src/crypto/merkle/blake3.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::parameters::MerkleTreeParams;
use ark_crypto_primitives::crh::blake3::fields::Blake3F;
use ark_crypto_primitives::crh::blake3::Blake3;
use ark_crypto_primitives::crh::blake3::GenericDigest;
use crate::crypto::blake3_crh::fields::Blake3F;
use crate::crypto::blake3_crh::{Blake3, GenericDigest};
use ark_crypto_primitives::{
crh::{CRHScheme, TwoToOneCRHScheme},
merkle_tree::{Config as MerkleConfig, IdentityDigestConverter},
Expand Down
1 change: 1 addition & 0 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod blake3_crh;
pub mod merkle;
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -733,7 +733,6 @@ impl<
)?;
(rt[0] == computed_mt.root()).ok_or_err(DeciderError::MerkleRoot)?;
(mt[0].root() == computed_mt.root()).ok_or_err(DeciderError::MerkleTrapDoor)?;
(mt[0].leaf_nodes == computed_mt.leaf_nodes).ok_or_err(DeciderError::MerkleRoot)?;

let f_hat = DenseMultilinearExtension::from_evaluations_slice(
log2(self.code.code_len()) as usize,
Expand Down
36 changes: 20 additions & 16 deletions src/relations/description.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use ark_ff::Field;
use ark_relations::r1cs::{ConstraintMatrices, ConstraintSynthesizer, ConstraintSystem};
use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystem, R1CS_PREDICATE_LABEL};
use serde::Serialize;

#[derive(Serialize)]
Expand Down Expand Up @@ -37,22 +37,26 @@ impl SerializableConstraintMatrices {
.generate_constraints(constraint_system.clone())
.unwrap();
constraint_system.finalize();
let matrices: ConstraintMatrices<F> = constraint_system.to_matrices().unwrap();
let serializable = SerializableConstraintMatrices::from(matrices);

let cs = constraint_system.into_inner().unwrap();
let all_matrices = cs.to_matrices().unwrap();
let r1cs_matrices = all_matrices
.get(R1CS_PREDICATE_LABEL)
.expect("R1CS predicate must exist");

let num_constraints = cs
.get_predicate_num_constraints(R1CS_PREDICATE_LABEL)
.unwrap_or(0);

let serializable = SerializableConstraintMatrices {
num_instance_variables: cs.num_instance_variables(),
num_witness_variables: cs.num_witness_variables(),
num_constraints,
a: Self::serialize_nested_field(r1cs_matrices[0].clone()),
b: Self::serialize_nested_field(r1cs_matrices[1].clone()),
c: Self::serialize_nested_field(r1cs_matrices[2].clone()),
};
let serialized = serde_json::to_string(&serializable).unwrap();
serialized.into_bytes()
}
}

impl<F: Field> From<ConstraintMatrices<F>> for SerializableConstraintMatrices {
fn from(m: ConstraintMatrices<F>) -> Self {
Self {
num_instance_variables: m.num_instance_variables,
num_witness_variables: m.num_witness_variables,
num_constraints: m.num_constraints,
a: SerializableConstraintMatrices::serialize_nested_field(m.a),
b: SerializableConstraintMatrices::serialize_nested_field(m.b),
c: SerializableConstraintMatrices::serialize_nested_field(m.c),
}
}
}
2 changes: 1 addition & 1 deletion src/relations/r1cs/hashchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use ark_crypto_primitives::{
};
use ark_ff::PrimeField;
use ark_r1cs_std::fields::fp::FpVar;
use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystem};
use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystem};
pub use config::HashChainConfig;
pub use instance::HashChainInstance;
pub use relation::compute_hash_chain;
Expand Down
18 changes: 13 additions & 5 deletions src/relations/r1cs/hashchain/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use ark_crypto_primitives::{
};
use ark_ff::{Field, PrimeField};
use ark_r1cs_std::fields::fp::FpVar;
use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef};
use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef};
use ark_serialize::CanonicalSerialize;
use ark_std::marker::PhantomData;

Expand Down Expand Up @@ -94,14 +94,22 @@ where
.unwrap();
constraint_system.finalize();

let cs = constraint_system.into_inner().unwrap();
// Extract assignments via the ref (borrow the inner CS)
let x = constraint_system
.borrow()
.map(|cs| cs.instance_assignment().unwrap().to_vec())
.unwrap();
let w = constraint_system
.borrow()
.map(|cs| cs.witness_assignment().unwrap().to_vec())
.unwrap();
Self {
constraint_system: ConstraintSystemRef::new(cs.clone()),
constraint_system,
config: hash_config,
instance,
witness,
x: cs.instance_assignment,
w: cs.witness_assignment,
x,
w,
_crhs_scheme: PhantomData,
_crhs_scheme_gadget: PhantomData,
}
Expand Down
2 changes: 1 addition & 1 deletion src/relations/r1cs/hashchain/synthesizer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use ark_crypto_primitives::crh::{CRHScheme, CRHSchemeGadget};
use ark_ff::{Field, PrimeField};
use ark_r1cs_std::{alloc::AllocVar, eq::EqGadget, fields::fp::FpVar};
use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError};
use ark_relations::gr1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError};
use ark_std::marker::PhantomData;

use crate::relations::r1cs::hashchain::{HashChainInstance, HashChainWitness};
Expand Down
26 changes: 18 additions & 8 deletions src/relations/r1cs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod hashchain;

use ark_ff::Field;
use ark_relations::r1cs::ConstraintSystemRef;
use ark_relations::gr1cs::ConstraintSystemRef;
use efficient_sumcheck::{hypercube::Hypercube, order_strategy::AscendingOrder};

use crate::error::WARPError;
Expand All @@ -27,21 +27,31 @@ impl<F: Field> TryFrom<ConstraintSystemRef<F>> for R1CS<F> {
type Error = WARPError;

fn try_from(cs: ConstraintSystemRef<F>) -> Result<Self, Self::Error> {
let matrices = cs.to_matrices().unwrap();
use ark_relations::gr1cs::R1CS_PREDICATE_LABEL;

let inner = cs.into_inner().unwrap();
let all_matrices = inner.to_matrices().unwrap();
let r1cs_matrices = all_matrices
.get(R1CS_PREDICATE_LABEL)
.expect("R1CS predicate must exist");

let num_constraints = inner
.get_predicate_num_constraints(R1CS_PREDICATE_LABEL)
.unwrap_or(0);

// number of constraints should be to be power of 2
let m = matrices.num_constraints.next_power_of_two();
let n = matrices.num_instance_variables + matrices.num_witness_variables;
let k = matrices.num_witness_variables;
let m = num_constraints.next_power_of_two();
let n = inner.num_instance_variables() + inner.num_witness_variables();
let k = inner.num_witness_variables();

// both `unwrap()` calls below are safe since warp/lib.rs forbids compiling on platforms
// with 16-bits pointers width
let log_m = m.ilog2().try_into().unwrap();
let log_n = n.ilog2().try_into().unwrap();

let mut a = matrices.a.into_iter();
let mut b = matrices.b.into_iter();
let mut c = matrices.c.into_iter();
let mut a = r1cs_matrices[0].clone().into_iter();
let mut b = r1cs_matrices[1].clone().into_iter();
let mut c = r1cs_matrices[2].clone().into_iter();
let mut p = vec![];
for _ in 0..m {
// when there are no constraints left, we store an empty one
Expand Down
11 changes: 4 additions & 7 deletions src/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ pub struct AccWitnessSerializer<
F: Field + PrimeField,
MT: Config<Leaf = [F], InnerDigest: AsRef<[u8]> + From<[u8; 32]>>,
> {
pub td: Vec<MT::LeafDigest>,
pub f: Vec<F>,
pub w: Vec<F>,
_mt: std::marker::PhantomData<MT>,
}

impl<F: Field + PrimeField, MT: Config<Leaf = [F], InnerDigest: AsRef<[u8]> + From<[u8; 32]>>>
Expand All @@ -41,13 +41,10 @@ impl<F: Field + PrimeField, MT: Config<Leaf = [F], InnerDigest: AsRef<[u8]> + Fr
assert_eq!(acc_witness.0.len(), 1);
assert_eq!(acc_witness.1.len(), 1);
assert_eq!(acc_witness.2.len(), 1);
let f = acc_witness.1[0].clone();
assert_eq!(f.len(), acc_witness.0[0].leaf_nodes.len());
let w = acc_witness.2[0].clone();
Self {
td: acc_witness.0[0].clone().leaf_nodes,
f,
w,
f: acc_witness.1[0].clone(),
w: acc_witness.2[0].clone(),
_mt: std::marker::PhantomData,
}
}
}
Expand Down
Loading