Some Refactor

This commit is contained in:
Fritz Schmid 2024-01-28 22:29:45 +01:00
parent 0fbfc57a9a
commit bdf8fd7bf4
2 changed files with 79 additions and 73 deletions

View File

@ -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();

View File

@ -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<Bls12_381>, VerifyingKey<Bls12_381>, PreparedVerifyingKey<Bls12_381>) {
pub fn setup_hash_proof() -> (
ProvingKey<Bls12_381>,
VerifyingKey<Bls12_381>,
PreparedVerifyingKey<Bls12_381>,
) {
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<Bls12_381>, VerifyingKey<Bls12_381>, Pr
(pk, vk, pvk)
}
pub fn generate_hash_proof(username: &String, password: &String, nonce: &Scalar,random: &Scalar,pk: &ProvingKey<Bls12_381>)-> (Scalar,Vec<u8>){
pub fn generate_hash_proof(
username: &String,
password: &String,
nonce: &Scalar,
random: &Scalar,
pk: &ProvingKey<Bls12_381>,
) -> (Scalar, Vec<u8>) {
// 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::<Bls12_381>::prove(
&pk,
proof,
&mut ark_std::test_rng(),
).unwrap();
let proof = Groth16::<Bls12_381>::prove(&pk, proof, &mut ark_std::test_rng()).unwrap();
let mut proof_serialized = Vec::<u8>::new();
proof.serialize(&mut proof_serialized).unwrap();
(result_scalar,proof_serialized)
(result_scalar, proof_serialized)
}
pub fn validate_hash_proof(scalar: &Scalar, proof: &Vec<u8>, vk: &PreparedVerifyingKey<Bls12_381>) -> bool {
pub fn validate_hash_proof(
scalar: &Scalar,
proof: &Vec<u8>,
vk: &PreparedVerifyingKey<Bls12_381>,
) -> bool {
match Proof::<Bls12_381>::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<u8>, 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<Fr>,
pub nonce_point: Option<Fr>,
@ -258,7 +262,6 @@ pub struct HashProof {
impl ConstraintSynthesizer<Fr> for HashProof {
fn generate_constraints(self, cs: ConstraintSystemRef<Fr>) -> Result<(), SynthesisError> {
let mimc = MiMC::<Fr, MIMC_7_91_BLS12_381_PARAMS>::new(
1,
Fr::zero(),
@ -269,21 +272,21 @@ impl ConstraintSynthesizer<Fr> 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::<FpVar<_>>::new_constant(cs.clone(), mimc.round_keys)?;
let mimc_var = MiMCVar::<_, _>::new(1, k_var, round_keys);
let hashed_var =
<MiMCFeistelCRHGadget<_, MIMC_7_91_BLS12_381_PARAMS> 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<Fr> 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::<Fr, MIMC_7_91_BLS12_381_PARAMS>::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::<Bls12_381>::setup(test.clone(), &mut rng).unwrap();
let pvk = prepare_verifying_key::<Bls12_381>(&vk);
let proof = Groth16::<Bls12_381>::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::<Bls12_381>::prove(
&pk,
HashProof {
@ -384,18 +386,24 @@ fn test_groth16() {
&mut rng,
)
.unwrap();
}
black_box(proof);
}
println!("{:.2?} Groth16::<Bls12_381>::prove(", start.elapsed()/100);
println!(
"{:.2?} Groth16::<Bls12_381>::prove(",
start.elapsed() / 100
);
let res = Groth16::<Bls12_381>::verify_with_processed_vk(&pvk, &[d], &proof);
// let start = Instant::now();
// for _i in 0..100{
// let res = Groth16::<Bls12_381>::verify_with_processed_vk(&pvk, &[a,b,Fr::from(1)], &proof);
// }
let start = Instant::now();
for _i in 0..100 {
let res =
Groth16::<Bls12_381>::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::<Fr>::new_ref();
let mimc = MiMC::<Fr, MIMC_7_91_BLS12_381_PARAMS>::new(
1,