narodnik 5 лет назад
Родитель
Сommit
9062c409c1
6 измененных файлов с 139 добавлено и 93 удалено
  1. 56 41
      src/bin/jubjub.rs
  2. 27 28
      src/bin/mimc.rs
  3. 3 12
      src/bin/mint.rs
  4. 1 2
      src/error.rs
  5. 10 9
      src/lib.rs
  6. 42 1
      src/vm_serial.rs

+ 56 - 41
src/bin/jubjub.rs

@@ -1,5 +1,5 @@
 use bls12_381::Scalar;
-use sapvi::{BlsStringConversion, Decodable, ZKContract};
+use sapvi::{BlsStringConversion, Encodable, Decodable, ZKContract, ZKProof};
 use std::fs::File;
 use std::time::Instant;
 
@@ -12,7 +12,11 @@ fn main() -> Result<()> {
         let start = Instant::now();
         let file = File::open("jubjub.zcd")?;
         let mut contract = ZKContract::decode(file)?;
-        println!("Loaded contract '{}': [{:?}]", contract.name, start.elapsed());
+        println!(
+            "Loaded contract '{}': [{:?}]",
+            contract.name,
+            start.elapsed()
+        );
 
         println!("Stats:");
         println!("    Constants: {}", contract.vm.constants.len());
@@ -33,51 +37,62 @@ fn main() -> Result<()> {
     let start = Instant::now();
     let file = File::open("jubjub.zcd")?;
     let mut contract = ZKContract::decode(file)?;
-    println!("Loaded contract '{}': [{:?}]", contract.name, start.elapsed());
+    println!(
+        "Loaded contract '{}': [{:?}]",
+        contract.name,
+        start.elapsed()
+    );
 
     contract.load_setup("jubjub.zts")?;
 
-    // Put in our input parameters
-
-    contract.set_param(
-        "a_u",
-        Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"),
-    )?;
-    contract.set_param(
-        "a_v",
-        Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"),
-    )?;
-    contract.set_param(
-        "b_u",
-        Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"),
-    )?;
-    contract.set_param(
-        "b_v",
-        Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"),
-    )?;
-
-    // Generate the ZK proof
-
-    let proof = contract.prove()?;
-
-    // Test and show our output values
-
-    assert_eq!(proof.public.len(), 2);
-    // 0x66ced46f14e5616d12b993f60a6e66558d6b6afe4c321ed212e0b9cfbd81061a
-    assert_eq!(
-        *proof.public.get("result_u").unwrap(),
-        Scalar::from_string("66ced46f14e5616d12b993f60a6e66558d6b6afe4c321ed212e0b9cfbd81061a")
-    );
-    // 0x4731570fdd57cf280eadc8946fa00df81112502e44e497e794ab9a221f1bcca
-    assert_eq!(
-        *proof.public.get("result_v").unwrap(),
-        Scalar::from_string("04731570fdd57cf280eadc8946fa00df81112502e44e497e794ab9a221f1bcca")
-    );
-    println!("u = {:?}", proof.public.get("result_u").unwrap());
-    println!("v = {:?}", proof.public.get("result_v").unwrap());
+    {
+        // Put in our input parameters
+
+        contract.set_param(
+            "a_u",
+            Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"),
+        )?;
+        contract.set_param(
+            "a_v",
+            Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"),
+        )?;
+        contract.set_param(
+            "b_u",
+            Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"),
+        )?;
+        contract.set_param(
+            "b_v",
+            Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"),
+        )?;
+
+        // Generate the ZK proof
+
+        let proof = contract.prove()?;
+
+        // Test and show our output values
+
+        assert_eq!(proof.public.len(), 2);
+        // 0x66ced46f14e5616d12b993f60a6e66558d6b6afe4c321ed212e0b9cfbd81061a
+        assert_eq!(
+            *proof.public.get("result_u").unwrap(),
+            Scalar::from_string("66ced46f14e5616d12b993f60a6e66558d6b6afe4c321ed212e0b9cfbd81061a")
+        );
+        // 0x4731570fdd57cf280eadc8946fa00df81112502e44e497e794ab9a221f1bcca
+        assert_eq!(
+            *proof.public.get("result_v").unwrap(),
+            Scalar::from_string("04731570fdd57cf280eadc8946fa00df81112502e44e497e794ab9a221f1bcca")
+        );
+        println!("u = {:?}", proof.public.get("result_u").unwrap());
+        println!("v = {:?}", proof.public.get("result_v").unwrap());
+
+        let mut file = File::create("jubjub.prf")?;
+        proof.encode(&mut file)?;
+    }
 
     // Verify the proof
 
+    let file = File::open("jubjub.prf")?;
+    let proof = ZKProof::decode(file)?;
     assert!(contract.verify(&proof));
 
     Ok(())

+ 27 - 28
src/bin/mimc.rs

@@ -1,9 +1,9 @@
 use bls12_381::Scalar;
+use ff::{Field, PrimeField};
 use sapvi::{BlsStringConversion, Decodable, ZKContract};
 use std::fs::File;
-use std::time::Instant;
-use ff::{Field, PrimeField};
 use std::ops::{Add, AddAssign, MulAssign, Neg, SubAssign};
+use std::time::Instant;
 
 type Result<T> = std::result::Result<T, failure::Error>;
 
@@ -60,7 +60,11 @@ fn main() -> Result<()> {
     let start = Instant::now();
     let file = File::open("mimc.zcd")?;
     let mut contract = ZKContract::decode(file)?;
-    println!("Loaded contract '{}': [{:?}]", contract.name, start.elapsed());
+    println!(
+        "Loaded contract '{}': [{:?}]",
+        contract.name,
+        start.elapsed()
+    );
 
     println!("Stats:");
     println!("    Constants: {}", contract.vm.constants.len());
@@ -77,26 +81,21 @@ fn main() -> Result<()> {
 
     // Put in our input parameters
 
-    let left =
-            Scalar::from_raw([
-                0xb981_9dc8_2d90_607e,
-                0xa361_ee3f_d48f_df77,
-                0x52a3_5a8c_1908_dd87,
-                0x15a3_6d1f_0f39_0d88,
-            ]);
-            let right = Scalar::from_raw([
-                0x7b0d_c53c_4ebf_1891,
-                0x1f3a_beeb_98fa_d3e8,
-                0xf789_1142_c001_d925,
-                0x015d_8c7f_5b43_fe33,
-            ]);
-
-    contract.set_param(
-        "left_0", left.clone()
-    )?;
-    contract.set_param(
-        "right", right.clone()
-    )?;
+    let left = Scalar::from_raw([
+        0xb981_9dc8_2d90_607e,
+        0xa361_ee3f_d48f_df77,
+        0x52a3_5a8c_1908_dd87,
+        0x15a3_6d1f_0f39_0d88,
+    ]);
+    let right = Scalar::from_raw([
+        0x7b0d_c53c_4ebf_1891,
+        0x1f3a_beeb_98fa_d3e8,
+        0xf789_1142_c001_d925,
+        0x015d_8c7f_5b43_fe33,
+    ]);
+
+    contract.set_param("left_0", left.clone())?;
+    contract.set_param("right", right.clone())?;
 
     // Generate the ZK proof
 
@@ -104,14 +103,14 @@ fn main() -> Result<()> {
 
     // Test and show our output values
 
-    let mimc_hash = mimc(left,right, &constants);
+    let mimc_hash = mimc(left, right, &constants);
     assert_eq!(proof.public.len(), 1);
     // 0x66ced46f14e5616d12b993f60a6e66558d6b6afe4c321ed212e0b9cfbd81061a
-    assert_eq!(
-        *proof.public.get("hash_result").unwrap(),
-        mimc_hash
+    assert_eq!(*proof.public.get("hash_result").unwrap(), mimc_hash);
+    println!(
+        "hash result = {:?}",
+        proof.public.get("hash_result").unwrap()
     );
-    println!("hash result = {:?}", proof.public.get("hash_result").unwrap());
 
     // Verify the proof
 

+ 3 - 12
src/bin/mint.rs

@@ -69,19 +69,10 @@ fn main() -> Result<()> {
         println!("Param name: {}", param);
     }
 
-    visor.set_param(
-        "public_u",
-        public_affine.get_u()
-    )?;
-    visor.set_param(
-        "public_v",
-        public_affine.get_v()
-    )?;
+    visor.set_param("public_u", public_affine.get_u())?;
+    visor.set_param("public_v", public_affine.get_v())?;
     for (i, param_bit) in unpack(randomness_value).into_iter().enumerate() {
-        visor.set_param(
-            &format!("vc_randomness_{}", i),
-            param_bit
-        )?;
+        visor.set_param(&format!("vc_randomness_{}", i), param_bit)?;
     }
 
     let proof = visor.prove()?;

+ 1 - 2
src/error.rs

@@ -30,7 +30,7 @@ pub enum Error {
     MissingParams,
     VMError(ZKVMError),
     BadContract,
-    Groth16Error(bellman::SynthesisError)
+    Groth16Error(bellman::SynthesisError),
 }
 
 impl std::error::Error for Error {}
@@ -86,4 +86,3 @@ impl From<bellman::SynthesisError> for Error {
         Error::Groth16Error(err)
     }
 }
-

+ 10 - 9
src/lib.rs

@@ -29,7 +29,7 @@ pub struct ZKContract {
 
 pub struct ZKProof {
     pub public: HashMap<String, Scalar>,
-    pub proof: groth16::Proof<Bls12>
+    pub proof: groth16::Proof<Bls12>,
 }
 
 impl ZKContract {
@@ -84,23 +84,24 @@ impl ZKContract {
         let mut public = HashMap::new();
         for (index, value) in self.vm.public() {
             match self.public_map.get_by_right(&index) {
-                Some(name) => { public.insert(name.clone(), value); },
-                None => return Err(Error::BadContract)
+                Some(name) => {
+                    public.insert(name.clone(), value);
+                }
+                None => return Err(Error::BadContract),
             }
         }
 
         // return proof and public values (Hashmap string -> scalars)
-        Ok(ZKProof {
-            public,
-            proof
-        })
+        Ok(ZKProof { public, proof })
     }
     pub fn verify(&self, proof: &ZKProof) -> bool {
         let mut public = vec![];
         for (name, value) in &proof.public {
             match self.public_map.get_by_left(name) {
-                Some(index) => { public.push((index, value.clone())); },
-                None => return false
+                Some(index) => {
+                    public.push((index, value.clone()));
+                }
+                None => return false,
             }
         }
         public.sort_by(|a, b| a.0.partial_cmp(b.0).unwrap());

+ 42 - 1
src/vm_serial.rs

@@ -4,11 +4,14 @@ use crate::vm::{
     AllocType, ConstraintInstruction, CryptoOperation, VariableIndex, VariableRef, ZKVMCircuit,
     ZKVirtualMachine,
 };
-use crate::{impl_vec, ZKContract};
+use crate::{impl_vec, ZKContract, ZKProof};
+use bellman::groth16;
+use bls12_381 as bls;
 use std::collections::HashMap;
 use std::io;
 
 impl_vec!((String, VariableIndex));
+impl_vec!((String, bls::Scalar));
 
 impl Encodable for ZKContract {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
@@ -43,6 +46,44 @@ impl Decodable for ZKContract {
     }
 }
 
+impl Encodable for ZKProof {
+    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
+        let mut len = self
+            .public
+            .iter()
+            .map(|(k, v)| (k.clone(), v.clone()))
+            .collect::<Vec<_>>()
+            .encode(&mut s)?;
+        len += self.proof.encode(&mut s)?;
+        Ok(len)
+    }
+}
+
+impl Decodable for ZKProof {
+    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
+        Ok(Self {
+            public: Vec::<(String, bls::Scalar)>::decode(&mut d)?
+                .into_iter()
+                .collect(),
+            proof: Decodable::decode(&mut d)?,
+        })
+    }
+}
+
+impl Encodable for groth16::Proof<bls::Bls12> {
+    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
+        self.write(s)?;
+        // Depends on groth16 impl
+        Ok(48 + 96 + 48)
+    }
+}
+
+impl Decodable for groth16::Proof<bls::Bls12> {
+    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
+        Ok(groth16::Proof::read(d)?)
+    }
+}
+
 impl Encodable for (AllocType, VariableIndex) {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
         //let len = self.x.encode(&mut s)?;