lisp.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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::borrow::{Borrow, BorrowMut};
  12. use std::rc::Rc;
  13. use std::time::Instant;
  14. use std::{cell::RefCell, collections::HashMap};
  15. use types::EnforceAllocation;
  16. #[macro_use]
  17. extern crate clap;
  18. #[macro_use]
  19. extern crate lazy_static;
  20. // extern crate fnv;
  21. extern crate itertools;
  22. extern crate regex;
  23. #[macro_use]
  24. mod types;
  25. use crate::types::MalErr::{ErrMalVal, ErrString};
  26. use crate::types::MalVal::{
  27. Alloc, Bool, Enforce, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector,
  28. };
  29. use crate::types::VerifyKeyParams;
  30. use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
  31. mod env;
  32. mod printer;
  33. mod reader;
  34. use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
  35. #[macro_use]
  36. mod core;
  37. // read
  38. fn read(str: &str) -> MalRet {
  39. reader::read_str(str.to_string())
  40. }
  41. // eval
  42. fn qq_iter(elts: &MalArgs) -> MalVal {
  43. let mut acc = list![];
  44. for elt in elts.iter().rev() {
  45. if let List(v, _) = elt {
  46. if v.len() == 2 {
  47. if let Sym(ref s) = v[0] {
  48. if s == "splice-unquote" {
  49. acc = list![Sym("concat".to_string()), v[1].clone(), acc];
  50. continue;
  51. }
  52. }
  53. }
  54. }
  55. acc = list![Sym("cons".to_string()), quasiquote(&elt), acc];
  56. }
  57. return acc;
  58. }
  59. fn quasiquote(ast: &MalVal) -> MalVal {
  60. match ast {
  61. List(v, _) => {
  62. if v.len() == 2 {
  63. if let Sym(ref s) = v[0] {
  64. if s == "unquote" {
  65. return v[1].clone();
  66. }
  67. }
  68. }
  69. return qq_iter(&v);
  70. }
  71. Vector(v, _) => return list![Sym("vec".to_string()), qq_iter(&v)],
  72. Hash(_, _) | Sym(_) => return list![Sym("quote".to_string()), ast.clone()],
  73. _ => ast.clone(),
  74. }
  75. }
  76. fn is_macro_call(ast: &MalVal, env: &Env) -> Option<(MalVal, MalArgs)> {
  77. match ast {
  78. List(v, _) => match v[0] {
  79. Sym(ref s) => match env_find(env, s) {
  80. Some(e) => match env_get(&e, &v[0]) {
  81. Ok(f @ MalFunc { is_macro: true, .. }) => Some((f, v[1..].to_vec())),
  82. _ => None,
  83. },
  84. _ => None,
  85. },
  86. _ => None,
  87. },
  88. _ => None,
  89. }
  90. }
  91. fn macroexpand(mut ast: MalVal, env: &Env) -> (bool, MalRet) {
  92. let mut was_expanded = false;
  93. while let Some((mf, args)) = is_macro_call(&ast, env) {
  94. // println!("macroexpand 1: {:?}", ast);
  95. ast = match mf.apply(args) {
  96. Err(e) => return (false, Err(e)),
  97. Ok(a) => a,
  98. };
  99. // println!("macroexpand 2: {:?}", ast);
  100. was_expanded = true;
  101. }
  102. (was_expanded, Ok(ast))
  103. }
  104. fn eval_ast(ast: &MalVal, env: &Env) -> MalRet {
  105. match ast {
  106. Sym(_) => Ok(env_get(&env, &ast)?),
  107. List(v, _) => {
  108. let mut lst: MalArgs = vec![];
  109. for a in v.iter() {
  110. lst.push(eval(a.clone(), env.clone())?)
  111. }
  112. Ok(list!(lst))
  113. }
  114. Vector(v, _) => {
  115. let mut lst: MalArgs = vec![];
  116. for a in v.iter() {
  117. lst.push(eval(a.clone(), env.clone())?)
  118. }
  119. Ok(vector!(lst))
  120. }
  121. Hash(hm, _) => {
  122. let mut new_hm: HashMap<String, MalVal> = HashMap::default();
  123. for (k, v) in hm.iter() {
  124. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  125. }
  126. Ok(Hash(Rc::new(new_hm), Rc::new(Nil)))
  127. }
  128. _ => Ok(ast.clone()),
  129. }
  130. }
  131. fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
  132. let ret: MalRet;
  133. let start = Instant::now();
  134. 'tco: loop {
  135. // TODO check DEBUG symbol on env
  136. println!("debug eval \t {:?} \t {:?}", ast, start.elapsed());
  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. ast = eval_ast(&l[2], &env)?;
  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. // TODO add debug param
  333. prove(a1.clone(), env.clone())
  334. }
  335. Sym(ref a0sym) if a0sym == "kill" => {
  336. error(&format!("KILL at: {:?}", ast).to_string())
  337. }
  338. Sym(ref a0sym) if a0sym == "alloc-const" => {
  339. let start = Instant::now();
  340. let a1 = l[1].clone();
  341. let mut value = eval(l[2].clone(), env.clone())?;
  342. if let Func(_, _) = value {
  343. value = value.apply(vec![]).unwrap();
  344. }
  345. let result = eval(value.clone(), env.clone())?;
  346. let allocs = get_allocations(&env, "AllocationsConst");
  347. allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
  348. if let Some(e) = &env.outer {
  349. env_set(&e, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
  350. } else {
  351. env_set(&env, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
  352. }
  353. println!("Alloc Const: {:?}", start.elapsed());
  354. Ok(result.clone())
  355. }
  356. Sym(ref a0sym) if a0sym == "alloc-input" => {
  357. let start = Instant::now();
  358. let a1 = l[1].clone();
  359. let mut value = eval(l[2].clone(), env.clone())?;
  360. if let Func(_, _) = value {
  361. value = value.apply(vec![]).unwrap();
  362. }
  363. let result = eval(value.clone(), env.clone())?;
  364. let allocs = get_allocations(&env, "AllocationsInput");
  365. allocs.borrow_mut().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. if let Some(e) = &env.outer {
  385. env_set(&e, Sym("Allocations".to_string()), Alloc(allocs))?;
  386. } else {
  387. env_set(&env, Sym("Allocations".to_string()), Alloc(allocs))?;
  388. }
  389. println!("Alloc:\t{:?}\t{:?}\t{:?}", value, result, start.elapsed());
  390. Ok(result.clone())
  391. }
  392. //Sym(ref a0sym) if a0sym == "verify" => {
  393. Sym(ref a0sym) if a0sym == "enforce" => {
  394. let mut left_vec = vec![];
  395. let mut right_vec = vec![];
  396. let mut out_vec = vec![];
  397. match l[1].clone() {
  398. List(v, _) | Vector(v, _) => {
  399. if v.to_vec().len() > 0 {
  400. // println!("{:?} {:?}", v, v.to_vec().len());
  401. if let List(_, _) = &v.to_vec()[0] {
  402. for ele in v.to_vec().iter() {
  403. if let List(ele_vec, _) = ele {
  404. left_vec.push((
  405. ele_vec[0].pr_str(false),
  406. ele_vec[1].pr_str(false),
  407. ));
  408. }
  409. }
  410. } else {
  411. if v.to_vec().len() == 1 {
  412. let result = eval(v.to_vec()[0].clone(), env.clone())?;
  413. if let List(val, _) = result {
  414. for ele in val.iter() {
  415. // println!("{:?}", ele);
  416. if let Vector(ele_vec, _) = ele {
  417. left_vec.push((
  418. ele_vec[0].pr_str(false),
  419. ele_vec[1].pr_str(false),
  420. ));
  421. }
  422. }
  423. }
  424. } else {
  425. left_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  426. }
  427. }
  428. }
  429. }
  430. _ => {}
  431. };
  432. match l[2].clone() {
  433. List(v, _) | Vector(v, _) => {
  434. if v.to_vec().len() > 0 {
  435. if let List(_, _) = &v.to_vec()[0] {
  436. for ele in v.to_vec().iter() {
  437. if let List(ele_vec, _) = ele {
  438. right_vec.push((
  439. ele_vec[0].pr_str(false),
  440. ele_vec[1].pr_str(false),
  441. ));
  442. }
  443. }
  444. } else {
  445. if v.to_vec().len() == 1 {
  446. let result = eval(v.to_vec()[0].clone(), env.clone())?;
  447. if let List(val, _) = result {
  448. for ele in val.iter() {
  449. // println!("{:?}", ele);
  450. if let Vector(ele_vec, _) = ele {
  451. right_vec.push((
  452. ele_vec[0].pr_str(false),
  453. ele_vec[1].pr_str(false),
  454. ));
  455. }
  456. }
  457. }
  458. } else {
  459. right_vec
  460. .push((v[0].pr_str(false), v[1].pr_str(false)));
  461. }
  462. }
  463. }
  464. }
  465. _ => {}
  466. };
  467. match l[3].clone() {
  468. List(v, _) | Vector(v, _) => {
  469. if v.to_vec().len() > 0 {
  470. if let List(_, _) = &v.to_vec()[0] {
  471. for ele in v.to_vec().iter() {
  472. if let List(ele_vec, _) = ele {
  473. out_vec.push((
  474. ele_vec[0].pr_str(false),
  475. ele_vec[1].pr_str(false),
  476. ));
  477. }
  478. }
  479. } else {
  480. if v.to_vec().len() == 1 {
  481. let result = eval(v.to_vec()[0].clone(), env.clone())?;
  482. if let List(val, _) = result {
  483. for ele in val.iter() {
  484. // println!("{:?}", ele);
  485. if let Vector(ele_vec, _) = ele {
  486. out_vec.push((
  487. ele_vec[0].pr_str(false),
  488. ele_vec[1].pr_str(false),
  489. ));
  490. }
  491. }
  492. }
  493. } else {
  494. out_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  495. }
  496. }
  497. }
  498. }
  499. _ => {}
  500. };
  501. let mut enforce_vec = get_enforce_allocs(&env).clone();
  502. let enforce = EnforceAllocation {
  503. idx: enforce_vec.len() + 1,
  504. left: left_vec,
  505. right: right_vec,
  506. output: out_vec,
  507. };
  508. enforce_vec.push(enforce);
  509. if let Some(e) = &env.outer {
  510. env_set(
  511. &e,
  512. Sym("AllocationsEnforce".to_string()),
  513. vector![vec![Enforce(Rc::new(enforce_vec))]],
  514. )?;
  515. } else {
  516. env_set(
  517. &env,
  518. Sym("AllocationsEnforce".to_string()),
  519. vector![vec![Enforce(Rc::new(enforce_vec))]],
  520. )?;
  521. }
  522. Ok(MalVal::Str("enforce-eof".to_string()))
  523. }
  524. _ => match eval_ast(&ast, &env)? {
  525. List(ref el, _) => {
  526. let ref f = el[0].clone();
  527. let args = el[1..].to_vec();
  528. match f {
  529. Func(_, _) => f.apply(args),
  530. MalFunc {
  531. ast: mast,
  532. env: menv,
  533. params,
  534. ..
  535. } => {
  536. let a = &**mast;
  537. let p = &**params;
  538. env = env_bind(Some(menv.clone()), p.clone(), args)?;
  539. ast = a.clone();
  540. continue 'tco;
  541. }
  542. _ => {
  543. // println!("{:?}", args);
  544. Ok(vector![el.to_vec()])
  545. //error("call non-function")
  546. }
  547. }
  548. }
  549. _ => error("expected a list"),
  550. },
  551. }
  552. }
  553. _ => eval_ast(&ast, &env),
  554. };
  555. break;
  556. } // end 'tco loop
  557. // println!("debug eval \t {:?} \t {:?}", ast, start.elapsed());
  558. ret
  559. }
  560. pub fn get_enforce_allocs(env: &Env) -> Vec<EnforceAllocation> {
  561. if let Some(e) = &env.outer {
  562. get_enforce_allocs_nested(&e)
  563. } else {
  564. get_enforce_allocs_nested(&env)
  565. }
  566. }
  567. pub fn get_enforce_allocs_nested(env: &Env) -> Vec<EnforceAllocation> {
  568. match env_find(env, "AllocationsEnforce") {
  569. Some(e) => match env_get(&e, &Sym("AllocationsEnforce".to_string())) {
  570. Ok(f) => {
  571. if let Vector(val, _) = f {
  572. if let Enforce(ret) = &val[0] {
  573. ret.to_vec()
  574. } else {
  575. vec![]
  576. }
  577. } else {
  578. vec![]
  579. }
  580. }
  581. _ => vec![],
  582. },
  583. _ => vec![],
  584. }
  585. }
  586. pub fn get_allocations(env: &Env, key: &str) -> RefCell<HashMap<String, MalVal>> {
  587. if let Some(e) = &env.outer {
  588. get_allocations_nested(&e, key)
  589. } else {
  590. get_allocations_nested(&env, key)
  591. }
  592. }
  593. pub fn get_allocations_nested(env: &Env, key: &str) -> RefCell<HashMap<String, MalVal>> {
  594. let alloc_hm: RefCell<HashMap<String, MalVal>> = RefCell::new(HashMap::default());
  595. match env_find(env, key) {
  596. Some(e) => match env_get(&e, &Sym(key.to_string())) {
  597. Ok(f) => {
  598. if let MalVal::Alloc(allocs) = f {
  599. allocs
  600. } else {
  601. alloc_hm
  602. }
  603. }
  604. _ => alloc_hm,
  605. },
  606. _ => alloc_hm,
  607. }
  608. }
  609. pub fn setup(_ast: MalVal, env: Env) -> Result<VerifyKeyParams, MalErr> {
  610. let start = Instant::now();
  611. let c = LispCircuit {
  612. params: HashMap::default(),
  613. allocs: HashMap::default(),
  614. alloc_inputs: HashMap::default(),
  615. constraints: Vec::new(),
  616. };
  617. let random_parameters =
  618. groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap();
  619. let pvk = groth16::prepare_verifying_key(&random_parameters.vk);
  620. println!("Setup: [{:?}]", start.elapsed());
  621. Ok(VerifyKeyParams {
  622. verifying_key: pvk,
  623. random_params: random_parameters,
  624. })
  625. }
  626. pub fn prove(_ast: MalVal, env: Env) -> MalRet {
  627. let start = Instant::now();
  628. let allocs_input = get_allocations(&env, "AllocationsInput");
  629. let allocs = get_allocations(&env, "Allocations");
  630. let enforce_allocs = get_enforce_allocs(&env);
  631. let allocs_const = get_allocations(&env, "AllocationsConst");
  632. //setup
  633. let params = Some({
  634. let circuit = LispCircuit {
  635. params: allocs_const.borrow().clone(),
  636. allocs: allocs.borrow().clone(),
  637. alloc_inputs: allocs_input.borrow().clone(),
  638. constraints: enforce_allocs.clone(),
  639. };
  640. groth16::generate_random_parameters::<Bls12, _, _>(circuit, &mut OsRng)?
  641. });
  642. let verifying_key = Some(groth16::prepare_verifying_key(&params.as_ref().unwrap().vk));
  643. // prove
  644. let circuit = LispCircuit {
  645. params: allocs_const.borrow().clone(),
  646. allocs: allocs.borrow().clone(),
  647. alloc_inputs: allocs_input.borrow().clone(),
  648. constraints: enforce_allocs.clone(),
  649. };
  650. let proof = groth16::create_random_proof(circuit, params.as_ref().unwrap(), &mut OsRng)?;
  651. let mut vec_input = vec![];
  652. for (k, val) in allocs_input.borrow_mut().iter() {
  653. match val {
  654. MalVal::Str(v) => {
  655. vec_input.push(bls12_381::Scalar::from_string(&v.to_string()));
  656. }
  657. MalVal::ZKScalar(v) => {
  658. vec_input.push(bls12_381::Scalar::from(*v));
  659. }
  660. _ => {}
  661. };
  662. }
  663. println!("groth16::create_random_proof: {:?}", start.elapsed());
  664. // verification process
  665. let start = Instant::now();
  666. let result = groth16::verify_proof(verifying_key.as_ref().unwrap(), &proof, &vec_input);
  667. println!("groth16::verify_proof: {:?}", start.elapsed());
  668. println!("vec public {:?}", vec_input);
  669. println!("result {:?}", result);
  670. Ok(MalVal::Nil)
  671. }
  672. pub fn verify(_ast: &MalVal) -> MalRet {
  673. let _public_input = vec![bls12_381::Scalar::from(27)];
  674. let start = Instant::now();
  675. println!("Verify: [{:?}]", start.elapsed());
  676. Ok(MalVal::Nil)
  677. }
  678. // print
  679. fn print(ast: &MalVal) -> String {
  680. ast.pr_str(true)
  681. }
  682. fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
  683. let ast = read(str)?;
  684. let exp = eval(ast, env.clone())?;
  685. Ok(print(&exp))
  686. }
  687. fn main() -> Result<(), ()> {
  688. let matches = clap_app!(zklisp =>
  689. (version: "0.1.0")
  690. (author: "Dark Renaissance")
  691. (about: "A Lisp Interpreter for Zero Knowledge Virtual Machine")
  692. (@subcommand load =>
  693. (about: "Load the file into the interpreter")
  694. (@arg FILE: +required "Lisp Contract filename")
  695. )
  696. )
  697. .get_matches();
  698. // CombinedLogger::init(vec![TermLogger::new(
  699. // LevelFilter::Debug,
  700. // Config::default(),
  701. // TerminalMode::Mixed,
  702. // )
  703. // .unwrap()])
  704. // .unwrap();
  705. match matches.subcommand() {
  706. Some(("load", matches)) => {
  707. let file: String = matches.value_of("FILE").unwrap().parse().unwrap();
  708. repl_load(file)?;
  709. }
  710. _ => {
  711. eprintln!("error: Invalid subcommand invoked");
  712. std::process::exit(-1);
  713. }
  714. }
  715. Ok(())
  716. }
  717. fn repl_load(file: String) -> Result<(), ()> {
  718. let start = Instant::now();
  719. let repl_env = env_new(None);
  720. for (k, v) in core::ns() {
  721. env_sets(&repl_env, k, v);
  722. }
  723. let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
  724. let _ = rep(
  725. "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
  726. &repl_env,
  727. );
  728. match rep(&format!("(load-file \"{}\")", file), &repl_env) {
  729. Ok(_) => {
  730. println!("lisp end \t {:?}", start.elapsed());
  731. std::process::exit(0)
  732. }
  733. Err(e) => {
  734. println!("Error: {}", format_error(e));
  735. std::process::exit(1);
  736. }
  737. }
  738. }
  739. #[cfg(test)]
  740. mod tests {
  741. #[test]
  742. fn it_works() {
  743. assert_eq!(2 + 2, 4);
  744. }
  745. }