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

Merge branch 'master' of github.com:narodnik/sapvi

rachel-rose 5 лет назад
Родитель
Сommit
d156f04f7a
5 измененных файлов с 177 добавлено и 75 удалено
  1. 30 1
      lisp/core.rs
  2. 50 20
      lisp/examples/mint2.lisp
  3. 80 48
      lisp/lisp.rs
  4. 1 1
      lisp/run.sh
  5. 16 5
      lisp/types.rs

+ 30 - 1
lisp/core.rs

@@ -191,7 +191,7 @@ fn unpack_bits(a: MalArgs) -> MalRet {
                 .map(|a| Str(std::string::ToString::to_string(&a)[2..].to_string()))
                 .collect::<Vec<MalVal>>()))
         }
-        _ => error("invalid args to unpack-bits"),
+        _ => error(&format!("invalid args to unpack-bits found \n {:?}", a).to_string()),
     }
 }
 
@@ -455,6 +455,16 @@ fn scalar_one(a: MalArgs) -> MalRet {
     }
 }
 
+fn scalar_one_neg(a: MalArgs) -> MalRet {
+    match a.len() {
+        0 => Ok(vector![vec![ZKScalar(bls12_381::Scalar::one().neg())]]),
+        _ => Ok(vector![vec![
+            ZKScalar(bls12_381::Scalar::one().neg()),
+            a[0].clone()
+        ]]),
+    }
+}
+
 fn cs_one(_a: MalArgs) -> MalRet {
     Ok(vector![vec![Sym("cs::one".to_string())]])
 }
