lisp.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. #![allow(non_snake_case)]
  2. use crate::types::LispCircuit;
  3. use bellman::groth16::PreparedVerifyingKey;
  4. use sapvi::{BlsStringConversion, Decodable, Encodable, ZKContract, ZKProof};
  5. use simplelog::*;
  6. use bellman::groth16;
  7. use bls12_381::Bls12;
  8. // use fnv::FnvHashMap;
  9. use itertools::Itertools;
  10. use rand::rngs::OsRng;
  11. use std::rc::Rc;
  12. use std::time::Instant;
  13. use std::{
  14. borrow::{Borrow, BorrowMut},
  15. fs,
  16. };
  17. use std::{cell::RefCell, collections::HashMap};
  18. use types::EnforceAllocation;
  19. #[macro_use]
  20. extern crate clap;
  21. #[macro_use]
  22. extern crate lazy_static;
  23. // extern crate fnv;
  24. extern crate itertools;
  25. extern crate regex;
  26. #[macro_use]
  27. mod types;
  28. use crate::types::MalErr::{ErrMalVal, ErrString};
  29. use crate::types::MalVal::{
  30. Alloc, Bool, Enforce, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector,
  31. };
  32. use crate::types::VerifyKeyParams;
  33. use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
  34. mod env;
  35. mod printer;
  36. mod reader;
  37. use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
  38. #[macro_use]
  39. mod core;
  40. // read
  41. fn read(str: &str) -> MalRet {
  42. reader::read_str(str.to_string())
  43. }
  44. // eval
  45. fn qq_iter(elts: &MalArgs) -> MalVal {
  46. let mut acc = list![];
  47. for elt in elts.iter().rev() {
  48. if let List(v, _) = elt {
  49. if v.len() == 2 {
  50. if let Sym(ref s) = v[0] {
  51. if s == "splice-unquote" {
  52. acc = list![Sym("concat".to_string()), v[1].clone(), acc];
  53. continue;
  54. }
  55. }
  56. }
  57. }
  58. acc = list![Sym("cons".to_string()), quasiquote(&elt), acc];
  59. }
  60. return acc;
  61. }
  62. fn quasiquote(ast: &MalVal) -> MalVal {
  63. match ast {
  64. List(v, _) => {
  65. if v.len() == 2 {
  66. if let Sym(ref s) = v[0] {
  67. if s == "unquote" {
  68. return v[1].clone();
  69. }
  70. }
  71. }
  72. return qq_iter(&v);
  73. }
  74. Vector(v, _) => return list![Sym("vec".to_string()), qq_iter(&v)],
  75. Hash(_, _) | Sym(_) => return list![Sym("quote".to_string()), ast.clone()],
  76. _ => ast.clone(),
  77. }
  78. }
  79. fn is_macro_call(ast: &MalVal, env: &Env) -> Option<(MalVal, MalArgs)> {
  80. match ast {
  81. List(v, _) => match v[0] {
  82. Sym(ref s) => match env_find(env, s) {
  83. Some(e) => match env_get(&e, &v[0]) {
  84. Ok(f @ MalFunc { is_macro: true, .. }) => Some((f, v[1..].to_vec())),
  85. _ => None,
  86. },
  87. _ => None,
  88. },
  89. _ => None,
  90. },
  91. _ => None,
  92. }
  93. }
  94. fn macroexpand(mut ast: MalVal, env: &Env) -> (bool, MalRet) {
  95. let mut was_expanded = false;
  96. while let Some((mf, args)) = is_macro_call(&ast, env) {
  97. // println!("macroexpand 1: {:?}", ast);
  98. ast = match mf.apply(args) {
  99. Err(e) => return (false, Err(e)),
  100. Ok(a) => a,
  101. };
  102. // println!("macroexpand 2: {:?}", ast);
  103. was_expanded = true;
  104. }
  105. (was_expanded, Ok(ast))
  106. }
  107. fn eval_ast(ast: &MalVal, env: &Env) -> MalRet {
  108. match ast {
  109. Sym(_) => Ok(env_get(&env, &ast)?),
  110. List(v, _) => {
  111. let mut lst: MalArgs = vec![];
  112. for a in v.iter() {
  113. lst.push(eval(a.clone(), env.clone())?)
  114. }
  115. Ok(list!(lst))
  116. }
  117. Vector(v, _) => {
  118. let mut lst: MalArgs = vec![];
  119. for a in v.iter() {
  120. lst.push(eval(a.clone(), env.clone())?)
  121. }
  122. Ok(vector!(lst))
  123. }
  124. Hash(hm, _) => {
  125. let mut new_hm: HashMap<String, MalVal> = HashMap::default();
  126. for (k, v) in hm.iter() {
  127. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  128. }
  129. Ok(Hash(Rc::new(new_hm), Rc::new(Nil)))
  130. }
  131. _ => Ok(ast.clone()),
  132. }
  133. }
  134. fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
  135. let ret: MalRet;
  136. 'tco: loop {
  137. ret = match ast.clone() {
  138. List(l, _) => {
  139. if l.len() == 0 {
  140. return Ok(ast);
  141. }
  142. match macroexpand(ast.clone(), &env) {
  143. (true, Ok(new_ast)) => {
  144. ast = new_ast;
  145. continue 'tco;
  146. }
  147. (_, Err(e)) => return Err(e),
  148. _ => (),
  149. }
  150. if l.len() == 0 {
  151. return Ok(ast);
  152. }
  153. let a0 = &l[0];
  154. match a0 {
  155. Sym(ref a0sym) if a0sym == "def!" => {
  156. env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
  157. }
  158. Sym(ref a0sym) if a0sym == "zk*" => {
  159. // println!("zk* {:?}", l[1]);
  160. let (a1, a2) = (l[1].clone(), l[2].clone());
  161. match a1 {
  162. List(ref binds, _) | Vector(ref binds, _) => {
  163. for (b, e) in binds.iter().tuples() {
  164. match b {
  165. Sym(_) => {
  166. let _ = env_set(
  167. &env,
  168. b.clone(),
  169. eval(e.clone(), env.clone())?,
  170. );
  171. }
  172. _ => {
  173. return error("let* with non-Sym binding");
  174. }
  175. }
  176. }
  177. }
  178. _ => {
  179. return error("let* with non-List bindings");
  180. }
  181. };
  182. ast = a2;
  183. continue 'tco;
  184. }
  185. Sym(ref a0sym) if a0sym == "let*" => {
  186. env = env_new(Some(env.clone()));
  187. let (a1, a2) = (l[1].clone(), l[2].clone());
  188. match a1 {
  189. List(ref binds, _) | Vector(ref binds, _) => {
  190. for (b, e) in binds.iter().tuples() {
  191. match b {
  192. Sym(_) => {
  193. let _ = env_set(
  194. &env,
  195. b.clone(),
  196. eval(e.clone(), env.clone())?,
  197. );
  198. }
  199. _ => {
  200. return error("let* with non-Sym binding");
  201. }
  202. }
  203. }
  204. }
  205. _ => {
  206. return error("let* with non-List bindings");
  207. }
  208. };
  209. ast = a2;
  210. continue 'tco;
  211. }
  212. Sym(ref a0sym) if a0sym == "quote" => Ok(l[1].clone()),
  213. Sym(ref a0sym) if a0sym == "quasiquoteexpand" => Ok(quasiquote(&l[1])),
  214. Sym(ref a0sym) if a0sym == "quasiquote" => {
  215. ast = quasiquote(&l[1]);
  216. continue 'tco;
  217. }
  218. Sym(ref a0sym) if a0sym == "defmacro!" => {
  219. let (a1, a2) = (l[1].clone(), l[2].clone());
  220. let r = eval(a2, env.clone())?;
  221. match r {
  222. MalFunc {
  223. eval,
  224. ast,
  225. env,
  226. params,
  227. ..
  228. } => Ok(env_set(
  229. &env,
  230. a1.clone(),
  231. MalFunc {
  232. eval: eval,
  233. ast: ast.clone(),
  234. env: env.clone(),
  235. params: params.clone(),
  236. is_macro: true,
  237. meta: Rc::new(Nil),
  238. },
  239. )?),
  240. _ => error("set_macro on non-function"),
  241. }
  242. }
  243. Sym(ref a0sym) if a0sym == "macroexpand" => {
  244. match macroexpand(l[1].clone(), &env) {
  245. (_, Ok(new_ast)) => Ok(new_ast),
  246. (_, e) => return e,
  247. }
  248. }
  249. Sym(ref a0sym) if a0sym == "try*" => match eval(l[1].clone(), env.clone()) {
  250. Err(ref e) if l.len() >= 3 => {
  251. let exc = match e {
  252. ErrMalVal(mv) => mv.clone(),
  253. ErrString(s) => Str(s.to_string()),
  254. };
  255. match l[2].clone() {
  256. List(c, _) => {
  257. let catch_env = env_bind(
  258. Some(env.clone()),
  259. list!(vec![c[1].clone()]),
  260. vec![exc],
  261. )?;
  262. eval(c[2].clone(), catch_env)
  263. }
  264. _ => error("invalid catch block"),
  265. }
  266. }
  267. res => res,
  268. },
  269. Sym(ref a0sym) if a0sym == "do" => {
  270. match eval_ast(&list!(l[1..l.len() - 1].to_vec()), &env)? {
  271. List(_, _) => {
  272. ast = l.last().unwrap_or(&Nil).clone();
  273. continue 'tco;
  274. }
  275. _ => error("invalid do form"),
  276. }
  277. }
  278. Sym(ref a0sym) if a0sym == "dotimes" => {
  279. match eval(l[1].clone(), env.clone())? {
  280. MalVal::Int(v) => {
  281. for _i in 0..v {
  282. eval(l[2].clone(), env.clone())?;
  283. }
  284. Ok(Nil)
  285. }
  286. _ => error("invalid args for dotimes"),
  287. }
  288. }
  289. Sym(ref a0sym) if a0sym == "if" => {
  290. let cond = eval(l[1].clone(), env.clone())?;
  291. match cond {
  292. Bool(false) | Nil if l.len() >= 4 => {
  293. ast = l[3].clone();
  294. continue 'tco;
  295. }
  296. Bool(false) | Nil => Ok(Nil),
  297. _ if l.len() >= 3 => {
  298. ast = l[2].clone();
  299. continue 'tco;
  300. }
  301. _ => Ok(Nil),
  302. }
  303. }
  304. Sym(ref a0sym) if a0sym == "fn*" => {
  305. let (a1, a2) = (l[1].clone(), l[2].clone());
  306. Ok(MalFunc {
  307. eval: eval,
  308. ast: Rc::new(a2),
  309. env: env,
  310. params: Rc::new(a1),
  311. is_macro: false,
  312. meta: Rc::new(Nil),
  313. })
  314. }
  315. Sym(ref a0sym) if a0sym == "eval" => {
  316. ast = eval(l[1].clone(), env.clone())?;
  317. while let Some(ref e) = env.clone().outer {
  318. env = e.clone();
  319. }
  320. continue 'tco;
  321. }
  322. Sym(ref a0sym) if a0sym == "setup" => {
  323. let a1 = l[1].clone();
  324. // todo
  325. ast = eval(a1.clone(), env.clone())?;
  326. // let _pvk = setup(a1.clone(), env.clone())?;
  327. continue 'tco;
  328. }
  329. Sym(ref a0sym) if a0sym == "prove" => {
  330. let a1 = l[1].clone();
  331. eval(a1.clone(), env.clone())?;
  332. prove(a1.clone(), env.clone())
  333. }
  334. Sym(ref a0sym) if a0sym == "alloc-const" => {
  335. // let start = Instant::now();
  336. let a1 = l[1].clone();
  337. let value = eval(l[2].clone(), env.clone())?;
  338. let result = eval(value.clone(), env.clone())?;
  339. let allocs = get_allocations(&env, "AllocationsConst");
  340. allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
  341. // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
  342. // for (k, v) in allocs.borrow_mut().iter() {
  343. // new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  344. // }
  345. // new_hm.insert(a1.pr_str(false), result.clone());
  346. if let Some(e) = &env.outer {
  347. env_set(&e, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
  348. } else {
  349. env_set(&env, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
  350. }
  351. // println!("Alloc Const: {:?}", start.elapsed());
  352. Ok(result.clone())
  353. }
  354. Sym(ref a0sym) if a0sym == "alloc-input" => {
  355. // let start = Instant::now();
  356. let a1 = l[1].clone();
  357. let value = eval(l[2].clone(), env.clone())?;
  358. let result = eval(value.clone(), env.clone())?;
  359. let allocs = get_allocations(&env, "AllocationsInput");
  360. allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
  361. // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
  362. // for (k, v) in allocs.borrow_mut().iter() {
  363. // new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  364. // }
  365. // new_hm.insert(a1.pr_str(false), result.clone());
  366. if let Some(e) = &env.outer {
  367. env_set(&e, Sym("AllocationsInput".to_string()), Alloc(allocs))?;
  368. } else {
  369. env_set(&env, Sym("AllocationsInput".to_string()), Alloc(allocs))?;
  370. }
  371. // println!("Alloc Input: {:?}", start.elapsed());
  372. Ok(result.clone())
  373. }
  374. Sym(ref a0sym) if a0sym == "alloc" => {
  375. // let start = Instant::now();
  376. let a1 = l[1].clone();
  377. let mut value = eval(l[2].clone(), env.clone())?;
  378. if let Func(_, _) = value {
  379. value = value.apply(vec![]).unwrap();
  380. }
  381. let result = eval(value.clone(), env.clone())?;
  382. let allocs = get_allocations(&env, "Allocations");
  383. allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
  384. // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
  385. // for (k, v) in allocs.borrow_mut().iter() {
  386. // new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  387. // }
  388. // new_hm.insert(a1.pr_str(false), result.clone());
  389. if let Some(e) = &env.outer {
  390. env_set(&e, Sym("Allocations".to_string()), Alloc(allocs))?;
  391. } else {
  392. env_set(&env, Sym("Allocations".to_string()), Alloc(allocs))?;
  393. }
  394. // println!("Alloc: {:?}", start.elapsed());
  395. Ok(result.clone())
  396. }
  397. //Sym(ref a0sym) if a0sym == "verify" => {
  398. Sym(ref a0sym) if a0sym == "enforce" => {
  399. // here i'm considering that we always have tuple with only two elements
  400. // also it's important to keep in mind for the sake of brevity of this v0
  401. // we will not allow calculation or any lisp evaluations inside the enforce
  402. // it means that every symbol will be on allocations and we will do the
  403. // find/replace on the bellman circuit, it's nasty v0
  404. let mut left_vec = vec![];
  405. let mut right_vec = vec![];
  406. let mut out_vec = vec![];
  407. // todo extract a macro for this
  408. match l[1].clone() {
  409. List(v, _) | Vector(v, _) => {
  410. if let List(_, _) = &v.to_vec()[0] {
  411. for ele in v.to_vec().iter() {
  412. if let List(ele_vec, _) = ele {
  413. left_vec.push((
  414. ele_vec[0].pr_str(false),
  415. ele_vec[1].pr_str(false),
  416. ));
  417. }
  418. }
  419. } else {
  420. left_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  421. }
  422. }
  423. _ => {}
  424. };
  425. match l[2].clone() {
  426. List(v, _) | Vector(v, _) => {
  427. if let List(_, _) = &v.to_vec()[0] {
  428. for ele in v.to_vec().iter() {
  429. if let List(ele_vec, _) = ele {
  430. right_vec.push((
  431. ele_vec[0].pr_str(false),
  432. ele_vec[1].pr_str(false),
  433. ));
  434. }
  435. }
  436. } else {
  437. right_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  438. }
  439. }
  440. _ => {}
  441. };
  442. match l[3].clone() {
  443. List(v, _) | Vector(v, _) => {
  444. if let List(_, _) = &v.to_vec()[0] {
  445. for ele in v.to_vec().iter() {
  446. if let List(ele_vec, _) = ele {
  447. out_vec.push((
  448. ele_vec[0].pr_str(false),
  449. ele_vec[1].pr_str(false),
  450. ));
  451. }
  452. }
  453. } else {
  454. out_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  455. }
  456. }
  457. _ => {}
  458. };
  459. let mut enforce_vec = get_enforce_allocs(&env).clone();
  460. let enforce = EnforceAllocation {
  461. idx: enforce_vec.len() + 1,
  462. left: left_vec,
  463. right: right_vec,
  464. output: out_vec,
  465. };
  466. enforce_vec.push(enforce);
  467. // let mut new_vec: Vec<EnforceAllocation> = vec![enforce];
  468. // for value in enforce_vec.iter() {
  469. // new_vec.push(value.clone());
  470. // }
  471. if let Some(e) = &env.outer {
  472. env_set(
  473. &e,
  474. Sym("AllocationsEnforce".to_string()),
  475. vector![vec![Enforce(Rc::new(enforce_vec))]],
  476. )?;
  477. } else {
  478. env_set(
  479. &env,
  480. Sym("AllocationsEnforce".to_string()),
  481. vector![vec![Enforce(Rc::new(enforce_vec))]],
  482. )?;
  483. }
  484. // println!(
  485. // "allocs here {:?}",
  486. // get_allocations_nested(&env, "Allocations")
  487. // );
  488. // println!("enforce here {:?}", get_enforce_allocs_nested(&env));
  489. Ok(MalVal::Str("enforce-eof".to_string()))
  490. }
  491. _ => match eval_ast(&ast, &env)? {
  492. List(ref el, _) => {
  493. let ref f = el[0].clone();
  494. let args = el[1..].to_vec();
  495. match f {
  496. Func(_, _) => f.apply(args),
  497. MalFunc {
  498. ast: mast,
  499. env: menv,
  500. params,
  501. ..
  502. } => {
  503. let a = &**mast;
  504. let p = &**params;
  505. env = env_bind(Some(menv.clone()), p.clone(), args)?;
  506. ast = a.clone();
  507. continue 'tco;
  508. }
  509. _ => {
  510. // println!("{:?}", args);
  511. Ok(vector![el.to_vec()])
  512. //error("call non-function")
  513. }
  514. }
  515. }
  516. _ => error("expected a list"),
  517. },
  518. }
  519. }
  520. _ => eval_ast(&ast, &env),
  521. };
  522. break;
  523. } // end 'tco loop
  524. ret
  525. }
  526. pub fn get_enforce_allocs(env: &Env) -> Vec<EnforceAllocation> {
  527. if let Some(e) = &env.outer {
  528. get_enforce_allocs_nested(&e)
  529. } else {
  530. get_enforce_allocs_nested(&env)
  531. }
  532. }
  533. pub fn get_enforce_allocs_nested(env: &Env) -> Vec<EnforceAllocation> {
  534. match env_find(env, "AllocationsEnforce") {
  535. Some(e) => match env_get(&e, &Sym("AllocationsEnforce".to_string())) {
  536. Ok(f) => {
  537. if let Vector(val, _) = f {
  538. if let Enforce(ret) = &val[0] {
  539. ret.to_vec()
  540. } else {
  541. vec![]
  542. }
  543. } else {
  544. vec![]
  545. }
  546. }
  547. _ => vec![],
  548. },
  549. _ => vec![],
  550. }
  551. }
  552. pub fn get_allocations(env: &Env, key: &str) -> RefCell<HashMap<String, MalVal>> {
  553. if let Some(e) = &env.outer {
  554. get_allocations_nested(&e, key)
  555. } else {
  556. get_allocations_nested(&env, key)
  557. }
  558. }
  559. pub fn get_allocations_nested(env: &Env, key: &str) -> RefCell<HashMap<String, MalVal>> {
  560. let alloc_hm: RefCell<HashMap<String, MalVal>> = RefCell::new(HashMap::default());
  561. match env_find(env, key) {
  562. Some(e) => match env_get(&e, &Sym(key.to_string())) {
  563. Ok(f) => {
  564. if let MalVal::Alloc(allocs) = f {
  565. allocs
  566. } else {
  567. alloc_hm
  568. }
  569. }
  570. _ => alloc_hm,
  571. },
  572. _ => alloc_hm,
  573. }
  574. }
  575. pub fn setup(_ast: MalVal, env: Env) -> Result<VerifyKeyParams, MalErr> {
  576. let start = Instant::now();
  577. let c = LispCircuit {
  578. params: HashMap::default(),
  579. allocs: HashMap::default(),
  580. alloc_inputs: HashMap::default(),
  581. constraints: Vec::new(),
  582. };
  583. let random_parameters =
  584. groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap();
  585. let pvk = groth16::prepare_verifying_key(&random_parameters.vk);
  586. println!("Setup: [{:?}]", start.elapsed());
  587. Ok(VerifyKeyParams {
  588. verifying_key: pvk,
  589. random_params: random_parameters,
  590. })
  591. }
  592. pub fn prove(_ast: MalVal, env: Env) -> MalRet {
  593. let start = Instant::now();
  594. let allocs_input = get_allocations(&env, "AllocationsInput");
  595. let allocs = get_allocations(&env, "Allocations");
  596. let enforce_allocs = get_enforce_allocs(&env);
  597. let allocs_const = get_allocations(&env, "AllocationsConst");
  598. //setup
  599. let params = Some({
  600. let circuit = LispCircuit {
  601. params: allocs_const.borrow().clone(),
  602. allocs: allocs.borrow().clone(),
  603. alloc_inputs: allocs_input.borrow().clone(),
  604. constraints: enforce_allocs.clone(),
  605. };
  606. groth16::generate_random_parameters::<Bls12, _, _>(circuit, &mut OsRng)?
  607. });
  608. let verifying_key = Some(groth16::prepare_verifying_key(&params.as_ref().unwrap().vk));
  609. // prove
  610. let circuit = LispCircuit {
  611. params: allocs_const.borrow().clone(),
  612. allocs: allocs.borrow().clone(),
  613. alloc_inputs: allocs_input.borrow().clone(),
  614. constraints: enforce_allocs.clone(),
  615. };
  616. let proof = groth16::create_random_proof(circuit, params.as_ref().unwrap(), &mut OsRng)?;
  617. let mut vec_input = vec![];
  618. for (k, val) in allocs_input.borrow_mut().iter() {
  619. match val {
  620. MalVal::Str(v) => {
  621. vec_input.push(bls12_381::Scalar::from_string(&v.to_string()));
  622. }
  623. MalVal::ZKScalar(v) => {
  624. vec_input.push(bls12_381::Scalar::from(*v));
  625. }
  626. _ => {}
  627. };
  628. }
  629. let result = groth16::verify_proof(verifying_key.as_ref().unwrap(), &proof, &vec_input);
  630. println!("vec public {:?}", vec_input);
  631. println!("result {:?}", result);
  632. println!("Elapsed time: {:?}", start.elapsed());
  633. Ok(MalVal::Nil)
  634. }
  635. pub fn verify(_ast: &MalVal) -> MalRet {
  636. let _public_input = vec![bls12_381::Scalar::from(27)];
  637. let start = Instant::now();
  638. println!("Verify: [{:?}]", start.elapsed());
  639. Ok(MalVal::Nil)
  640. }
  641. // print
  642. fn print(ast: &MalVal) -> String {
  643. ast.pr_str(true)
  644. }
  645. fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
  646. let ast = read(str)?;
  647. let exp = eval(ast, env.clone())?;
  648. Ok(print(&exp))
  649. }
  650. fn main() -> Result<(), ()> {
  651. let matches = clap_app!(zklisp =>
  652. (version: "0.1.0")
  653. (author: "Dark Renaissance")
  654. (about: "A Lisp Interpreter for Zero Knowledge Virtual Machine")
  655. (@subcommand load =>
  656. (about: "Load the file into the interpreter")
  657. (@arg FILE: +required "Lisp Contract filename")
  658. )
  659. )
  660. .get_matches();
  661. // CombinedLogger::init(vec![TermLogger::new(
  662. // LevelFilter::Debug,
  663. // Config::default(),
  664. // TerminalMode::Mixed,
  665. // )
  666. // .unwrap()])
  667. // .unwrap();
  668. match matches.subcommand() {
  669. Some(("load", matches)) => {
  670. let file: String = matches.value_of("FILE").unwrap().parse().unwrap();
  671. repl_load(file)?;
  672. }
  673. _ => {
  674. eprintln!("error: Invalid subcommand invoked");
  675. std::process::exit(-1);
  676. }
  677. }
  678. Ok(())
  679. }
  680. fn repl_load(file: String) -> Result<(), ()> {
  681. let repl_env = env_new(None);
  682. for (k, v) in core::ns() {
  683. env_sets(&repl_env, k, v);
  684. }
  685. let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
  686. let _ = rep(
  687. "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
  688. &repl_env,
  689. );
  690. match rep(&format!("(load-file \"{}\")", file), &repl_env) {
  691. Ok(_) => std::process::exit(0),
  692. Err(e) => {
  693. println!("Error: {}", format_error(e));
  694. std::process::exit(1);
  695. }
  696. }
  697. }