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

working set_param function in visor

narodnik 5 лет назад
Родитель
Сommit
c7bece1788
6 измененных файлов с 106 добавлено и 47 удалено
  1. 2 2
      run_mint.sh
  2. 16 0
      scripts/compile_export_supervisor.py
  3. 60 40
      src/bin/mint.rs
  4. 2 0
      src/error.rs
  5. 12 3
      src/lib.rs
  6. 14 2
      src/vm_serial.rs

+ 2 - 2
run_mint3.sh → run_mint.sh

@@ -1,6 +1,6 @@
 #!/bin/bash -x
 #python scripts/preprocess.py proofs/mint2.psm > /tmp/mint2.psm || exit $?
-python scripts/preprocess.py proofs/jubjub.pism > /tmp/mint2.psm || exit $?
+python scripts/preprocess.py proofs/jubjub.psm > /tmp/mint2.psm || exit $?
 python scripts/compile.py --supervisor /tmp/mint2.psm --output mint.zcd || exit $?
-cargo run --release --bin mint3
+cargo run --release --bin mint
 

+ 16 - 0
scripts/compile_export_supervisor.py

@@ -89,6 +89,7 @@ def export(output, contract_name, contract):
     constants.sort(key=lambda obj: obj[1][0])
     constants = [(obj[0], obj[1][1]) for obj in constants]
 
+    # Constants
     output.write(varuint(len(constants)))
     for symbol, value in constants:
         print("Constant '%s' = %s" % (symbol, value))
@@ -97,6 +98,7 @@ def export(output, contract_name, contract):
         assert len(const_bytes) == 32
         output.write(const_bytes)
 
