lisp.rs 32 KB

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