Просмотр исходного кода

add save and load trusted setup stuff

narodnik 5 лет назад
Родитель
Сommit
1099a62eb4
4 измененных файлов с 54 добавлено и 18 удалено
  1. 23 12
      src/bin/jubjub.rs
  2. 9 0
      src/error.rs
  3. 15 2
      src/lib.rs
  4. 7 4
      src/vm.rs

+ 23 - 12
src/bin/jubjub.rs

@@ -6,6 +6,28 @@ use std::time::Instant;
 type Result<T> = std::result::Result<T, failure::Error>;
 type Result<T> = std::result::Result<T, failure::Error>;
 
 
 fn main() -> Result<()> {
 fn main() -> Result<()> {
+    {
+        // Load the contract from file
+
+        let start = Instant::now();
+        let file = File::open("jubjub.zcd")?;
+        let mut contract = ZKContract::decode(file)?;
+        println!("Loaded contract '{}': [{:?}]", contract.name, start.elapsed());
+
+        println!("Stats:");
+        println!("    Constants: {}", contract.vm.constants.len());
+        println!("    Alloc: {}", contract.vm.alloc.len());
+        println!("    Operations: {}", contract.vm.ops.len());
+        println!(
+            "    Constraint Instructions: {}",
+            contract.vm.constraints.len()
+        );
+
+        // Do the trusted setup
+
+        contract.setup("jubjub.zts")?;
+    }
+
     // Load the contract from file
     // Load the contract from file
 
 
     let start = Instant::now();
     let start = Instant::now();
@@ -13,18 +35,7 @@ fn main() -> Result<()> {
     let mut contract = ZKContract::decode(file)?;
     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());
-    println!("    Alloc: {}", contract.vm.alloc.len());
-    println!("    Operations: {}", contract.vm.ops.len());
-    println!(
-        "    Constraint Instructions: {}",
-        contract.vm.constraints.len()
-    );
-
-    // Do the trusted setup
-
-    contract.setup();
+    contract.load_setup("jubjub.zts")?;
 
 
     // Put in our input parameters
     // Put in our input parameters
 
 

+ 9 - 0
src/error.rs

@@ -30,6 +30,7 @@ pub enum Error {
     MissingParams,
     MissingParams,
     VMError(ZKVMError),
     VMError(ZKVMError),
     BadContract,
     BadContract,
+    Groth16Error(bellman::SynthesisError)
 }
 }
 
 
 impl std::error::Error for Error {}
 impl std::error::Error for Error {}
@@ -63,6 +64,7 @@ impl fmt::Display for Error {
             Error::MissingParams => f.write_str("Missing params"),
             Error::MissingParams => f.write_str("Missing params"),
             Error::VMError(_) => f.write_str("VM error"),
             Error::VMError(_) => f.write_str("VM error"),
             Error::BadContract => f.write_str("Contract is poorly defined"),
             Error::BadContract => f.write_str("Contract is poorly defined"),
+            Error::Groth16Error(ref err) => write!(f, "groth16 error: {}", err),
         }
         }
     }
     }
 }
 }
@@ -78,3 +80,10 @@ impl From<ZKVMError> for Error {
         Error::VMError(err)
         Error::VMError(err)
     }
     }
 }
 }
+
+impl From<bellman::SynthesisError> for Error {
+    fn from(err: bellman::SynthesisError) -> Error {
+        Error::Groth16Error(err)
+    }
+}
+

+ 15 - 2
src/lib.rs

@@ -36,8 +36,21 @@ impl ZKContract {
     // Just have a load() and save()
     // Just have a load() and save()
     // Load the contract, do the setup, save it...
     // Load the contract, do the setup, save it...
 
 
-    pub fn setup(&mut self) {
-        self.vm.setup();
+    pub fn setup(&mut self, filename: &str) -> Result<()> {
+        self.vm.setup()?;
+
+        let buffer = std::fs::File::create(filename)?;
+        self.vm.params.as_ref().unwrap().write(buffer)?;
+        Ok(())
+    }
+
+    pub fn load_setup(&mut self, filename: &str) -> Result<()> {
+        let buffer = std::fs::File::open(filename)?;
+        let setup = groth16::Parameters::<Bls12>::read(buffer, false)?;
+        let vk = groth16::prepare_verifying_key(&setup.vk);
+        self.vm.params = Some(setup);
+        self.vm.verifying_key = Some(vk);
+        Ok(())
     }
     }
 
 
     pub fn param_names(&self) -> Vec<String> {
     pub fn param_names(&self) -> Vec<String> {

+ 7 - 4
src/vm.rs

@@ -13,6 +13,8 @@ use rand::rngs::OsRng;
 use std::ops::{Add, AddAssign, MulAssign, Neg, SubAssign};
 use std::ops::{Add, AddAssign, MulAssign, Neg, SubAssign};
 use std::time::Instant;
 use std::time::Instant;
 
 
+use crate::error::Result;
+
 pub struct ZKVirtualMachine {
 pub struct ZKVirtualMachine {
     pub constants: Vec<Scalar>,
     pub constants: Vec<Scalar>,
     pub alloc: Vec<(AllocType, VariableIndex)>,
     pub alloc: Vec<(AllocType, VariableIndex)>,
@@ -283,7 +285,7 @@ impl ZKVirtualMachine {
         publics
         publics
     }
     }
 
 
-    pub fn setup(&mut self) {
+    pub fn setup(&mut self) -> Result<()> {
         let start = Instant::now();
         let start = Instant::now();
         // Create parameters for our circuit. In a production deployment these would
         // Create parameters for our circuit. In a production deployment these would
         // be generated securely using a multiparty computation.
         // be generated securely using a multiparty computation.
@@ -294,14 +296,15 @@ impl ZKVirtualMachine {
                 constraints: self.constraints.clone(),
                 constraints: self.constraints.clone(),
                 constants: self.constants.clone(),
                 constants: self.constants.clone(),
             };
             };
-            groth16::generate_random_parameters::<Bls12, _, _>(circuit, &mut OsRng).unwrap()
+            groth16::generate_random_parameters::<Bls12, _, _>(circuit, &mut OsRng)?
         });
         });
 
 
         println!("Setup: [{:?}]", start.elapsed());
         println!("Setup: [{:?}]", start.elapsed());
 
 
         self.verifying_key = Some(groth16::prepare_verifying_key(
         self.verifying_key = Some(groth16::prepare_verifying_key(
             &self.params.as_ref().unwrap().vk,
             &self.params.as_ref().unwrap().vk,
-        ))
+        ));
+        Ok(())
     }
     }
 
 
     pub fn prove(&self) -> groth16::Proof<Bls12> {
     pub fn prove(&self) -> groth16::Proof<Bls12> {
@@ -344,7 +347,7 @@ impl Circuit<bls12_381::Scalar> for ZKVMCircuit {
     fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
     fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
         self,
         self,
         cs: &mut CS,
         cs: &mut CS,
-    ) -> Result<(), SynthesisError> {
+    ) -> std::result::Result<(), SynthesisError> {
         let mut variables = Vec::new();
         let mut variables = Vec::new();
 
 
         for (alloc_type, index) in &self.alloc {
         for (alloc_type, index) in &self.alloc {