@@ -505,6 +515,24 @@ fn scalar_square(a: MalArgs) -> MalRet {
 
 fn scalar_double(a: MalArgs) -> MalRet {
     match a[0].clone() {
+        Func(_, _) => {
+            if let Vector(ref values, _) = a[0].apply(vec![]).unwrap() {
+                if let ZKScalar(a0) = values[0] {
+                    a0.double();
+                    Ok(ZKScalar(a0))
+                } else {
+                    error(
+                        &format!("scalar double expect (zkscalar or string) found \n {:?}", a)
+                            .to_string(),
+                    )
+                }
+            } else {
+                error(
+                    &format!("scalar double expect (zkscalar or string) found \n {:?}", a)
+                        .to_string(),
+                )
+            }
+        }
         ZKScalar(a0) => {
             let z0 = a0.clone();
             Ok(ZKScalar(z0.double()))
@@ -771,6 +799,7 @@ pub fn ns() -> Vec<(&'static str, MalVal)> {
         ("unpack-bits", func(unpack_bits)),
         ("range", func(range)),
         ("scalar::one", func(scalar_one)),
+        ("scalar::one::neg", func(scalar_one_neg)),
         ("neg", func(negate_from)),
         ("scalar::zero", func(scalar_zero)),
         ("scalar", func(scalar_from)),

+ 50 - 20
lisp/examples/mint2.lisp

@@ -190,7 +190,7 @@
         (let* [var (gensym)] (
             `(alloc ~var ~val)
             `(enforce
-                (scalar::one cs::one) (scalar::one ~var)
+                ((scalar::one cs::one) (scalar::one::neg ~var))
                 (scalar::one ~var)
                 ()
              )
@@ -265,35 +265,65 @@
     ))
 )))
 
-(def! mint-contract (fn* [public-u public-v] (
-    (def! randomness (rnd-scalar))    
-    (def! witness-result (zk-witness public-u public-v))    
-    (def! not-small-order (zk-not-small-order? public-u public-v))    
-    (def! g-vcr-u (alloc-input "g-vcr-u" public-u))
-    (def! g-vcr-v (alloc-input "g-vcr-v" public-v))
-    (def! mul-result (last (last (jj-mul g-vcr-u g-vcr-v randomness))))
-    (def! rcvu (alloc "rcvu" (get mul-result "u3")))
-    (def! rcvr (alloc "rcvr" (get mul-result "v3")))
-    (enforce
-        (scalar::one rcvu)
-        (scalar::one cs::one)
-        (scalar::one rcvu)
-    )
-    (enforce
-        (scalar::one rcvr)
-        (scalar::one cs::one)
-        (scalar::one rcvr)
+(defmacro! rangeproof-alloc (fn* [value value-digit] (
+ (let* [bit (gensym2 'bit)
+        digit (gensym2 'digit)] (
+    `(def! ~bit (alloc ~bit ~value))
+    `(def! ~digit (alloc-const ~digit ~value-digit))
+    `(enforce 
+        (scalar::one ~bit) 
+        (scalar::one::neg ~bit) 
+        () 
     )    
+    { "lc" ((str digit) (str bit)) }
+)))))
+
+(def! rangeproof (fn* [value] (    
+    (def! values-bit (unpack-bits value))
+    (def! acc 0)
+    (def! digit scalar::one)    
+    (def! value-result ())
+    (dotimes 64 (
+        (def! bit (nth values-bit acc))    
+        (def! value-result 
+            (conj value-result (get (last (last (rangeproof-alloc bit digit))) "lc")))
+        (def! digit (double digit))
+        (def! acc (i+ acc 1))
+    ))
+    (def! value-alloc (alloc-input "value-alloc" value))
+    (enforce 
+        (value-result)
+        (scalar::one cs::one)
+        (scalar::one value-alloc)
+    )  
 )))
 
 (prove 
   (            
     (def! param-u (scalar "6800f4fa0f001cfc7ff6826ad58004b4d1d8da41af03744e3bce3b7793664337"))
     (def! param-v (scalar "6d81d3a9cb45dedbe6fb2a6e1e22ab50ad46f1b0473b803b3caefab9380b6a8b"))
-    (mint-contract param-u param-v)    
+    (rangeproof param-u)
+    ;; (def! param3 (rnd-scalar))
+    ;; (jj-mul param-u param-v param3)
   )
 )
 
+;; (defmacro! test (fn* [value value-digit] (
+;;  (let* [bit (gensym2 'bit)
+;;         digit (gensym2 'digit)] (
+;;     `(def! ~bit (alloc ~bit ~value))
+;;     `(def! ~digit (alloc ~digit ~value-digit))
+;;     (println (str digit))
+;; )))))
+;; (def! param-u (scalar "6800f4fa0f001cfc7ff6826ad58004b4d1d8da41af03744e3bce3b7793664337"))
+;; (def! param-v (scalar "6d81d3a9cb45dedbe6fb2a6e1e22ab50ad46f1b0473b803b3caefab9380b6a8b"))
+;; (println (test param-u param-v))
+
+;; (mint-contract param-u param-v)    
+;; (def! param3 (rnd-scalar))
+;; (def! param-u (scalar "6800f4fa0f001cfc7ff6826ad58004b4d1d8da41af03744e3bce3b7793664337"))
+;; (def! param-v (scalar "6d81d3a9cb45dedbe6fb2a6e1e22ab50ad46f1b0473b803b3caefab9380b6a8b"))
+;; (jj-mul param-u param-v param3)
 ;; following some examples 
 ;; (def! left (scalar "15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e"))
 ;; (def! right (scalar "015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891"))

+ 80 - 48
lisp/lisp.rs

@@ -354,11 +354,6 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         let result = eval(value.clone(), env.clone())?;
                         let allocs = get_allocations(&env, "AllocationsConst");
                         allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
-                        // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
-                        // for (k, v) in allocs.borrow_mut().iter() {
-                        //     new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
-                        // }
-                        // new_hm.insert(a1.pr_str(false), result.clone());
                         if let Some(e) = &env.outer {
                             env_set(&e, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
                         } else {
@@ -374,11 +369,6 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         let result = eval(value.clone(), env.clone())?;
                         let allocs = get_allocations(&env, "AllocationsInput");
                         allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
-                        // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
-                        // for (k, v) in allocs.borrow_mut().iter() {
-                        //     new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
-                        // }
-                        // new_hm.insert(a1.pr_str(false), result.clone());
                         if let Some(e) = &env.outer {
                             env_set(&e, Sym("AllocationsInput".to_string()), Alloc(allocs))?;
                         } else {
@@ -397,11 +387,6 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         let result = eval(value.clone(), env.clone())?;
                         let allocs = get_allocations(&env, "Allocations");
                         allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
-                        // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
-                        // for (k, v) in allocs.borrow_mut().iter() {
-                        //     new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
-                        // }
-                        // new_hm.insert(a1.pr_str(false), result.clone());
                         if let Some(e) = &env.outer {
                             env_set(&e, Sym("Allocations".to_string()), Alloc(allocs))?;
                         } else {
@@ -412,62 +397,109 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                     }
                     //Sym(ref a0sym) if a0sym == "verify" => {
                     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
-                        // it means that every symbol will be on allocations and we will do the
-                        // find/replace on the bellman circuit, it's nasty v0
                         let mut left_vec = vec![];
                         let mut right_vec = vec![];
                         let mut out_vec = vec![];
-                        // todo extract a macro for this
                         match l[1].clone() {
                             List(v, _) | Vector(v, _) => {
-                                if let List(_, _) = &v.to_vec()[0] {
-                                    for ele in v.to_vec().iter() {
-                                        if let List(ele_vec, _) = ele {
-                                            left_vec.push((
-                                                ele_vec[0].pr_str(false),
-                                                ele_vec[1].pr_str(false),
-                                            ));
+                                if v.to_vec().len() > 0 {
+                                    // println!("{:?} {:?}", v, v.to_vec().len());
+                                    if let List(_, _) = &v.to_vec()[0] {
+                                        for ele in v.to_vec().iter() {
+                                            if let List(ele_vec, _) = ele {
+                                                left_vec.push((
+                                                    ele_vec[0].pr_str(false),
+                                                    ele_vec[1].pr_str(false),
+                                                ));
+                                            }
+                                        }
+                                    } else {
+                                        if v.to_vec().len() == 1 {
+                                            let result = eval(v.to_vec()[0].clone(), env.clone())?;
+                                            if let List(val, _) = result {
+                                                for ele in val.iter() {
+                                                    // println!("{:?}", ele);
+                                                    if let Vector(ele_vec, _) = ele {
+                                                        left_vec.push((
+                                                            ele_vec[0].pr_str(false),
+                                                            ele_vec[1].pr_str(false),
+                                                        ));
+                                                    }
+                                                }
+                                            }
+                                        } else {
+                                            left_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
                                         }
                                     }
-                                } else {
-                                    left_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
                                 }
                             }
                             _ => {}
                         };
                         match l[2].clone() {
                             List(v, _) | Vector(v, _) => {
-                                if let List(_, _) = &v.to_vec()[0] {
-                                    for ele in v.to_vec().iter() {
-                                        if let List(ele_vec, _) = ele {
-                                            right_vec.push((
-                                                ele_vec[0].pr_str(false),
-                                                ele_vec[1].pr_str(false),
-                                            ));
+                                if v.to_vec().len() > 0 {
+                                    if let List(_, _) = &v.to_vec()[0] {
+                                        for ele in v.to_vec().iter() {
+                                            if let List(ele_vec, _) = ele {
+                                                right_vec.push((
+                                                    ele_vec[0].pr_str(false),
+                                                    ele_vec[1].pr_str(false),
+                                                ));
+                                            }
+                                        }
+                                    } else {
+                                        if v.to_vec().len() == 1 {
+                                            let result = eval(v.to_vec()[0].clone(), env.clone())?;
+                                            if let List(val, _) = result {
+                                                for ele in val.iter() {
+                                                    // println!("{:?}", ele);
+                                                    if let Vector(ele_vec, _) = ele {
+                                                        right_vec.push((
+                                                            ele_vec[0].pr_str(false),
+                                                            ele_vec[1].pr_str(false),
+                                                        ));
+                                                    }
+                                                }
+                                            }
+                                        } else {
+                                            right_vec
+                                                .push((v[0].pr_str(false), v[1].pr_str(false)));
                                         }
                                     }
-                                } else {
-                                    right_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
                                 }
                             }
                             _ => {}
                         };
                         match l[3].clone() {
                             List(v, _) | Vector(v, _) => {
-                                if let List(_, _) = &v.to_vec()[0] {
-                                    for ele in v.to_vec().iter() {
-                                        if let List(ele_vec, _) = ele {
-                                            out_vec.push((
-                                                ele_vec[0].pr_str(false),
-                                                ele_vec[1].pr_str(false),
-                                            ));
+                                if v.to_vec().len() > 0 {
+                                    if let List(_, _) = &v.to_vec()[0] {
+                                        for ele in v.to_vec().iter() {
+                                            if let List(ele_vec, _) = ele {
+                                                out_vec.push((
+                                                    ele_vec[0].pr_str(false),
+                                                    ele_vec[1].pr_str(false),
+                                                ));
+                                            }
+                                        }
+                                    } else {
+                                        if v.to_vec().len() == 1 {
+                                            let result = eval(v.to_vec()[0].clone(), env.clone())?;
+                                            if let List(val, _) = result {
+                                                for ele in val.iter() {
+                                                    // println!("{:?}", ele);
+                                                    if let Vector(ele_vec, _) = ele {
+                                                        out_vec.push((
+                                                            ele_vec[0].pr_str(false),
+                                                            ele_vec[1].pr_str(false),
+                                                        ));
+                                                    }
+                                                }
+                                            }
+                                        } else {
+                                            out_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
                                         }
                                     }
-                                } else {
-                                    out_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
                                 }
                             }
                             _ => {}

+ 1 - 1
lisp/run.sh

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

+ 16 - 5
lisp/types.rs

@@ -79,13 +79,17 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                 MalVal::ZKScalar(val) => {
                     let var = cs.alloc(|| k, || Ok(*val))?;
                     variables.insert(k.to_string(), 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);
+                }
+                MalVal::Vector(val, _) => {
+                    if let MalVal::ZKScalar(v) = &val.to_vec()[0] {
+                        let var = cs.alloc(|| k, || Ok(*v))?;
+                        variables.insert(k.to_string(), var);
+                    }
                 }
                 _ => {
                     println!("not allocated k {:?} v {:?}", k, v);
@@ -126,6 +130,7 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                 let (a, b) = values;
                 let mut val_b = CS::one();
                 if b != "cs::one" {
+                    println!("{:?}", b);
                     val_b = *variables.get(b).unwrap();
                 }
                 if a == "scalar::one" {
@@ -142,7 +147,9 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                                 let val = bls12_381::Scalar::from_string(&s.to_string());
                                 left = left + (val, val_b);
                             }
-                            _ => println!("not a valid param {:?}", value),
+                            _ => {
+                                println!("not a valid param {:?}", value)
+                            }
                         }
                     }
                 }
@@ -169,7 +176,9 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                                 let val = bls12_381::Scalar::from_string(&s.to_string());
                                 right = right + (val, val_b);
                             }
-                            _ => println!("not a valid param {:?}", value),
+                            _ => {
+                                println!("not a valid param {:?}", value)
+                            }
                         }
                     }
                 }
@@ -197,7 +206,9 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                                 let val = bls12_381::Scalar::from_string(&s.to_string());
                                 output = output + (val, val_b);
                             }
-                            _ => println!("not a valid param {:?}", value),
+                            _ => {
+                                println!("not a valid param {:?}", value)
+                            }
                         }
                     }
                 }