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

Support for Hyrax polynomial commitment scheme #1

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 12 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ license-file = "LICENSE"
keywords = ["zkSNARKs", "cryptography", "proofs"]

[dependencies]
bellpepper-core = "0.2.1"
ff = { version = "0.13.0", features = ["derive"] }
bellpepper-core = { version="0.2.0", default-features = false }
bellpepper = { version="0.2.0", default-features = false }
digest = "0.10"
sha3 = "0.10"
rayon = "1.7"
Expand All @@ -31,16 +32,20 @@ flate2 = "1.0"
bitvec = "1.0"
byteorder = "1.4.3"
thiserror = "1.0"
halo2curves = { version = "0.4.0", features = ["derive_serde"] }
group = "0.13.0"
once_cell = "1.18.0"

[target.'cfg(any(target_arch = "x86_64", target_arch = "aarch64"))'.dependencies]
pasta-msm = { version = "0.1.4" }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
halo2curves = { version = "0.5.0", features = ["bits", "derive_serde"] }


[target.wasm32-unknown-unknown.dependencies]
# see https://github.com/rust-random/rand/pull/948
getrandom = { version = "0.2.0", default-features = false, features = ["js"] }
halo2curves = { version = "0.5.0", default-features = false, features = ["bits", "derive_serde"] }

[dev-dependencies]
criterion = { version = "0.4", features = ["html_reports"] }
Expand All @@ -51,8 +56,13 @@ cfg-if = "1.0.0"
sha2 = "0.10.7"
proptest = "1.2.0"

[[bench]]
name = "sha256"
harness = false

[features]
default = []
asm = ["halo2curves/asm"]
# Compiles in portable mode, w/o ISA extensions => binary can be executed on all systems.
portable = ["pasta-msm/portable"]
flamegraph = ["pprof/flamegraph", "pprof/criterion"]
150 changes: 150 additions & 0 deletions benches/sha256.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
//! Benchmarks Spartan's prover for proving SHA-256 with varying sized messages.
//! This code invokes a hand-written SHA-256 gadget from bellman/bellperson.
//! It also uses code from bellman/bellperson to compare circuit-generated digest with sha2 crate's output
#![allow(non_snake_case)]
use bellpepper::gadgets::{sha256::sha256, Assignment};
use bellpepper_core::{
boolean::{AllocatedBit, Boolean},
num::{AllocatedNum, Num},
Circuit, ConstraintSystem, SynthesisError,
};
use core::time::Duration;
use criterion::*;
use ff::{PrimeField, PrimeFieldBits};
use sha2::{Digest, Sha256};
use spartan2::{traits::Group, SNARK};
use std::marker::PhantomData;

type G = pasta_curves::pallas::Point;
type EE = spartan2::provider::hyrax_pc::HyraxEvaluationEngine<G>;
type S = spartan2::spartan::snark::RelaxedR1CSSNARK<G, EE>;

#[derive(Clone, Debug)]
struct Sha256Circuit<Scalar: PrimeField> {
preimage: Vec<u8>,
_p: PhantomData<Scalar>,
}

impl<Scalar: PrimeField + PrimeFieldBits> Sha256Circuit<Scalar> {
pub fn new(preimage: Vec<u8>) -> Self {
Self {
preimage,
_p: PhantomData,
}
}
}

impl<Scalar: PrimeField> Circuit<Scalar> for Sha256Circuit<Scalar> {
fn synthesize<CS: ConstraintSystem<Scalar>>(self, cs: &mut CS) -> Result<(), SynthesisError> {
let bit_values: Vec<_> = self
.preimage
.clone()
.into_iter()
.flat_map(|byte| (0..8).map(move |i| (byte >> i) & 1u8 == 1u8))
.map(Some)
.collect();
assert_eq!(bit_values.len(), self.preimage.len() * 8);

let preimage_bits = bit_values
.into_iter()
.enumerate()
.map(|(i, b)| AllocatedBit::alloc(cs.namespace(|| format!("preimage bit {i}")), b))
.map(|b| b.map(Boolean::from))
.collect::<Result<Vec<_>, _>>()?;

let hash_bits = sha256(cs.namespace(|| "sha256"), &preimage_bits)?;

for (i, hash_bits) in hash_bits.chunks(256_usize).enumerate() {
let mut num = Num::<Scalar>::zero();
let mut coeff = Scalar::ONE;
for bit in hash_bits {
num = num.add_bool_with_coeff(CS::one(), bit, coeff);

coeff = coeff.double();
}

let hash = AllocatedNum::alloc(cs.namespace(|| format!("input {i}")), || {
Ok(*num.get_value().get()?)
})?;

// num * 1 = hash
cs.enforce(
|| format!("packing constraint {i}"),
|_| num.lc(Scalar::ONE),
|lc| lc + CS::one(),
|lc| lc + hash.get_variable(),
);
}

// sanity check with the hasher
let mut hasher = Sha256::new();
hasher.update(&self.preimage);
let hash_result = hasher.finalize();

let mut s = hash_result
.iter()
.flat_map(|&byte| (0..8).rev().map(move |i| (byte >> i) & 1u8 == 1u8));

for b in hash_bits {
match b {
Boolean::Is(b) => {
assert!(s.next().unwrap() == b.get_value().unwrap());
}
Boolean::Not(b) => {
assert!(s.next().unwrap() != b.get_value().unwrap());
}
Boolean::Constant(_b) => {
panic!("Can't reach here")
}
}
}
Ok(())
}
}

criterion_group! {
name = snark;
config = Criterion::default().warm_up_time(Duration::from_millis(3000));
targets = bench_snark
}

criterion_main!(snark);

