Skip to content

Commit

Permalink
feat(core): update read_zkey with new_unchecked
Browse files Browse the repository at this point in the history
  • Loading branch information
vivianjeng committed Apr 21, 2024
1 parent a8b95da commit 931b110
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 41 deletions.
32 changes: 30 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion mopro-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ calc-native-witness = ["witness"] # experimental feature to calculate witness wi
build-native-witness = ["witness/build-witness"] # only enable build-native-witness feature when building the witness graph

[dependencies]
ark-circom = { git = "https://github.com/arkworks-rs/circom-compat.git" }
ark-circom = { git = "https://github.com/vimwitch/circom-compat.git" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
ark-serialize = { version = "=0.4.1", features = ["derive"] }
Expand Down
Binary file not shown.
82 changes: 44 additions & 38 deletions mopro-core/src/middleware/circom/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ use self::{
};
use crate::MoproError;

use std::collections::HashMap;
//use std::io::Cursor;
use std::io::Cursor;
use std::sync::Mutex;
use std::time::Instant;
use std::{collections::HashMap, fs::File, io::BufReader};

use ark_bn254::{Bn254, Fr};
use ark_circom::{
read_zkey,
CircomReduction,
WitnessCalculator, //read_zkey,
};
Expand Down Expand Up @@ -52,7 +53,7 @@ type CircuitInputs = HashMap<String, Vec<BigInt>>;
// TODO: Split up this namespace a bit, right now quite a lot of things going on

pub struct CircomState {
arkzkey: Option<(ProvingKey<Bn254>, ConstraintMatrices<Fr>)>,
zkey: Option<(ProvingKey<Bn254>, ConstraintMatrices<Fr>)>,
wtns: Option<WitnessCalculator>,
}

Expand All @@ -66,21 +67,21 @@ impl Default for CircomState {

// TODO: Replace printlns with logging

//const ZKEY_BYTES: &[u8] = include_bytes!(env!("BUILD_RS_ZKEY_FILE"));
const ZKEY_BYTES: &[u8] = include_bytes!(env!("BUILD_RS_ZKEY_FILE"));

const ARKZKEY_BYTES: &[u8] = include_bytes!(env!("BUILD_RS_ARKZKEY_FILE"));
// const ARKZKEY_BYTES: &[u8] = include_bytes!(env!("BUILD_RS_ARKZKEY_FILE"));

// static ZKEY: Lazy<(ProvingKey<Bn254>, ConstraintMatrices<Fr>)> = Lazy::new(|| {
// let mut reader = Cursor::new(ZKEY_BYTES);
// read_zkey(&mut reader).expect("Failed to read zkey")
// });

static ARKZKEY: Lazy<(ProvingKey<Bn254>, ConstraintMatrices<Fr>)> = Lazy::new(|| {
//let mut reader = Cursor::new(ARKZKEY_BYTES);
// TODO: Use reader? More flexible; unclear if perf diff
read_arkzkey_from_bytes(ARKZKEY_BYTES).expect("Failed to read arkzkey")
static ZKEY: Lazy<(ProvingKey<Bn254>, ConstraintMatrices<Fr>)> = Lazy::new(|| {
let mut reader = Cursor::new(ZKEY_BYTES);
read_zkey(&mut reader).expect("Failed to read zkey")
});

// static ARKZKEY: Lazy<(ProvingKey<Bn254>, ConstraintMatrices<Fr>)> = Lazy::new(|| {
// //let mut reader = Cursor::new(ARKZKEY_BYTES);
// // TODO: Use reader? More flexible; unclear if perf diff
// read_arkzkey_from_bytes(ARKZKEY_BYTES).expect("Failed to read arkzkey")
// });

#[cfg(not(feature = "dylib"))]
const WASM: &[u8] = include_bytes!(env!("BUILD_RS_WASM_FILE"));

Expand Down Expand Up @@ -140,7 +141,8 @@ pub fn initialize() {
// Initialize ARKZKEY
// TODO: Speed this up even more!
let now = std::time::Instant::now();
Lazy::force(&ARKZKEY);
Lazy::force(&ZKEY);
// Lazy::force(&ARKZKEY);
println!("Initializing arkzkey took: {:.2?}", now.elapsed());
}

Expand All @@ -157,17 +159,17 @@ fn from_dylib(path: &Path) -> Mutex<WitnessCalculator> {
Mutex::new(result)
}

// #[must_use]
// pub fn zkey() -> &'static (ProvingKey<Bn254>, ConstraintMatrices<Fr>) {
// &ZKEY
// }

// Experimental
#[must_use]
pub fn arkzkey() -> &'static (ProvingKey<Bn254>, ConstraintMatrices<Fr>) {
&ARKZKEY
pub fn zkey() -> &'static (ProvingKey<Bn254>, ConstraintMatrices<Fr>) {
&ZKEY
}

// Experimental
// #[must_use]
// pub fn arkzkey() -> &'static (ProvingKey<Bn254>, ConstraintMatrices<Fr>) {
// &ARKZKEY
// }

/// Provides access to the `WITNESS_CALCULATOR` singleton, initializing it if necessary.
/// It expects the path to the dylib file to be set in the `CIRCUIT_WASM_DYLIB` environment variable.
#[cfg(feature = "dylib")]
Expand Down Expand Up @@ -223,8 +225,8 @@ pub fn generate_proof2(
println!("Witness generation took: {:.2?}", now.elapsed());

let now = std::time::Instant::now();
//let zkey = zkey();
let zkey = arkzkey();
let zkey = zkey();
// let zkey = arkzkey();
println!("Loading arkzkey took: {:.2?}", now.elapsed());

let public_inputs = full_assignment.as_slice()[1..zkey.1.num_instance_variables].to_vec();
Expand Down Expand Up @@ -253,7 +255,8 @@ pub fn verify_proof2(
serialized_inputs: SerializableInputs,
) -> Result<bool, MoproError> {
let start = Instant::now();
let zkey = arkzkey();
let zkey = zkey();
// let zkey = arkzkey();
let pvk = prepare_verifying_key(&zkey.0.vk);

let proof_verified =
Expand All @@ -268,15 +271,18 @@ pub fn verify_proof2(
impl CircomState {
pub fn new() -> Self {
Self {
arkzkey: None,
zkey: None,
// arkzkey: None,
wtns: None,
}
}

pub fn initialize(&mut self, arkzkey_path: &str, wasm_path: &str) -> Result<(), MoproError> {
let arkzkey =
read_arkzkey(arkzkey_path).map_err(|e| MoproError::CircomError(e.to_string()))?;
self.arkzkey = Some(arkzkey);
pub fn initialize(&mut self, zkey_path: &str, wasm_path: &str) -> Result<(), MoproError> {
let mut file = File::open(zkey_path).map_err(|e| MoproError::CircomError(e.to_string()))?;
let zkey = read_zkey(&mut file).map_err(|e| MoproError::CircomError(e.to_string()))?;

// read_arkzkey(arkzkey_path).map_err(|e| MoproError::CircomError(e.to_string()))?;
self.zkey = Some(zkey);

let wtns = WitnessCalculator::new(wasm_path)
.map_err(|e| MoproError::CircomError(e.to_string()))
Expand Down Expand Up @@ -309,7 +315,7 @@ impl CircomState {
println!("Witness generation took: {:.2?}", now.elapsed());

let now = std::time::Instant::now();
let zkey = self.arkzkey.as_ref().ok_or(MoproError::CircomError(
let zkey = self.zkey.as_ref().ok_or(MoproError::CircomError(
"Zkey has not been set up".to_string(),
))?;
println!("Loading arkzkey took: {:.2?}", now.elapsed());
Expand Down Expand Up @@ -339,7 +345,7 @@ impl CircomState {
serialized_inputs: SerializableInputs,
) -> Result<bool, MoproError> {
let start = Instant::now();
let zkey = self.arkzkey.as_ref().ok_or(MoproError::CircomError(
let zkey = self.zkey.as_ref().ok_or(MoproError::CircomError(
"Zkey has not been set up".to_string(),
))?;
let pvk = prepare_verifying_key(&zkey.0.vk);
Expand Down Expand Up @@ -386,7 +392,7 @@ mod tests {
#[test]
fn test_setup_prove_verify_simple() {
let wasm_path = "./examples/circom/multiplier2/target/multiplier2_js/multiplier2.wasm";
let arkzkey_path = "./examples/circom/multiplier2/target/multiplier2_final.arkzkey";
let arkzkey_path = "./examples/circom/multiplier2/target/multiplier2_final.zkey";
// Instantiate CircomState
let mut circom_state = CircomState::new();

Expand Down Expand Up @@ -432,7 +438,7 @@ mod tests {
fn test_setup_prove_verify_keccak() {
let wasm_path =
"./examples/circom/keccak256/target/keccak256_256_test_js/keccak256_256_test.wasm";
let arkzkey_path = "./examples/circom/keccak256/target/keccak256_256_test_final.arkzkey";
let arkzkey_path = "./examples/circom/keccak256/target/keccak256_256_test_final.zkey";
// Instantiate CircomState
let mut circom_state = CircomState::new();

Expand Down Expand Up @@ -485,7 +491,7 @@ mod tests {
let mut circom_state = CircomState::new();

let wasm_path = "badpath/multiplier2.wasm";
let arkzkey_path = "badpath/multiplier2.arkzkey";
let arkzkey_path = "badpath/multiplier2.zkey";

// Act: Call the setup method
let result = circom_state.initialize(arkzkey_path, wasm_path);
Expand Down Expand Up @@ -558,7 +564,7 @@ mod tests {
#[test]
fn test_setup_prove_rsa() {
let wasm_path = "./examples/circom/rsa/target/main_js/main.wasm";
let arkzkey_path = "./examples/circom/rsa/target/main_final.arkzkey";
let arkzkey_path = "./examples/circom/rsa/target/main_final.zkey";

// Instantiate CircomState
let mut circom_state = CircomState::new();
Expand Down Expand Up @@ -669,7 +675,7 @@ mod tests {
fn test_setup_prove_anon_aadhaar() {
let wasm_path =
"./examples/circom/anonAadhaar/target/aadhaar-verifier_js/aadhaar-verifier.wasm";
let arkzkey_path = "./examples/circom/anonAadhaar/target/aadhaar-verifier_final.arkzkey";
let arkzkey_path = "./examples/circom/anonAadhaar/target/aadhaar-verifier_final.zkey";

// Instantiate CircomState
let mut circom_state = CircomState::new();
Expand Down

0 comments on commit 931b110

Please sign in to comment.