lisp.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. #![allow(non_snake_case)]
  2. use crate::groth16::VerifyingKey;
  3. use crate::types::LispCircuit;
  4. use crate::MalVal::Zk;
  5. use sapvi::bls_extensions::BlsStringConversion;
  6. use sapvi::{ZKVMCircuit, ZKVirtualMachine};
  7. use simplelog::*;
  8. use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError};
  9. use bls12_381::Bls12;
  10. use bls12_381::Scalar;
  11. use ff::{Field, PrimeField};
  12. use rand::rngs::OsRng;
  13. use std::{cell::RefCell, ops::{AddAssign, MulAssign, SubAssign}};
  14. use std::rc::Rc;
  15. use std::time::Instant;
  16. //use std::collections::HashMap;
  17. use fnv::FnvHashMap;
  18. use itertools::Itertools;
  19. use MalVal::ZKScalar;
  20. #[macro_use]
  21. extern crate clap;
  22. #[macro_use]
  23. extern crate lazy_static;
  24. extern crate fnv;
  25. extern crate itertools;
  26. extern crate regex;
  27. #[macro_use]
  28. mod types;
  29. use crate::types::MalErr::{ErrMalVal, ErrString};
  30. use crate::types::MalVal::{Bool, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector};
  31. use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
  32. mod env;
  33. mod printer;
  34. mod reader;
  35. use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
  36. #[macro_use]
  37. mod core;
  38. pub const ZK_CIRCUIT_ENV_KEY: &str = "ZKC";
  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: FnvHashMap<String, MalVal> = FnvHashMap::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. 'tco: loop {
  136. ret = match ast.clone() {
  137. List(l, _) => {
  138. if l.len() == 0 {
  139. return Ok(ast);
  140. }
  141. match macroexpand(ast.clone(), &env) {
  142. (true, Ok(new_ast)) => {
  143. ast = new_ast;
  144. continue 'tco;
  145. }
  146. (_, Err(e)) => return Err(e),
  147. _ => (),
  148. }
  149. if l.len() == 0 {
  150. return Ok(ast);
  151. }
  152. let a0 = &l[0];
  153. match a0 {
  154. Sym(ref a0sym) if a0sym == "def!" => {
  155. env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
  156. }
  157. Sym(ref a0sym) if a0sym == "let*" => {
  158. env = env_new(Some(env.clone()));
  159. let (a1, a2) = (l[1].clone(), l[2].clone());
  160. match a1 {
  161. List(ref binds, _) | Vector(ref binds, _) => {
  162. for (b, e) in binds.iter().tuples() {
  163. match b {
  164. Sym(_) => {
  165. let _ = env_set(
  166. &env,
  167. b.clone(),
  168. eval(e.clone(), env.clone())?,
  169. );
  170. }
  171. _ => {
  172. return error("let* with non-Sym binding");
  173. }
  174. }
  175. }
  176. }
  177. _ => {
  178. return error("let* with non-List bindings");
  179. }
  180. };
  181. ast = a2;
  182. continue 'tco;
  183. }
  184. Sym(ref a0sym) if a0sym == "quote" => Ok(l[1].clone()),
  185. Sym(ref a0sym) if a0sym == "quasiquoteexpand" => Ok(quasiquote(&l[1])),
  186. Sym(ref a0sym) if a0sym == "quasiquote" => {
  187. ast = quasiquote(&l[1]);
  188. continue 'tco;
  189. }
  190. Sym(ref a0sym) if a0sym == "defmacro!" => {
  191. let (a1, a2) = (l[1].clone(), l[2].clone());
  192. let r = eval(a2, env.clone())?;
  193. match r {
  194. MalFunc {
  195. eval,
  196. ast,
  197. env,
  198. params,
  199. ..
  200. } => Ok(env_set(
  201. &env,
  202. a1.clone(),
  203. MalFunc {
  204. eval: eval,
  205. ast: ast.clone(),
  206. env: env.clone(),
  207. params: params.clone(),
  208. is_macro: true,
  209. meta: Rc::new(Nil),
  210. },
  211. )?),
  212. _ => error("set_macro on non-function"),
  213. }
  214. }
  215. Sym(ref a0sym) if a0sym == "macroexpand" => {
  216. match macroexpand(l[1].clone(), &env) {
  217. (_, Ok(new_ast)) => Ok(new_ast),
  218. (_, e) => return e,
  219. }
  220. }
  221. Sym(ref a0sym) if a0sym == "try*" => match eval(l[1].clone(), env.clone()) {
  222. Err(ref e) if l.len() >= 3 => {
  223. let exc = match e {
  224. ErrMalVal(mv) => mv.clone(),
  225. ErrString(s) => Str(s.to_string()),
  226. };
  227. match l[2].clone() {
  228. List(c, _) => {
  229. let catch_env = env_bind(
  230. Some(env.clone()),
  231. list!(vec![c[1].clone()]),
  232. vec![exc],
  233. )?;
  234. eval(c[2].clone(), catch_env)
  235. }
  236. _ => error("invalid catch block"),
  237. }
  238. }
  239. res => res,
  240. },
  241. Sym(ref a0sym) if a0sym == "do" => {
  242. match eval_ast(&list!(l[1..l.len() - 1].to_vec()), &env)? {
  243. List(_, _) => {
  244. ast = l.last().unwrap_or(&Nil).clone();
  245. continue 'tco;
  246. }
  247. _ => error("invalid do form"),
  248. }
  249. }
  250. Sym(ref a0sym) if a0sym == "if" => {
  251. let cond = eval(l[1].clone(), env.clone())?;
  252. match cond {
  253. Bool(false) | Nil if l.len() >= 4 => {
  254. ast = l[3].clone();
  255. continue 'tco;
  256. }
  257. Bool(false) | Nil => Ok(Nil),
  258. _ if l.len() >= 3 => {
  259. ast = l[2].clone();
  260. continue 'tco;
  261. }
  262. _ => Ok(Nil),
  263. }
  264. }
  265. Sym(ref a0sym) if a0sym == "fn*" => {
  266. let (a1, a2) = (l[1].clone(), l[2].clone());
  267. Ok(MalFunc {
  268. eval: eval,
  269. ast: Rc::new(a2),
  270. env: env,
  271. params: Rc::new(a1),
  272. is_macro: false,
  273. meta: Rc::new(Nil),
  274. })
  275. }
  276. Sym(ref a0sym) if a0sym == "eval" => {
  277. ast = eval(l[1].clone(), env.clone())?;
  278. while let Some(ref e) = env.clone().outer {
  279. env = e.clone();
  280. }
  281. continue 'tco;
  282. }
  283. Sym(ref a0sym) if a0sym == "setup" => {
  284. let a1 = l[1].clone();
  285. let circuit = setup(&ast, env.clone())?;
  286. env_sets(&env, ZK_CIRCUIT_ENV_KEY, circuit);
  287. eval(a1.clone(), env.clone())
  288. }
  289. Sym(ref a0sym) if a0sym == "prove" => {
  290. let a1 = l[0].clone();
  291. println!("prove {:?}", a1);
  292. prove(a1.clone(), env.clone())
  293. }
  294. Sym(ref a0sym) if a0sym == "alloc-input" => Ok(MalVal::Nil),
  295. Sym(ref a0sym) if a0sym == "alloc" => {
  296. let a1 = l[1].clone();
  297. let a2 = l[2].clone();
  298. let value = eval_ast(&a2, &env)?;
  299. println!("a1 {:?} \n value {:?}", a1, value);
  300. Ok(value)
  301. }
  302. //Sym(ref a0sym) if a0sym == "verify" => {
  303. Sym(ref a0sym) if a0sym == "enforce" => {
  304. let (a1, a2) = (l[0].clone(), l[1].clone());
  305. let value = eval_ast(&a2, &env)?;
  306. match value {
  307. List(ref el, _) => {
  308. println!("{:?}", el.to_vec());
  309. }
  310. _ => println!("invalid format"),
  311. }
  312. Ok(Nil)
  313. }
  314. _ => match eval_ast(&ast, &env)? {
  315. List(ref el, _) => {
  316. let ref f = el[0].clone();
  317. let args = el[1..].to_vec();
  318. match f {
  319. Func(_, _) => f.apply(args),
  320. MalFunc {
  321. ast: mast,
  322. env: menv,
  323. params,
  324. ..
  325. } => {
  326. let a = &**mast;
  327. let p = &**params;
  328. env = env_bind(Some(menv.clone()), p.clone(), args)?;
  329. ast = a.clone();
  330. continue 'tco;
  331. }
  332. _ => {
  333. Ok(Nil)
  334. //error("call non-function")
  335. }
  336. }
  337. }
  338. _ => error("expected a list"),
  339. },
  340. }
  341. }
  342. _ => eval_ast(&ast, &env),
  343. };
  344. break;
  345. } // end 'tco loop
  346. ret
  347. }
  348. pub fn env_circuit(mut env: Env) -> MalVal {
  349. let s = ZK_CIRCUIT_ENV_KEY;
  350. match env_find(&env, s) {
  351. Some(e) => match env_get(&e, &Str(s.to_string())) {
  352. Ok(v) => v,
  353. _ => MalVal::Zk(LispCircuit {
  354. params: vec![],
  355. allocs: vec![],
  356. alloc_inputs: vec![],
  357. constraints: vec![],
  358. env: env.clone(),
  359. }),
  360. },
  361. _ => MalVal::Zk(LispCircuit {
  362. params: vec![],
  363. allocs: vec![],
  364. alloc_inputs: vec![],
  365. constraints: vec![],
  366. env: env.clone(),
  367. }),
  368. }
  369. }
  370. pub fn setup(ast: &MalVal, mut env: Env) -> MalRet {
  371. println!("{:?}", ast);
  372. // TODO get params from ast
  373. let start = Instant::now();
  374. // Create parameters for our circuit. In a production deployment these would
  375. // be generated securely using a multiparty computation.
  376. let mut c = LispCircuit {
  377. params: vec![],
  378. allocs: vec![],
  379. alloc_inputs: vec![],
  380. constraints: vec![],
  381. env: env.clone(),
  382. };
  383. // TODO move to another fn
  384. let random_parameters =
  385. groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap();
  386. let pvk = groth16::prepare_verifying_key(&random_parameters.vk);
  387. println!("Setup: [{:?}]", start.elapsed());
  388. Ok(MalVal::Nil)
  389. }
  390. pub fn prove(mut ast: MalVal, mut env: Env) -> MalRet {
  391. // TODO remove it
  392. let quantity = bls12_381::Scalar::from(3);
  393. // Create an instance of our circuit (with the preimage as a witness).
  394. let params = {
  395. let c = LispCircuit {
  396. params: vec![],
  397. allocs: vec![],
  398. alloc_inputs: vec![],
  399. constraints: vec![],
  400. env: env.clone(),
  401. };
  402. groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap()
  403. };
  404. let circuit= LispCircuit {
  405. params: vec![],
  406. allocs: vec![],
  407. alloc_inputs: vec![],
  408. constraints: vec![],
  409. env: env.clone(),
  410. };
  411. let start = Instant::now();
  412. // Create a Groth16 proof with our parameters.
  413. let proof = groth16::create_random_proof(circuit, &params, &mut OsRng).unwrap();
  414. println!("Prove: [{:?}]", start.elapsed());
  415. Ok(MalVal::Nil)
  416. }
  417. pub fn verify(ast: &MalVal) -> MalRet {
  418. let public_input = vec![bls12_381::Scalar::from(27)];
  419. let start = Instant::now();
  420. // Check the proof!
  421. //assert!(groth16::verify_proof(&pvk, &proof, &public_input).is_ok());
  422. println!("Verify: [{:?}]", start.elapsed());
  423. Ok(MalVal::Nil)
  424. }
  425. // print
  426. fn print(ast: &MalVal) -> String {
  427. ast.pr_str(true)
  428. }
  429. fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
  430. let ast = read(str)?;
  431. let exp = eval(ast, env.clone())?;
  432. Ok(print(&exp))
  433. }
  434. fn main() -> Result<(), ()> {
  435. let matches = clap_app!(zklisp =>
  436. (version: "0.1.0")
  437. (author: "mileschet <miles.chet@gmail.com>")
  438. (about: "A Lisp Interpreter for Zero Knowledge Virtual Machine")
  439. (@subcommand load =>
  440. (about: "Load the file into the interpreter")
  441. (@arg FILE: +required "Lisp Contract filename")
  442. )
  443. )
  444. .get_matches();
  445. CombinedLogger::init(vec![TermLogger::new(
  446. LevelFilter::Debug,
  447. Config::default(),
  448. TerminalMode::Mixed,
  449. )
  450. .unwrap()])
  451. .unwrap();
  452. match matches.subcommand() {
  453. Some(("load", matches)) => {
  454. let file: String = matches.value_of("FILE").unwrap().parse().unwrap();
  455. repl_load(file);
  456. }
  457. _ => {
  458. eprintln!("error: Invalid subcommand invoked");
  459. std::process::exit(-1);
  460. }
  461. }
  462. Ok(())
  463. }
  464. fn repl_load(file: String) -> Result<(), ()> {
  465. let repl_env = env_new(None);
  466. for (k, v) in core::ns() {
  467. env_sets(&repl_env, k, v);
  468. }
  469. let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
  470. let _ = rep(
  471. "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
  472. &repl_env,
  473. );
  474. let _ = rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", &repl_env);
  475. match rep(&format!("(load-file \"{}\")", file), &repl_env) {
  476. Ok(_) => std::process::exit(0),
  477. Err(e) => {
  478. println!("Error: {}", format_error(e));
  479. std::process::exit(1);
  480. }
  481. }
  482. Ok(())
  483. }