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/circom prover #304

Merged
merged 11 commits into from
Jan 25, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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
505 changes: 244 additions & 261 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["mopro-ffi", "test-e2e", "cli", "mopro-wasm", "test-e2e/mopro-wasm-lib"]
members = ["mopro-ffi", "test-e2e", "cli", "mopro-wasm", "test-e2e/mopro-wasm-lib", "circom-prover"]
resolver = "2"
exclude = ["mopro-example-app"]

Expand Down
56 changes: 56 additions & 0 deletions circom-prover/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[package]
name = "circom-prover"
version = "0.1.0"
edition = "2021"

[lib]
name = "circom_prover"

[features]
default = ["rustwitness", "arkworks", "witnesscalc"]

# Witness Generation
rustwitness = [
"rust-witness",
]
witnesscalc = [
"witnesscalc-adapter",
]

# Proof Generation
arkworks = [
"ark-circom",
"ark-serialize",
"ark-ec",
"ark-crypto-primitives",
"ark-std",
"ark-bn254",
"ark-groth16",
"ark-relations",
"ark-ff",
"ark-bls12-381",
]
rapidsnark = []

[dependencies]
num = { version = "0.4.0" }
num-traits = { version = "0.2.15", default-features = false }
num-bigint = { version = "0.4.3", default-features = false, features = [
"rand",
] }
anyhow = "1.0.95"
rust-witness = { version = "0.1.2", optional = true }
witnesscalc-adapter = { git = "https://github.com/zkmopro/witnesscalc_adapter.git", package = "witnesscalc-adapter", optional = true }

ark-ec = { version = "=0.4.1", default-features = false, features = ["parallel"], optional = true }
ark-crypto-primitives = { version = "=0.4.0", optional = true }
ark-std = { version = "=0.4.0", default-features = false, features = ["parallel"], optional = true }
ark-bn254 = { version = "=0.4.0", optional = true }
ark-groth16 = { version = "=0.4.0", default-features = false, features = ["parallel"], optional = true }
ark-relations = { version = "0.4", default-features = false, optional = true }
uuid = { version = "1.9.1", features = ["v4"] }
byteorder = { version = "1.0.0", optional = true }
ark-ff = { version = "0.4.0", optional = true }
ark-bls12-381 = { version = "0.4.0", optional = true }
ark-circom = { git = "https://github.com/zkmopro/circom-compat.git", version = "0.1.0", branch = "wasm-delete", optional = true }
ark-serialize = { version = "=0.4.1", features = ["derive"], optional = true }
27 changes: 27 additions & 0 deletions circom-prover/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub mod prover;
pub mod witness;

// pub use rust_witness::transpile::transpile_wasm;
KimiWu123 marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(feature = "rustwitness")]
pub use rust_witness::*;
#[cfg(feature = "witnesscalc")]
pub use witnesscalc_adapter;

#[derive(Debug, Clone, Default)]
pub struct G1 {
pub x: String,
pub y: String,
}

