From bdf8fd7bf4d89ccbd38e7be697d95daa094f5ff3 Mon Sep 17 00:00:00 2001 From: Fritz Schmid Date: Sun, 28 Jan 2024 22:29:45 +0100 Subject: [PATCH] Some Refactor --- src/ophe.rs | 3 +- src/proofs.rs | 149 ++++++++++++++++++++++++++------------------------ 2 files changed, 79 insertions(+), 73 deletions(-) diff --git a/src/ophe.rs b/src/ophe.rs index f1a1999..e60892a 100644 --- a/src/ophe.rs +++ b/src/ophe.rs @@ -82,7 +82,8 @@ fn serialize_failed(_req: &Request) -> String { #[rocket::main] async fn main() { - let cryptoservice_urls = vec!["http://localhost:9001","http://localhost:9002"]; + rayon::ThreadPoolBuilder::new().num_threads(1).build_global().unwrap(); + let cryptoservice_urls = vec!["http://localhost:9001"]; let n = cryptoservice_urls.len(); let t = n; let rl_key = ophe::utils::random_scalar(); diff --git a/src/proofs.rs b/src/proofs.rs index 7b4e640..a51e287 100644 --- a/src/proofs.rs +++ b/src/proofs.rs @@ -1,4 +1,5 @@ use std::convert::TryInto; +use std::hint::black_box; use std::time::Instant; use crate::serializers; @@ -10,12 +11,12 @@ use ark_ff::BigInteger; use ark_ff::Fp2; use ark_ff::Fp384; use ark_ff::Fp384Parameters; +use ark_groth16::prepare_verifying_key; +use ark_groth16::Groth16; use ark_groth16::PreparedVerifyingKey; use ark_groth16::Proof; use ark_groth16::ProvingKey; use ark_groth16::VerifyingKey; -use ark_groth16::prepare_verifying_key; -use ark_groth16::Groth16; use ark_r1cs_std::alloc::AllocationMode; use ark_r1cs_std::eq::EqGadget; use ark_r1cs_std::fields::FieldVar; @@ -123,8 +124,8 @@ use arkworks_mimc::params::mimc_7_91_bls12_381::{ use arkworks_mimc::params::round_keys_contants_to_vec; use arkworks_mimc::MiMC; //mimc-7-91-bls12-381 -use ark_bls12_381::Fr; use ark_bls12_381::Fq; +use ark_bls12_381::Fr; use ark_ff::Field; use ark_ff::PrimeField; use ark_ff::Zero; @@ -147,10 +148,7 @@ fn test_mimc_hash() { use ark_std; -use arkworks_mimc::{ - constraints::{MiMCFeistelCRHGadget}, - MiMCFeistelCRH -}; +use arkworks_mimc::{constraints::MiMCFeistelCRHGadget, MiMCFeistelCRH}; use ark_crypto_primitives::{ crh::{TwoToOneCRH, TwoToOneCRHGadget}, @@ -158,25 +156,24 @@ use ark_crypto_primitives::{ }; use ark_ff::to_bytes; -use ark_r1cs_std::{ - fields::fp::FpVar, - prelude::{AllocVar}, - R1CSVar, ToBytesGadget, -}; +use ark_r1cs_std::{fields::fp::FpVar, prelude::AllocVar, R1CSVar, ToBytesGadget}; -use ark_serialize::{CanonicalSerialize, CanonicalDeserialize}; +use ark_serialize::SerializationError; +use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::io::{Read, Write}; use sha2::Digest; use std::ops::MulAssign; -use ark_serialize::SerializationError; - //TODO Type conversion //TODO add to server //TODO add to client //TODO 32 bytes? -pub fn setup_hash_proof() -> (ProvingKey, VerifyingKey, PreparedVerifyingKey) { +pub fn setup_hash_proof() -> ( + ProvingKey, + VerifyingKey, + PreparedVerifyingKey, +) { let a = Fr::from(20); // No idea why this is needed // TODO remove once fixed let test: HashProof = HashProof { @@ -191,13 +188,19 @@ pub fn setup_hash_proof() -> (ProvingKey, VerifyingKey, Pr (pk, vk, pvk) } -pub fn generate_hash_proof(username: &String, password: &String, nonce: &Scalar,random: &Scalar,pk: &ProvingKey)-> (Scalar,Vec){ +pub fn generate_hash_proof( + username: &String, + password: &String, + nonce: &Scalar, + random: &Scalar, + pk: &ProvingKey, +) -> (Scalar, Vec) { // hash the password and nonce to Fr let n_fr = Fr::from_le_bytes_mod_order(&nonce.to_bytes()); //use sha256 let mut hasher = sha2::Sha256::new(); hasher.update(username.as_bytes()); - hasher.update(password.as_bytes()); + hasher.update(password.as_bytes()); let hash = hasher.finalize(); let hash_fr = Fr::from_le_bytes_mod_order(&hash); // hash the two Fr to Fr @@ -211,8 +214,9 @@ pub fn generate_hash_proof(username: &String, password: &String, nonce: &Scalar, &mimc, &to_bytes!(hash_fr).unwrap(), &to_bytes!(n_fr).unwrap(), - ).unwrap(); - + ) + .unwrap(); + let result_fr = random_fr * hashed; let mut result_vec = Vec::new(); result_fr.serialize(&mut result_vec).unwrap(); @@ -224,19 +228,19 @@ pub fn generate_hash_proof(username: &String, password: &String, nonce: &Scalar, nonce_point: Some(n_fr), random_r: Some(random_fr), }; - let proof = Groth16::::prove( - &pk, - proof, - &mut ark_std::test_rng(), - ).unwrap(); + let proof = Groth16::::prove(&pk, proof, &mut ark_std::test_rng()).unwrap(); let mut proof_serialized = Vec::::new(); proof.serialize(&mut proof_serialized).unwrap(); - (result_scalar,proof_serialized) + (result_scalar, proof_serialized) } -pub fn validate_hash_proof(scalar: &Scalar, proof: &Vec, vk: &PreparedVerifyingKey) -> bool { +pub fn validate_hash_proof( + scalar: &Scalar, + proof: &Vec, + vk: &PreparedVerifyingKey, +) -> bool { match Proof::::deserialize(&proof[..]) { Ok(proof) => { let g2_fr = Fr::from_le_bytes_mod_order(&scalar.to_bytes()); @@ -249,7 +253,7 @@ pub fn validate_hash_proof(scalar: &Scalar, proof: &Vec, vk: &PreparedVerify } } -#[derive(Clone, Debug, PartialEq, Eq, Hash,CanonicalSerialize, CanonicalDeserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, CanonicalSerialize, CanonicalDeserialize)] pub struct HashProof { pub pw_point: Option, pub nonce_point: Option, @@ -258,7 +262,6 @@ pub struct HashProof { impl ConstraintSynthesizer for HashProof { fn generate_constraints(self, cs: ConstraintSystemRef) -> Result<(), SynthesisError> { - let mimc = MiMC::::new( 1, Fr::zero(), @@ -269,21 +272,21 @@ impl ConstraintSynthesizer for HashProof { let x_r = self.nonce_point.ok_or(SynthesisError::AssignmentMissing)?; let c_r = self.random_r.ok_or(SynthesisError::AssignmentMissing)?; - let x_l_var = FpVar::new_witness(cs.clone(), || Ok(x_l) )?; - let x_r_var = FpVar::new_witness(cs.clone(), || Ok(x_r) )?; - let c_r_var = FpVar::new_witness(cs.clone(), || Ok(c_r) )?; - let k_var = FpVar::new_constant(cs.clone(), &mimc.k)?; + let x_l_var = FpVar::new_witness(cs.clone(), || Ok(x_l))?; + let x_r_var = FpVar::new_witness(cs.clone(), || Ok(x_r))?; + let c_r_var = FpVar::new_witness(cs.clone(), || Ok(c_r))?; + let k_var = FpVar::new_constant(cs.clone(), &mimc.k)?; let round_keys = Vec::>::new_constant(cs.clone(), mimc.round_keys)?; let mimc_var = MiMCVar::<_, _>::new(1, k_var, round_keys); - + let hashed_var = as TwoToOneCRHGadget< MiMCFeistelCRH<_, _>, _, >>::evaluate(&mimc_var, &x_l_var.to_bytes()?, &x_r_var.to_bytes()?) .unwrap(); - + // mult c and hashed_var let result = FpVar::new_input(cs.clone(), || { let mut res = c_r_var.value()?; @@ -295,33 +298,34 @@ impl ConstraintSynthesizer for HashProof { } } - #[test] fn test_type_conversion() { - -let usename = String::from("username"); -let password = String::from("password"); -let nonce = utils::random_scalar(); -let random = utils::random_scalar(); -let (pk, vk, pvk) = setup_hash_proof(); -let (sclar1, proof) = generate_hash_proof(&usename, &password, &nonce, &random, &pk); -let res = validate_hash_proof(&sclar1, &proof, &pvk); -assert!(res); -// change g2 and test for inequality -let mut scalar2 = sclar1; -scalar2 *= utils::random_scalar(); -let res = validate_hash_proof(&scalar2, &proof, &pvk); -assert!(!res); -// change proof and test for inequality -let mut proof2 = proof; -proof2[0] = 0; -let res = validate_hash_proof(&sclar1, &proof2, &pvk); -assert!(!res); - + let usename = String::from("username"); + let password = String::from("password"); + let nonce = utils::random_scalar(); + let random = utils::random_scalar(); + let (pk, vk, pvk) = setup_hash_proof(); + let (sclar1, proof) = generate_hash_proof(&usename, &password, &nonce, &random, &pk); + let res = validate_hash_proof(&sclar1, &proof, &pvk); + assert!(res); + // change g2 and test for inequality + let mut scalar2 = sclar1; + scalar2 *= utils::random_scalar(); + let res = validate_hash_proof(&scalar2, &proof, &pvk); + assert!(!res); + // change proof and test for inequality + let mut proof2 = proof; + proof2[10] = 0; + let res = validate_hash_proof(&sclar1, &proof2, &pvk); + assert!(!res); } #[test] fn test_groth16() { + rayon::ThreadPoolBuilder::new() + .num_threads(1) + .build_global() + .unwrap(); let mut rng = &mut ark_std::test_rng(); let mimc = MiMC::::new( 1, @@ -348,17 +352,15 @@ fn test_groth16() { (&mut buf[0..32]).copy_from_slice(&bytes[..]); let scalar = Scalar::from_bytes(&buf).unwrap(); - let point = G2Affine::generator() * scalar; - println!("point: {:?}", point); - let test: HashProof = HashProof { pw_point: Some(a), nonce_point: Some(b), - random_r: Some(c), }; + random_r: Some(c), + }; let (pk, vk) = Groth16::::setup(test.clone(), &mut rng).unwrap(); - + let pvk = prepare_verifying_key::(&vk); let proof = Groth16::::prove( @@ -373,7 +375,7 @@ fn test_groth16() { .unwrap(); let start = Instant::now(); - for _i in 0..100{ + for _i in 0..100 { let proof = Groth16::::prove( &pk, HashProof { @@ -384,18 +386,24 @@ fn test_groth16() { &mut rng, ) .unwrap(); - } + black_box(proof); + } - println!("{:.2?} Groth16::::prove(", start.elapsed()/100); + println!( + "{:.2?} Groth16::::prove(", + start.elapsed() / 100 + ); let res = Groth16::::verify_with_processed_vk(&pvk, &[d], &proof); - // let start = Instant::now(); - // for _i in 0..100{ - // let res = Groth16::::verify_with_processed_vk(&pvk, &[a,b,Fr::from(1)], &proof); - // } + let start = Instant::now(); + for _i in 0..100 { + let res = + Groth16::::verify_with_processed_vk(&pvk, &[a, b, Fr::from(1)], &proof); + black_box(res); + } - println!("{:.2?} verify_with_processed_vk", start.elapsed()/100); + println!("{:.2?} verify_with_processed_vk", start.elapsed() / 100); println!("res: {:?}", res.unwrap()); @@ -412,13 +420,10 @@ fn test_groth16() { assert_eq!(vk, vk2); let pk2 = prepare_verifying_key(&vk2); assert_eq!(pvk, pk2); - - } #[test] fn test_constraint() -> Result<(), ark_relations::r1cs::SynthesisError> { - let rng = &mut ark_std::test_rng(); let cs = ConstraintSystem::::new_ref(); let mimc = MiMC::::new( 1,