+    # Alloc
     output.write(varuint(len(contract.alloc)))
     for symbol, variable in contract.alloc.items():
         print("Alloc '%s' = (%s, %s)" % (symbol, 
@@ -111,6 +113,7 @@ def export(output, contract_name, contract):
         assert len(alloc_bytes) == 5
         output.write(alloc_bytes)
 
+    # Ops
     output.write(varuint(len(contract.ops)))
     for op in contract.ops:
         op_form = ops_table[op.command]
@@ -143,6 +146,7 @@ def export(output, contract_name, contract):
         print("Operation", op.command,
               [(arg.type.name, arg.index) for arg in op.args])
 
+    # Constraints
     output.write(varuint(len(contract.constraints)))
     for constraint in contract.constraints:
         args = constraint.args[:]
@@ -159,3 +163,15 @@ def export(output, contract_name, contract):
         for arg in args:
             output.write(struct.pack("<I", arg))
 
+    # Params Map
+    param_alloc = [(symbol, variable) for (symbol, variable)
+                   in contract.alloc.items() if variable.is_param]
+    output.write(varuint(len(param_alloc)))
+    for symbol, variable in param_alloc:
+        assert variable.is_param
+        print("Public '%s' = %s" % (symbol, variable.index))
+        symbol = symbol.encode()
+        output.write(varuint(len(symbol)))
+        output.write(symbol)
+        output.write(struct.pack("<I", variable.index))
+

+ 60 - 40
src/bin/mint.rs

@@ -1,4 +1,4 @@
-use sapvi::{Decodable, ZKSupervisor};
+use sapvi::{BlsStringConversion, Decodable, ZKSupervisor};
 use std::fs::File;
 use std::time::Instant;
 
@@ -9,6 +9,36 @@ use rand::rngs::OsRng;
 
 type Result<T> = std::result::Result<T, failure::Error>;
 
+// Unpack a value (such as jubjub::Fr) into 256 Scalar binary digits
+fn unpack<F: PrimeField>(value: F) -> Vec<Scalar> {
+    let mut bits = Vec::new();
+    print!("Unpack: ");
+    for (i, bit) in value.to_le_bits().into_iter().cloned().enumerate() {
+        match bit {
+            true => bits.push(Scalar::one()),
+            false => bits.push(Scalar::zero()),
+        }
+        print!("{}", if bit { 1 } else { 0 });
+    }
+    println!("");
+    bits
+}
+
+// Unpack a u64 value in 64 Scalar binary digits
+fn unpack_u64(value: u64) -> Vec<Scalar> {
+    let mut result = Vec::with_capacity(64);
+
+    for i in 0..64 {
+        if (value >> i) & 1 == 1 {
+            result.push(Scalar::one());
+        } else {
+            result.push(Scalar::zero());
+        }
+    }
+
+    result
+}
+
 fn main() -> Result<()> {
     let start = Instant::now();
     let file = File::open("mint.zcd")?;
@@ -28,45 +58,35 @@ fn main() -> Result<()> {
 
     visor.vm.setup();
 
-    let params = vec![
-        (
-            0,
-            Scalar::from_raw([
-                0xb981_9dc8_2d90_607e,
-                0xa361_ee3f_d48f_df77,
-                0x52a3_5a8c_1908_dd87,
-                0x15a3_6d1f_0f39_0d88,
-            ]),
-        ),
-        (
-            1,
-            Scalar::from_raw([
-                0x7b0d_c53c_4ebf_1891,
-                0x1f3a_beeb_98fa_d3e8,
-                0xf789_1142_c001_d925,
-                0x015d_8c7f_5b43_fe33,
-            ]),
-        ),
-        (
-            2,
-            Scalar::from_raw([
-                0xb981_9dc8_2d90_607e,
-                0xa361_ee3f_d48f_df77,
-                0x52a3_5a8c_1908_dd87,
-                0x15a3_6d1f_0f39_0d88,
-            ]),
-        ),
-        (
-            3,
-            Scalar::from_raw([
-                0x7b0d_c53c_4ebf_1891,
-                0x1f3a_beeb_98fa_d3e8,
-                0xf789_1142_c001_d925,
-                0x015d_8c7f_5b43_fe33,
-            ]),
-        ),
-    ];
-    visor.vm.initialize(&params);
+    // We use the ExtendedPoint in calculations because it's faster
+    let public_point = jubjub::ExtendedPoint::from(jubjub::SubgroupPoint::random(&mut OsRng));
+    // But to serialize we need to convert to affine (which has the (u, v) values)
+    let public_affine = public_point.to_affine();
+
+    let randomness_value: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
+
+    for param in visor.param_names() {
+        println!("Param name: {}", param);
+    }
+
+    visor.set_param(
+        "x1",
+        Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"),
+    )?;
+    visor.set_param(
+        "y1",
+        Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"),
+    )?;
+    visor.set_param(
+        "x2",
+        Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"),
+    )?;
+    visor.set_param(
+        "y2",
+        Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"),
+    )?;
+
+    visor.vm.initialize(&visor.params.into_iter().collect());
 
     let proof = visor.vm.prove();
 

+ 2 - 0
src/error.rs

@@ -24,6 +24,7 @@ pub enum Error {
     BadVariableRefType,
     BadOperationType,
     BadConstraintType,
+    InvalidParamName,
 }
 
 impl std::error::Error for Error {}
@@ -53,6 +54,7 @@ impl fmt::Display for Error {
             Error::BadVariableRefType => f.write_str("Bad variable ref type byte"),
             Error::BadOperationType => f.write_str("Bad operation type byte"),
             Error::BadConstraintType => f.write_str("Bad constraint type byte"),
+            Error::InvalidParamName => f.write_str("Invalid param name"),
         }
     }
 }

+ 12 - 3
src/lib.rs

@@ -9,6 +9,7 @@ pub mod vm;
 pub mod vm_serial;
 
 pub use crate::bls_extensions::BlsStringConversion;
+pub use crate::error::{Error, Result};
 pub use crate::serial::{Decodable, Encodable};
 pub use crate::vm::{
     AllocType, ConstraintInstruction, CryptoOperation, VariableIndex, VariableRef, ZKVMCircuit,
@@ -21,7 +22,7 @@ pub struct ZKSupervisor {
     pub name: String,
     pub vm: ZKVirtualMachine,
     params_map: HashMap<String, VariableIndex>,
-    params: HashMap<VariableIndex, Scalar>,
+    pub params: HashMap<VariableIndex, Scalar>,
     public_map: HashMap<String, VariableIndex>,
 }
 
@@ -57,10 +58,18 @@ impl ZKSupervisor {
 
     fn load_setup(&self) {}
 
-    fn param_names(&self) -> Vec<String> {
+    pub fn param_names(&self) -> Vec<String> {
         self.params_map.keys().cloned().collect()
     }
-    fn set_param(&self, name: &str, value: Scalar) {}
+    pub fn set_param(&mut self, name: &str, value: Scalar) -> Result<()> {
+        match self.params_map.get(name) {
+            Some(index) => {
+                self.params.insert(*index, value);
+                Ok(())
+            }
+            None => Err(Error::InvalidParamName),
+        }
+    }
 
     fn prove(&self) {
         // error if params not all set

+ 14 - 2
src/vm_serial.rs

@@ -8,6 +8,8 @@ use crate::{impl_vec, ZKSupervisor};
 use std::collections::HashMap;
 use std::io;
 
+impl_vec!((String, VariableIndex));
+
 impl Encodable for ZKSupervisor {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
         unimplemented!();
@@ -29,9 +31,12 @@ impl Decodable for ZKSupervisor {
                 params: None,
                 verifying_key: None,
             },
-            params_map: HashMap::new(),
-            params: HashMap::new(),
+            params_map: Vec::<(String, VariableIndex)>::decode(&mut d)?
+                .into_iter()
+                .collect(),
             public_map: HashMap::new(),
+
+            params: HashMap::new(),
         })
     }
 }
@@ -60,6 +65,13 @@ impl Decodable for (AllocType, VariableIndex) {
 
 impl_vec!((AllocType, VariableIndex));
 
+impl Encodable for VariableIndex {
+    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
+        unimplemented!();
+        Ok(0)
+    }
+}
+
 impl Decodable for VariableIndex {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         Ok(ReadExt::read_u32(&mut d)? as Self)