#[derive(Debug, Clone, Default)]
pub struct G2 {
pub x: Vec<String>,
pub y: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub struct ProofCalldata {
pub a: G1,
pub b: G2,
pub c: G1,
}
47 changes: 47 additions & 0 deletions circom-prover/src/prover.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use anyhow::Result;
use num::BigUint;
use std::thread::JoinHandle;

#[cfg(feature = "arkworks")]
pub mod arkworks;
#[cfg(feature = "arkworks")]
pub mod serialization;

pub struct CircomProof {
pub proof: Vec<u8>,
pub pub_inputs: Vec<u8>,
}

pub enum ProofLib {
#[cfg(feature = "arkworks")]
Arkworks,
#[cfg(feature = "rapidsnark")]
RapidSnark,
}

pub fn prove(
lib: ProofLib,
zkey_path: String,
witnesses: JoinHandle<Vec<BigUint>>,
) -> Result<CircomProof> {
match lib {
#[cfg(feature = "arkworks")]
ProofLib::Arkworks => arkworks::generate_circom_proof(zkey_path, witnesses),
#[cfg(feature = "rapidsnark")]
ProofLib::RapidSnark => panic!("Not supported yet."),
}
}

pub fn verify(
lib: ProofLib,
zkey_path: String,
proof: Vec<u8>,
public_inputs: Vec<u8>,
) -> Result<bool> {
match lib {
#[cfg(feature = "arkworks")]
ProofLib::Arkworks => arkworks::verify_circom_proof(zkey_path, proof, public_inputs),
#[cfg(feature = "rapidsnark")]
ProofLib::RapidSnark => panic!("Not supported yet."),
}
}
124 changes: 124 additions & 0 deletions circom-prover/src/prover/arkworks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
use ark_bls12_381::Bls12_381;
use ark_bn254::Bn254;
use ark_circom::{
read_proving_key, read_zkey, CircomReduction, FieldSerialization, ZkeyHeaderReader,
};
use ark_crypto_primitives::snark::SNARK;
use ark_ec::pairing::Pairing;
use ark_ff::PrimeField;
use ark_groth16::{prepare_verifying_key, Groth16, ProvingKey, VerifyingKey};
use ark_relations::r1cs::ConstraintMatrices;
use ark_std::rand::thread_rng;
use ark_std::UniformRand;
use serialization::{SerializableInputs, SerializableProof};

use anyhow::{bail, Result};
use num_bigint::BigUint;
use std::{fs::File, thread::JoinHandle};

use super::{serialization, CircomProof};

pub fn generate_circom_proof(
zkey_path: String,
witness_thread: JoinHandle<Vec<BigUint>>,
) -> Result<CircomProof> {
// here we make a loader just to get the groth16 header
// this header tells us what curve the zkey was compiled for
// this loader will only load the first few bytes
let mut header_reader = ZkeyHeaderReader::new(&zkey_path);
header_reader.read();
let file = File::open(&zkey_path)?;
let mut reader = std::io::BufReader::new(file);

// check the prime in the header
if header_reader.r == BigUint::from(ark_bn254::Fr::MODULUS) {
let (proving_key, matrices) = read_zkey::<_, Bn254>(&mut reader)?;
// Get the result witness from the background thread
let witnesses = witness_thread
.join()
.map_err(|_e| anyhow::anyhow!("witness thread panicked"))
.unwrap();
prove(proving_key, matrices, witnesses)
} else if header_reader.r == BigUint::from(ark_bls12_381::Fr::MODULUS) {
let (proving_key, matrices) = read_zkey::<_, Bls12_381>(&mut reader)?;
let witnesses = witness_thread
.join()
.map_err(|_e| anyhow::anyhow!("witness thread panicked"))
.unwrap();
prove(proving_key, matrices, witnesses)
} else {
panic!("unknown curve detected in zkey");
}
}
pub fn verify_circom_proof(
zkey_path: String,
proof: Vec<u8>,
public_inputs: Vec<u8>,
) -> Result<bool> {
let mut header_reader = ZkeyHeaderReader::new(&zkey_path);
header_reader.read();
let file = File::open(&zkey_path)?;
let mut reader = std::io::BufReader::new(file);
if header_reader.r == BigUint::from(ark_bn254::Fr::MODULUS) {
let proving_key = read_proving_key::<_, Bn254>(&mut reader)?;
let p = serialization::deserialize_inputs::<Bn254>(public_inputs);
verify(proving_key.vk, p.0, proof)
} else if header_reader.r == BigUint::from(ark_bls12_381::Fr::MODULUS) {
let proving_key = read_proving_key::<_, Bls12_381>(&mut reader)?;
let p = serialization::deserialize_inputs::<Bls12_381>(public_inputs);
verify(proving_key.vk, p.0, proof)
} else {
// unknown curve
bail!("unknown curve detected in zkey")
}
}

fn prove<T: Pairing + FieldSerialization>(
pkey: ProvingKey<T>,
matrices: ConstraintMatrices<T::ScalarField>,
witness: Vec<BigUint>,
) -> Result<CircomProof> {
let witness_fr = witness
.iter()
.map(|v| T::ScalarField::from(v.clone()))
.collect::<Vec<_>>();
let mut rng = thread_rng();
let rng = &mut rng;
let r = T::ScalarField::rand(rng);
let s = T::ScalarField::rand(rng);
let public_inputs = witness_fr.as_slice()[1..matrices.num_instance_variables].to_vec();

// build the proof
let ark_proof = Groth16::<T, CircomReduction>::create_proof_with_reduction_and_matrices(
&pkey,
r,
s,
&matrices,
matrices.num_instance_variables,
matrices.num_constraints,
witness_fr.as_slice(),
);

let proof = ark_proof?;

Ok(CircomProof {
proof: serialization::serialize_proof(&SerializableProof(proof)),
pub_inputs: serialization::serialize_inputs(&SerializableInputs::<T>(public_inputs)),
})
}

fn verify<T: Pairing + FieldSerialization>(
vk: VerifyingKey<T>,
public_inputs: Vec<T::ScalarField>,
proof: Vec<u8>,
) -> Result<bool> {
let pvk = prepare_verifying_key(&vk);
let public_inputs_fr = public_inputs.to_vec();
let proof_parsed = serialization::deserialize_proof::<T>(proof);
let verified = Groth16::<T, CircomReduction>::verify_with_processed_vk(
&pvk,
&public_inputs_fr,
&proof_parsed.0,
)?;
Ok(verified)
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::{ProofCalldata, G1, G2};
use anyhow::Result;
use ark_bn254::Bn254;
use ark_circom::ethereum;
use ark_ec::pairing::Pairing;
use ark_groth16::{Proof, ProvingKey};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use color_eyre::Result;

#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug)]
pub struct SerializableProvingKey<T: Pairing>(pub ProvingKey<T>);
Expand Down Expand Up @@ -70,7 +70,6 @@ pub fn to_ethereum_inputs(inputs: Vec<u8>) -> Vec<String> {
#[cfg(test)]
mod tests {
use super::*;
use crate::circom::serialization::SerializableProvingKey;
use anyhow::Result;
use ark_bn254::Bn254;
use ark_circom::circom::{r1cs_reader::R1CSFile, CircomCircuit};
Expand Down
47 changes: 47 additions & 0 deletions circom-prover/src/witness.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use num::{BigInt, BigUint};
use std::{collections::HashMap, str::FromStr, thread::JoinHandle};

/// Witness function signature for rust_witness (inputs) -> witness
#[cfg(feature = "rustwitness")]
type RustWitnessWtnsFn = fn(HashMap<String, Vec<BigInt>>) -> Vec<BigInt>;
/// Witness function signature for witnesscalc_adapter (inputs, .dat file path) -> witness
#[cfg(feature = "witnesscalc")]
type WitnesscalcWtnsFn = fn(HashMap<String, Vec<BigInt>>, &str) -> Vec<BigInt>;

pub enum WitnessFn {
#[cfg(feature = "witnesscalc")]
WitnessCalc(WitnesscalcWtnsFn),
#[cfg(feature = "rustwitness")]
RustWitness(RustWitnessWtnsFn),
}

pub fn generate_witness(
witness_fn: WitnessFn,
inputs: HashMap<String, Vec<String>>,
_dat_path: String,
) -> JoinHandle<Vec<BigUint>> {
std::thread::spawn(move || {
Copy link
Collaborator

Choose a reason for hiding this comment

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

This thread is a noop. This generate_witness implementation creates a background thread, then blocks the main thread waiting for the background thread (e.g. immediately joins the thread below).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Nice catch! I forgot to handle this. fixed in b6d39a6

let bigint_inputs = inputs
.into_iter()
.map(|(k, v)| {
(
k,
v.into_iter()
.map(|i| BigInt::from_str(&i).unwrap())
.collect(),
)
})
.collect();

let witness = match witness_fn {
#[cfg(feature = "witnesscalc")]
WitnessFn::WitnessCalc(wit_fn) => wit_fn(bigint_inputs, _dat_path.as_str()),
#[cfg(feature = "rustwitness")]
WitnessFn::RustWitness(wit_fn) => wit_fn(bigint_inputs),
};
witness
.into_iter()
.map(|w| w.to_biguint().unwrap())
.collect::<Vec<_>>()
})
}
38 changes: 7 additions & 31 deletions mopro-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,19 @@ default = []
ashlang = ["dep:ashlang"]
halo2 = []
circom = [
"circom-prover",
"rust-witness",
"ark-circom",
"ark-serialize",
"ark-ec",
"ark-crypto-primitives",
"ark-std",
"ark-bn254",
"ark-groth16",
"ark-relations",
"ark-ff",
"ark-bls12-381",
"num-traits",
"byteorder",
"ark-ff",
]

[dependencies]
uniffi = { version = "=0.28.0", features = ["cli", "build"] }
serde = { version = "1.0", features = ["derive"] }
anyhow = "1.0.86"
bincode = "1.3.3"
num-bigint = { version = "0.4.3", default-features = false, features = ["rand",] }

# Error handling
thiserror = "=2.0.3"
Expand All @@ -46,32 +41,13 @@ ashlang = { git = "https://github.com/chancehudson/ashlang.git", rev = "696960a0

# circom deps
rust-witness = { version = "0.1.1", optional = true }
ark-circom = { git = "https://github.com/zkmopro/circom-compat.git", version = "0.1.0", branch = "wasm-delete", optional = true }
ark-serialize = { version = "=0.4.1", features = ["derive"], optional = true }
num-bigint = { version = "0.4.3", default-features = false, features = [
"rand",
] }
ark-ff = { version = "0.4.0", optional = true }
circom-prover = {path = "../circom-prover", optional = true}

# ZKP generation
ark-ec = { version = "=0.4.1", default-features = false, features = [
"parallel",
], optional = true }
ark-crypto-primitives = { version = "=0.4.0", optional = true }
ark-std = { version = "=0.4.0", default-features = false, features = [
"parallel",
], optional = true }
ark-bn254 = { version = "=0.4.0", optional = true }
ark-groth16 = { version = "=0.4.0", default-features = false, features = [
"parallel",
], optional = true }
ark-relations = { version = "0.4", default-features = false, optional = true }
uuid = { version = "1.9.1", features = ["v4"] }
byteorder = { version = "1.0.0", optional = true }
ark-ff = { version = "0.4.0", optional = true }
ark-bls12-381 = { version = "0.4.0", optional = true }
num-traits = { version = "0.2.0", optional = true }
anyhow = "1.0.86"
bincode = "1.3.3"

[build-dependencies]
rust-witness = { version = "0.1.1", optional = true }
Expand Down
Loading
Loading