fn bench_snark(c: &mut Criterion) {
// Test vectors
let circuits = vec![
Sha256Circuit::new(vec![0u8; 1 << 6]),
Sha256Circuit::new(vec![0u8; 1 << 7]),
Sha256Circuit::new(vec![0u8; 1 << 8]),
Sha256Circuit::new(vec![0u8; 1 << 9]),
Sha256Circuit::new(vec![0u8; 1 << 10]),
Sha256Circuit::new(vec![0u8; 1 << 11]),
Sha256Circuit::new(vec![0u8; 1 << 12]),
Sha256Circuit::new(vec![0u8; 1 << 13]),
Sha256Circuit::new(vec![0u8; 1 << 14]),
Sha256Circuit::new(vec![0u8; 1 << 15]),
Sha256Circuit::new(vec![0u8; 1 << 16]),
];

for circuit in circuits {
let mut group = c.benchmark_group(format!(
"SpartanProve-Sha256-message-len-{}",
circuit.preimage.len()
));
group.sample_size(10);

// produce keys
let (pk, _vk) =
SNARK::<G, S, Sha256Circuit<<G as Group>::Scalar>>::setup(circuit.clone()).unwrap();

group.bench_function("Prove", |b| {
b.iter(|| {
let _ = SNARK::<G, S, Sha256Circuit<<G as Group>::Scalar>>::prove(
black_box(&pk),
black_box(circuit.clone()),
);
});
});
group.finish();
}
}
1 change: 0 additions & 1 deletion src/bellpepper/r1cs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ where
let X = &self.input_assignment[1..];

let comm_W = W.commit(ck);

let instance = R1CSInstance::<G>::new(shape, &comm_W, X)?;

Ok((instance, W))
Expand Down
3 changes: 3 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,7 @@ pub enum SpartanError {
/// returned when the consistency with public IO and assignment used fails
#[error("IncorrectWitness")]
IncorrectWitness,
/// returned when the library encounters an internal error
#[error("InternalError")]
InternalError,
}
27 changes: 17 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ mod tests {
let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
Ok(x_cu.get_value().unwrap() + x.get_value().unwrap() + F::from(5u64))
})?;
let z = AllocatedNum::alloc(cs.namespace(|| "z"), || Ok(F::from(1u64)))?;

cs.enforce(
|| "y = x^3 + x + 5",
Expand All @@ -144,34 +145,40 @@ mod tests {
|lc| lc + y.get_variable(),
);

cs.enforce(
|| "z = 1",
|lc| lc + z.get_variable(),
|lc| lc + CS::one() - z.get_variable(),
|lc| lc,
);

let _ = y.inputize(cs.namespace(|| "output"));

Ok(())
}
}

#[test]
fn test_snark() {
fn test_snark_hyrax_pc() {
type G = pasta_curves::pallas::Point;
type EE = crate::provider::ipa_pc::EvaluationEngine<G>;
type EE = crate::provider::hyrax_pc::HyraxEvaluationEngine<G>;
type S = crate::spartan::snark::RelaxedR1CSSNARK<G, EE>;
type Spp = crate::spartan::ppsnark::RelaxedR1CSSNARK<G, EE>;
//type Spp = crate::spartan::ppsnark::RelaxedR1CSSNARK<G, EE>;
test_snark_with::<G, S>();
test_snark_with::<G, Spp>();
//test_snark_with::<G, Spp>();

type G2 = bn256::Point;
type EE2 = crate::provider::ipa_pc::EvaluationEngine<G2>;
type EE2 = crate::provider::hyrax_pc::HyraxEvaluationEngine<G2>;
type S2 = crate::spartan::snark::RelaxedR1CSSNARK<G2, EE2>;
type S2pp = crate::spartan::ppsnark::RelaxedR1CSSNARK<G2, EE2>;
test_snark_with::<G2, S2>();
test_snark_with::<G2, S2pp>();
//test_snark_with::<G2, S2pp>();

type G3 = secp256k1::Point;
type EE3 = crate::provider::ipa_pc::EvaluationEngine<G3>;
type EE3 = crate::provider::hyrax_pc::HyraxEvaluationEngine<G3>;
type S3 = crate::spartan::snark::RelaxedR1CSSNARK<G3, EE3>;
type S3pp = crate::spartan::ppsnark::RelaxedR1CSSNARK<G3, EE3>;
//type S3pp = crate::spartan::ppsnark::RelaxedR1CSSNARK<G3, EE3>;
test_snark_with::<G3, S3>();
test_snark_with::<G3, S3pp>();
//test_snark_with::<G3, S3pp>();
}

fn test_snark_with<G: Group, S: RelaxedR1CSSNARKTrait<G>>() {
Expand Down
3 changes: 2 additions & 1 deletion src/provider/bn256_grumpkin.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! This module implements the Spartan traits for `bn256::Point`, `bn256::Scalar`, `grumpkin::Point`, `grumpkin::Scalar`.
use crate::{
impl_traits,
provider::{cpu_best_multiexp, keccak::Keccak256Transcript, pedersen::CommitmentEngine},
provider::{hyrax_pc::HyraxCommitmentEngine, keccak::Keccak256Transcript},
traits::{CompressedGroup, Group, PrimeFieldExt, TranscriptReprTrait},
};
use digest::{ExtendableOutput, Update};
Expand All @@ -21,6 +21,7 @@ use halo2curves::bn256::{
use halo2curves::grumpkin::{
G1Affine as GrumpkinAffine, G1Compressed as GrumpkinCompressed, G1 as GrumpkinPoint,
};
use halo2curves::msm::best_multiexp;

/// Re-exports that give access to the standard aliases used in the code base, for bn256
pub mod bn256 {
Expand Down
Loading
Loading