Ver Fonte

organizing code

plato há 5 anos atrás
pai
commit
18e2584460

+ 3 - 3
lisp/core.rs

@@ -1,7 +1,7 @@
+use rand::Rng;
 use std::fs::File;
 use std::io::Read;
 use std::rc::Rc;
-use rand::Rng;
 
 use std::time::{SystemTime, UNIX_EPOCH};
 
@@ -410,11 +410,11 @@ fn scalar_from(a: MalArgs) -> MalRet {
 fn scalar_square(a: MalArgs) -> MalRet {
     match a[0].clone() {
         ZKScalar(a0) => {
-            let  z0 = a0.clone();
+            let z0 = a0.clone();
             Ok(ZKScalar(z0.square()))
         }
         Str(a0) => {
-            let  s0 = bls12_381::Scalar::from_string(&a0);
+            let s0 = bls12_381::Scalar::from_string(&a0);
             Ok(ZKScalar(s0.square()))
         }
         _ => error(

+ 52 - 0
lisp/examples/jubjub-add-macro.lisp

@@ -0,0 +1,52 @@
+(println "jubjub-add-macro.lisp")
+(load-file "util.lisp")
+
+(defmacro! jubjub-add (fn* [param1 param2 param3 param4]
+    (let* [u1 (gensym) v1 (gensym) u2 (gensym) v2 (gensym)
+           EDWARDS_D (gensym) U (gensym) A (gensym) B (gensym)
+           C (gensym) u3 (gensym) v3 (gensym)] (
+        `(def! ~u1 (alloc ~u1 param1))
+        `(def! ~v1 (alloc ~v1 param2))
+        `(def! ~u2 (alloc ~u2 param3))
+        `(def! ~v2 (alloc ~v2 param4)) 
+        `(def! ~EDWARDS_D (alloc-const ~EDWARDS_D (scalar "2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1")))
+        `(def! ~U (alloc ~U (* (+ ~u1 ~v1) (+ ~u2 ~v2))))
+        `(def! ~A (alloc ~A (* ~v2 ~u1)))
+        `(def! ~B (alloc ~B (* ~u2 ~v1)))
+        `(def! ~C (alloc ~C (* ~EDWARDS_D (* ~A ~B))))
+        `(def! ~u3 (alloc-input ~u3 (/ (+ ~A ~B) (+ scalar::one ~C))))
+        `(def! ~v3 (alloc-input ~v3 (/ (- (- ~U ~A) ~B) (- scalar::one ~C))))        
+  `(enforce  
+    ((scalar::one ~u1) (scalar::one ~v1))
+    ((scalar::one ~u2) (scalar::one ~v2))
+    (scalar::one ~U)
+   )
+  `(enforce
+    (~EDWARDS_D ~A)
+    (scalar::one ~B)
+    (scalar::one ~C)
+   )
+  `(enforce
+    ((scalar::one cs::one)(scalar::one ~C))
+    (scalar::one ~u3)
+    ((scalar::one ~A) (scalar::one ~B))
+   )
+  `(enforce
+    ((scalar::one cs::one) (scalar::one::neg ~C))
+    (scalar::one ~v3)
+    ((scalar::one ~U) (scalar::one::neg ~A) (scalar::one::neg ~B))
+   )
+  )
+  ;; improve return values
+)
+))
+
+(def! param4 (scalar "015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"))
+(def! param3 (scalar "15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"))
+(def! param2 (scalar "015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"))
+(def! param1 (scalar "15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"))
+
+(prove (
+    (def! result1 (jubjub-add param1 param2 param3 param4))
+    (println 'jubjub-result result1)
+))

+ 79 - 0
lisp/examples/jubjub.lisp

@@ -0,0 +1,79 @@
+(println "jubjub-add.lisp")
+(load-file "util.lisp")
+
+(defmacro! zk-square (fn* [var] (
+        (let* [v1 (gensym)
+               v2 (gensym)] (
+        `(alloc ~v1 ~var)
+        `(alloc ~v2 (square ~var))
+        `(enforce  
+            (scalar::one ~v1) 
+            (scalar::one ~v1) 
+            (scalar::one ~v2) 
+        )
+        )
+    ))
+))
+
+;; -u^2 + v^2 = 1 + du^2v^2
+(defmacro! zk-witness (fn* [val1 val2] (
+        (let* [v (gensym)
+               u (gensym)
+               u2v2 (gensym)] (
+        `(alloc ~v1 ~var)
+        `(alloc ~v2 (square ~var))
+        `(enforce  
+            (scalar::one ~v1) 
+            (scalar::one ~v1) 
+            (scalar::one ~v2) 
+        )
+        )
+    ))
+))
+
+(defmacro! jubjub-add (fn* [param1 param2 param3 param4]
+    (let* [u1 (gensym) v1 (gensym) u2 (gensym) v2 (gensym)
+           EDWARDS_D (gensym) U (gensym) A (gensym) B (gensym)
+           C (gensym) u3 (gensym) v3 (gensym)] (
+        `(def! ~u1 (alloc ~u1 param1))
+        `(def! ~v1 (alloc ~v1 param2))
+        `(def! ~u2 (alloc ~u2 param3))
+        `(def! ~v2 (alloc ~v2 param4)) 
+        `(def! ~EDWARDS_D (alloc-const ~EDWARDS_D (scalar "2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1")))
+        `(def! ~U (alloc ~U (* (+ ~u1 ~v1) (+ ~u2 ~v2))))
+        `(def! ~A (alloc ~A (* ~v2 ~u1)))
+        `(def! ~B (alloc ~B (* ~u2 ~v1)))
+        `(def! ~C (alloc ~C (* ~EDWARDS_D (* ~A ~B))))
+        `(def! ~u3 (alloc-input ~u3 (/ (+ ~A ~B) (+ scalar::one ~C))))
+        `(def! ~v3 (alloc-input ~v3 (/ (- (- ~U ~A) ~B) (- scalar::one ~C))))        
+  `(enforce  
+    ((scalar::one ~u1) (scalar::one ~v1))
+    ((scalar::one ~u2) (scalar::one ~v2))
+    (scalar::one ~U)
+   )
+  `(enforce
+    (~EDWARDS_D ~A)
+    (scalar::one ~B)
+    (scalar::one ~C)
+   )
+  `(enforce
+    ((scalar::one cs::one)(scalar::one ~C))
+    (scalar::one ~u3)
+    ((scalar::one ~A) (scalar::one ~B))
+   )
+  `(enforce
+    ((scalar::one cs::one) (scalar::one::neg ~C))
+    (scalar::one ~v3)
+    ((scalar::one ~U) (scalar::one::neg ~A) (scalar::one::neg ~B))
+   )
+  )
+  ;; improve return values
+)
+))
+
+(prove 
+  (
+    (def! result-witness (zk-witness param1 param2))
+    (println 'result-witness (nth (nth result-witness 0) 1))   
+  )
+)

+ 47 - 0
lisp/examples/macro-test.lisp

@@ -0,0 +1,47 @@
+(def! inc (fn* [a] (i+ a 1)))
+(def! gensym
+  (let* [counter (atom 0)]
+    (fn* []
+      (symbol (str "G__" (swap! counter inc))))))
+
+(defmacro! zk-square (fn* [var] (
+        (let* [v1 (gensym)
+               v2 (gensym)] (
+        `(alloc ~v1 ~var)
+        `(def! v2 (alloc ~v2 (square ~var)))
+        `(enforce  
+            (scalar::one ~v1) 
+            (scalar::one ~v1) 
+            (scalar::one ~v2) 
+         )
+        `{ "v2" v2 }
+        )
+    ))
+))
+
+;; -u^2 + v^2 = 1 + du^2v^2
+(defmacro! zk-witness (fn* [val1 val2] (
+        (let* [v (gensym)
+               u (gensym)
+               u2v2 (gensym)] (
+        `(alloc ~v1 ~var)
+        `(alloc ~v2 (square ~var))
+        `(enforce  
+            (scalar::one ~v1) 
+            (scalar::one ~v1) 
+            (scalar::one ~v2) 
+        )
+        )
+    ))
+))
+
+(def! param1 (scalar 3))
+(def! param2 (scalar 1))
+(prove 
+  (
+    (def! result1 (zk-square param1))
+    ;; (def! result2 (zk-square param2))
+    (println 'result1_map (nth (nth result1 0) 3))
+    (println 'result1 (nth (nth result1 0) 1))   
+  )
+)

+ 22 - 0
lisp/examples/util.lisp

@@ -0,0 +1,22 @@
+(def! inc (fn* [a] (i+ a 1)))
+(def! gensym
+  (let* [counter (atom 0)]
+    (fn* []
+      (symbol (str "G__" (swap! counter inc))))))
+
+;; Like load-file, but will never load the same path twice.
+
+;; This file is normally loaded with `load-file`, so it needs a
+;; different mechanism to neutralize multiple inclusions of
+;; itself. Moreover, the file list should never be reset.
+
+(def! load-file-once
+  (try*
+    load-file-once
+  (catch* _
+    (let* [seen (atom {"../lib/util.mal" nil})]
+      (fn* [filename]
+        (if (not (contains? @seen filename))
+          (do
+            (swap! seen assoc filename nil)
+            (load-file filename))))))))

+ 21 - 17
lisp/lisp.rs

@@ -11,10 +11,13 @@ use bls12_381::Bls12;
 use fnv::FnvHashMap;
 use itertools::Itertools;
 use rand::rngs::OsRng;
-use std::{borrow::{Borrow, BorrowMut}, fs};
 use std::fs::File;
 use std::rc::Rc;
 use std::time::Instant;
+use std::{
+    borrow::{Borrow, BorrowMut},
+    fs,
+};
 use types::EnforceAllocation;
 
 #[macro_use]
@@ -166,7 +169,7 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
                     }
                     Sym(ref a0sym) if a0sym == "zk*" => {
-                        println!("zk* {:?}", l[1]);
+                        // println!("zk* {:?}", l[1]);
                         let (a1, a2) = (l[1].clone(), l[2].clone());
                         match a1 {
                             List(ref binds, _) | Vector(ref binds, _) => {
@@ -369,14 +372,14 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         let a1 = l[1].clone();
                         let value = eval(l[2].clone(), env.clone())?;
                         let result = eval(value.clone(), env.clone())?;
-                        println!("a1 {:?} ", a1);
+                        // println!("a1 {:?} ", a1);
                         let allocs = get_allocations(&env, "Allocations");
                         let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
                         for (k, v) in allocs.iter() {
                             new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
                         }
                         new_hm.insert(a1.pr_str(false), result.clone());
-                        // TODO change it 
+                        // TODO change it
                         if let Some(e) = &env.outer {
                             env_set(
                                 &e,
@@ -393,7 +396,7 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         Ok(result.clone())
                     }
                     //Sym(ref a0sym) if a0sym == "verify" => {
-                    Sym(ref a0sym) if a0sym == "enforce" => {                        
+                    Sym(ref a0sym) if a0sym == "enforce" => {
                         // here i'm considering that we always have tuple with only two elements
                         // also it's important to keep in mind for the sake of brevity of this v0
                         // we will not allow calculation or any lisp evaluations inside the enforce
@@ -465,24 +468,27 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         for value in enforce_vec.iter() {
                             new_vec.push(value.clone());
                         }
-                        // TODO change it 
+                        // TODO change it
                         if let Some(e) = &env.outer {
                             env_set(
                                 &e,
                                 Sym("AllocationsEnforce".to_string()),
                                 vector![vec![Enforce(Rc::new(new_vec.clone()))]],
-                            )?;                     
+                            )?;
                         } else {
                             env_set(
                                 &env,
                                 Sym("AllocationsEnforce".to_string()),
                                 vector![vec![Enforce(Rc::new(new_vec.clone()))]],
-                            )?;                     
+                            )?;
                         }
 
-                        println!("allocs here {:?}", get_allocations_nested(&env, "Allocations"));
-                        println!("enforce here {:?}", get_enforce_allocs_nested(&env));
-                        
+                        // println!(
+                        //     "allocs here {:?}",
+                        //     get_allocations_nested(&env, "Allocations")
+                        // );
+                        // println!("enforce here {:?}", get_enforce_allocs_nested(&env));
+
                         Ok(MalVal::Nil)
                     }
                     _ => match eval_ast(&ast, &env)? {
@@ -504,7 +510,7 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                                     continue 'tco;
                                 }
                                 _ => {
-                                    println!("{:?}", args);
+                                    // println!("{:?}", args);
                                     Ok(vector![el.to_vec()])
                                     //error("call non-function")
                                 }
@@ -523,7 +529,7 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
     ret
 }
 
-pub fn get_enforce_allocs(env: &Env) -> Vec<EnforceAllocation> {    
+pub fn get_enforce_allocs(env: &Env) -> Vec<EnforceAllocation> {
     if let Some(e) = &env.outer {
         get_enforce_allocs_nested(&e)
     } else {
@@ -532,7 +538,6 @@ pub fn get_enforce_allocs(env: &Env) -> Vec<EnforceAllocation> {
 }
 
 pub fn get_enforce_allocs_nested(env: &Env) -> Vec<EnforceAllocation> {
-    
     match env_find(env, "AllocationsEnforce") {
         Some(e) => match env_get(&e, &Sym("AllocationsEnforce".to_string())) {
             Ok(f) => {
@@ -565,7 +570,7 @@ pub fn get_allocations_nested(env: &Env, key: &str) -> Rc<FnvHashMap<String, Mal
     match env_find(env, key) {
         Some(e) => match env_get(&e, &Sym(key.to_string())) {
             Ok(f) => {
-                if let Hash(allocs, _) = f {                  
+                if let Hash(allocs, _) = f {
                     allocs
                 } else {
                     alloc_hm
@@ -577,7 +582,6 @@ pub fn get_allocations_nested(env: &Env, key: &str) -> Rc<FnvHashMap<String, Mal
     }
 }
 
-
 pub fn setup(_ast: MalVal, env: Env) -> Result<VerifyKeyParams, MalErr> {
     let start = Instant::now();
     let c = LispCircuit {
@@ -663,7 +667,7 @@ fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
 fn main() -> Result<(), ()> {
     let matches = clap_app!(zklisp =>
         (version: "0.1.0")
-        (author: "mileschet <miles.chet@gmail.com>")
+        (author: "Dark Renaissance")
         (about: "A Lisp Interpreter for Zero Knowledge Virtual Machine")
         (@subcommand load =>
             (about: "Load the file into the interpreter")

+ 1 - 1
lisp/run.sh

@@ -1,4 +1,4 @@
 export RUST_BACKTRACE=full
-cargo run --bin lisp load macros.lisp
+cargo run --bin lisp load examples/macro-test.lisp
 #cargo run --bin lisp load jubjub-mul.lisp
 #cargo run --bin lisp load new-cs.lisp

+ 12 - 12
lisp/types.rs

@@ -75,52 +75,52 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
         let mut variables: FnvHashMap<String, Variable> = FnvHashMap::default();
         let mut params_const = self.params;
 
-        println!("Allocations\n");
+        // println!("Allocations\n");
         for (k, v) in &self.allocs {
             match v {
                 MalVal::ZKScalar(val) => {
                     let var = cs.alloc(|| k, || Ok(*val))?;
                     variables.insert(k.to_string(), var);
-                    println!("k {:?} v {:?} var {:?}", k, v, var);
+                    // println!("k {:?} v {:?} var {:?}", k, v, var);
                 }
                 MalVal::Str(val) => {
                     let val_scalar = bls12_381::Scalar::from_string(&*val);
                     let var = cs.alloc(|| k, || Ok(val_scalar))?;
                     variables.insert(k.to_string(), var);
-                    println!("k {:?} v {:?} var {:?}", k, v, var);
+                    // println!("k {:?} v {:?} var {:?}", k, v, var);
                 }
                 _ => {
-                    println!("not allocated k {:?} v {:?}", k, v);
+                    // println!("not allocated k {:?} v {:?}", k, v);
                 }
             }
         }
 
-        println!("Allocations Input\n");
+        // println!("Allocations Input\n");
         for (k, v) in &self.alloc_inputs {
-            println!("k {:?} v {:?}", k, v);
+            // println!("k {:?} v {:?}", k, v);
             match v {
                 MalVal::ZKScalar(val) => {
                     let var = cs.alloc_input(|| k, || Ok(*val))?;
                     variables.insert(k.to_string(), var);
-                    println!("k {:?} v {:?} var {:?}", k, v, var);
+                    // println!("k {:?} v {:?} var {:?}", k, v, var);
                 }
                 MalVal::Str(val) => {
                     let val_scalar = bls12_381::Scalar::from_string(&*val);
                     let var = cs.alloc_input(|| k, || Ok(val_scalar))?;
                     variables.insert(k.to_string(), var);
-                    println!("k {:?} v {:?} var {:?}", k, v, var);
+                    // println!("k {:?} v {:?} var {:?}", k, v, var);
                 }
                 _ => {
-                    println!("not allocated k {:?} v {:?}", k, v);
+                    // println!("not allocated k {:?} v {:?}", k, v);
                 }
             }
         }
 
-        println!("Enforce Allocations\n");
+        // println!("Enforce Allocations\n");
         let mut enforce_sorted = self.constraints.clone();
         enforce_sorted.sort_by(|a, b| a.idx.cmp(&b.idx));
         for alloc_value in enforce_sorted.iter() {
-            println!("Enforce -> {:?}", alloc_value);
+            // println!("Enforce -> {:?}", alloc_value);
             let coeff = bls12_381::Scalar::one();
             let mut left = bellman::LinearCombination::<Scalar>::zero();
             let mut right = bellman::LinearCombination::<Scalar>::zero();
@@ -173,7 +173,7 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                 //println!("output: a {:?} b {:?} val_b: {:?}", a, b, val_b);
             }
 
-            println!("Enforcing ...");
+            // println!("Enforcing ...");
             cs.enforce(
                 || "constraint",
                 |_| left.clone(),