types.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError};
  2. use sapvi::bls_extensions::BlsStringConversion;
  3. use std::ops::{Add, AddAssign, MulAssign, SubAssign};
  4. use std::rc::Rc;
  5. use std::{cell::RefCell, collections::HashMap};
  6. // use fnv::FnvHashMap;
  7. use itertools::Itertools;
  8. use crate::env::{env_bind, Env};
  9. use crate::types::MalErr::{ErrMalVal, ErrString};
  10. use crate::types::MalVal::{Atom, Bool, Func, Hash, Int, List, MalFunc, Nil, Str, Sym, Vector};
  11. use bellman::Variable;
  12. use bls12_381::Bls12;
  13. use bls12_381::Scalar;
  14. #[derive(Debug, Clone)]
  15. pub struct Allocation {
  16. pub symbol: String,
  17. pub value: Scalar,
  18. }
  19. #[derive(Debug, Clone)]
  20. pub struct EnforceAllocation {
  21. pub idx: usize,
  22. pub left: Vec<(String, String)>,
  23. pub right: Vec<(String, String)>,
  24. pub output: Vec<(String, String)>,
  25. }
  26. pub struct VerifyKeyParams {
  27. pub random_params: groth16::Parameters<Bls12>,
  28. pub verifying_key: groth16::PreparedVerifyingKey<Bls12>,
  29. }
  30. #[derive(Debug, Clone)]
  31. pub struct LispCircuit {
  32. pub params: HashMap<String, MalVal>,
  33. pub allocs: HashMap<String, MalVal>,
  34. pub alloc_inputs: HashMap<String, MalVal>,
  35. pub constraints: Vec<EnforceAllocation>,
  36. }
  37. #[derive(Debug, Clone)]
  38. pub enum MalVal {
  39. Nil,
  40. Bool(bool),
  41. Int(i64),
  42. Str(String),
  43. Sym(String),
  44. List(Rc<Vec<MalVal>>, Rc<MalVal>),
  45. Vector(Rc<Vec<MalVal>>, Rc<MalVal>),
  46. Hash(Rc<HashMap<String, MalVal>>, Rc<MalVal>),
  47. Func(fn(MalArgs) -> MalRet, Rc<MalVal>),
  48. MalFunc {
  49. eval: fn(ast: MalVal, env: Env) -> MalRet,
  50. ast: Rc<MalVal>,
  51. env: Env,
  52. params: Rc<MalVal>,
  53. is_macro: bool,
  54. meta: Rc<MalVal>,
  55. },
  56. Atom(Rc<RefCell<MalVal>>),
  57. Alloc(RefCell<HashMap<String, MalVal>>),
  58. Enforce(Rc<Vec<EnforceAllocation>>),
  59. ZKScalar(bls12_381::Scalar),
  60. }
  61. impl Circuit<bls12_381::Scalar> for LispCircuit {
  62. fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
  63. self,
  64. cs: &mut CS,
  65. ) -> Result<(), SynthesisError> {
  66. let mut variables: HashMap<String, Variable> = HashMap::default();
  67. let mut params_const = self.params;
  68. // println!("Allocations\n");
  69. for (k, v) in &self.allocs {
  70. match v {
  71. MalVal::ZKScalar(val) => {
  72. let var = cs.alloc(|| k, || Ok(*val))?;
  73. variables.insert(k.to_string(), var);
  74. // println!("k {:?} v {:?} var {:?}", k, v, var);
  75. }
  76. MalVal::Str(val) => {
  77. let val_scalar = bls12_381::Scalar::from_string(&*val);
  78. let var = cs.alloc(|| k, || Ok(val_scalar))?;
  79. variables.insert(k.to_string(), var);
  80. // println!("k {:?} v {:?} var {:?}", k, v, var);
  81. }
  82. _ => {
  83. println!("not allocated k {:?} v {:?}", k, v);
  84. }
  85. }
  86. }
  87. // println!("Allocations Input\n");
  88. for (k, v) in &self.alloc_inputs {
  89. match v {
  90. MalVal::ZKScalar(val) => {
  91. let var = cs.alloc_input(|| k, || Ok(*val))?;
  92. variables.insert(k.to_string(), var);
  93. // println!("k {:?} v {:?} var {:?}", k, v, var);
  94. }
  95. MalVal::Str(val) => {
  96. let val_scalar = bls12_381::Scalar::from_string(&*val);
  97. let var = cs.alloc_input(|| k, || Ok(val_scalar))?;
  98. variables.insert(k.to_string(), var);
  99. // println!("k {:?} v {:?} var {:?}", k, v, var);
  100. }
  101. _ => {
  102. println!("not allocated k {:?} v {:?}", k, v);
  103. }
  104. }
  105. }
  106. println!("Enforce Allocations\n");
  107. let mut enforce_sorted = self.constraints.clone();
  108. enforce_sorted.sort_by(|a, b| a.idx.cmp(&b.idx));
  109. for alloc_value in enforce_sorted.iter() {
  110. // println!("Enforce -> {:?}", alloc_value);
  111. let coeff = bls12_381::Scalar::one();
  112. let mut left = bellman::LinearCombination::<Scalar>::zero();
  113. let mut right = bellman::LinearCombination::<Scalar>::zero();
  114. let mut output = bellman::LinearCombination::<Scalar>::zero();
  115. for values in alloc_value.left.iter() {
  116. let (a, b) = values;
  117. let mut val_b = CS::one();
  118. if b != "cs::one" {
  119. val_b = *variables.get(b).unwrap();
  120. }
  121. if a == "scalar::one" {
  122. left = left + (coeff, val_b);
  123. } else if a == "scalar::one::neg" {
  124. left = left + (coeff.neg(), val_b);
  125. } else {
  126. if let Some(value) = params_const.get(a) {
  127. match value {
  128. MalVal::ZKScalar(val) => {
  129. left = left + (*val, val_b);
  130. }
  131. MalVal::Str(s) => {
  132. let val = bls12_381::Scalar::from_string(&s.to_string());
  133. left = left + (val, val_b);
  134. }
  135. _ => {
  136. println!("not a valid param {:?}", value)
  137. }
  138. }
  139. }
  140. }
  141. println!("left: a {:?} b {:?} val_b: {:?}", a, b, val_b);
  142. }
  143. for values in alloc_value.right.iter() {
  144. let (a, b) = values;
  145. let mut val_b = CS::one();
  146. if b != "cs::one" {
  147. val_b = *variables.get(b).unwrap();
  148. }
  149. if a == "scalar::one" {
  150. right = right + (coeff, val_b);
  151. } else if a == "scalar::one::neg" {
  152. right = right + (coeff.neg(), val_b);
  153. } else {
  154. if let Some(value) = params_const.get(a) {
  155. match value {
  156. MalVal::ZKScalar(val) => {
  157. right = right + (*val, val_b);
  158. }
  159. MalVal::Str(s) => {
  160. let val = bls12_381::Scalar::from_string(&s.to_string());
  161. right = right + (val, val_b);
  162. }
  163. _ => {
  164. println!("not a valid param {:?}", value)
  165. }
  166. }
  167. }
  168. }
  169. println!("right: a {:?} b {:?} val_b: {:?}", a, b, val_b);
  170. }
  171. for values in alloc_value.output.iter() {
  172. let (a, b) = values;
  173. let mut val_b = CS::one();
  174. if b != "cs::one" {
  175. println!("{:?}", b);
  176. val_b = *variables.get(b).unwrap();
  177. }
  178. if a == "scalar::one" {
  179. output = output + (coeff, val_b);
  180. } else if a == "scalar::one::neg" {
  181. output = output + (coeff.neg(), val_b);
  182. } else {
  183. if let Some(value) = params_const.get(a) {
  184. match value {
  185. MalVal::ZKScalar(val) => {
  186. output = output + (*val, val_b);
  187. }
  188. MalVal::Str(s) => {
  189. let val = bls12_381::Scalar::from_string(&s.to_string());
  190. output = output + (val, val_b);
  191. }
  192. _ => {
  193. println!("not a valid param {:?}", value)
  194. }
  195. }
  196. }
  197. }
  198. println!("output: a {:?} b {:?} val_b: {:?}", a, b, val_b);
  199. }
  200. println!("Enforcing ...");
  201. cs.enforce(
  202. || "constraint",
  203. |_| left.clone(),
  204. |_| right.clone(),
  205. |_| output.clone(),
  206. );
  207. }
  208. Ok(())
  209. }
  210. }
  211. #[derive(Debug)]
  212. pub enum MalErr {
  213. ErrString(String),
  214. ErrMalVal(MalVal),
  215. }
  216. impl From<SynthesisError> for MalErr {
  217. fn from(err: SynthesisError) -> MalErr {
  218. ErrString(err.to_string())
  219. }
  220. }
  221. pub type MalArgs = Vec<MalVal>;
  222. pub type MalRet = Result<MalVal, MalErr>;
  223. // type utility macros
  224. macro_rules! list {
  225. ($seq:expr) => {{
  226. List(Rc::new($seq),Rc::new(Nil))
  227. }};
  228. [$($args:expr),*] => {{
  229. let v: Vec<MalVal> = vec![$($args),*];
  230. List(Rc::new(v),Rc::new(Nil))
  231. }}
  232. }
  233. macro_rules! vector {
  234. ($seq:expr) => {{
  235. Vector(Rc::new($seq),Rc::new(Nil))
  236. }};
  237. [$($args:expr),*] => {{
  238. let v: Vec<MalVal> = vec![$($args),*];
  239. Vector(Rc::new(v),Rc::new(Nil))
  240. }}
  241. }
  242. // type utility functions
  243. pub fn error(s: &str) -> MalRet {
  244. Err(ErrString(s.to_string()))
  245. }
  246. pub fn format_error(e: MalErr) -> String {
  247. match e {
  248. ErrString(s) => s.clone(),
  249. ErrMalVal(mv) => mv.pr_str(true),
  250. }
  251. }
  252. pub fn atom(mv: &MalVal) -> MalVal {
  253. Atom(Rc::new(RefCell::new(mv.clone())))
  254. }
  255. impl MalVal {
  256. pub fn keyword(&self) -> MalRet {
  257. match self {
  258. Str(s) if s.starts_with("\u{29e}") => Ok(Str(s.to_string())),
  259. Str(s) => Ok(Str(format!("\u{29e}{}", s))),
  260. _ => error("invalid type for keyword"),
  261. }
  262. }
  263. pub fn empty_q(&self) -> MalRet {
  264. match self {
  265. List(l, _) | Vector(l, _) => Ok(Bool(l.len() == 0)),
  266. Nil => Ok(Bool(true)),
  267. _ => error("invalid type for empty?"),
  268. }
  269. }
  270. pub fn count(&self) -> MalRet {
  271. match self {
  272. List(l, _) | Vector(l, _) => Ok(Int(l.len() as i64)),
  273. Nil => Ok(Int(0)),
  274. _ => error("invalid type for count"),
  275. }
  276. }
  277. pub fn apply(&self, args: MalArgs) -> MalRet {
  278. match *self {
  279. Func(f, _) => f(args),
  280. MalFunc {
  281. eval,
  282. ref ast,
  283. ref env,
  284. ref params,
  285. ..
  286. } => {
  287. let a = &**ast;
  288. let p = &**params;
  289. let fn_env = env_bind(Some(env.clone()), p.clone(), args)?;
  290. Ok(eval(a.clone(), fn_env)?)
  291. }
  292. _ => error("attempt to call non-function"),
  293. }
  294. }
  295. pub fn keyword_q(&self) -> bool {
  296. match self {
  297. Str(s) if s.starts_with("\u{29e}") => true,
  298. _ => false,
  299. }
  300. }
  301. pub fn deref(&self) -> MalRet {
  302. match self {
  303. Atom(a) => Ok(a.borrow().clone()),
  304. _ => error("attempt to deref a non-Atom"),
  305. }
  306. }
  307. pub fn reset_bang(&self, new: &MalVal) -> MalRet {
  308. match self {
  309. Atom(a) => {
  310. *a.borrow_mut() = new.clone();
  311. Ok(new.clone())
  312. }
  313. _ => error("attempt to reset! a non-Atom"),
  314. }
  315. }
  316. pub fn swap_bang(&self, args: &MalArgs) -> MalRet {
  317. match self {
  318. Atom(a) => {
  319. let f = &args[0];
  320. let mut fargs = args[1..].to_vec();
  321. fargs.insert(0, a.borrow().clone());
  322. *a.borrow_mut() = f.apply(fargs)?;
  323. Ok(a.borrow().clone())
  324. }
  325. _ => error("attempt to swap! a non-Atom"),
  326. }
  327. }
  328. pub fn get_meta(&self) -> MalRet {
  329. match self {
  330. List(_, meta) | Vector(_, meta) | Hash(_, meta) => Ok((&**meta).clone()),
  331. Func(_, meta) => Ok((&**meta).clone()),
  332. MalFunc { meta, .. } => Ok((&**meta).clone()),
  333. _ => error("meta not supported by type"),
  334. }
  335. }
  336. pub fn with_meta(&mut self, new_meta: &MalVal) -> MalRet {
  337. match self {
  338. List(_, ref mut meta)
  339. | Vector(_, ref mut meta)
  340. | Hash(_, ref mut meta)
  341. | Func(_, ref mut meta)
  342. | MalFunc { ref mut meta, .. } => {
  343. *meta = Rc::new((&*new_meta).clone());
  344. }
  345. _ => return error("with-meta not supported by type"),
  346. };
  347. Ok(self.clone())
  348. }
  349. }
  350. impl PartialEq for MalVal {
  351. fn eq(&self, other: &MalVal) -> bool {
  352. match (self, other) {
  353. (Nil, Nil) => true,
  354. (Bool(ref a), Bool(ref b)) => a == b,
  355. (Int(ref a), Int(ref b)) => a == b,
  356. (Str(ref a), Str(ref b)) => a == b,
  357. (Sym(ref a), Sym(ref b)) => a == b,
  358. (List(ref a, _), List(ref b, _))
  359. | (Vector(ref a, _), Vector(ref b, _))
  360. | (List(ref a, _), Vector(ref b, _))
  361. | (Vector(ref a, _), List(ref b, _)) => a == b,
  362. (Hash(ref a, _), Hash(ref b, _)) => a == b,
  363. (MalFunc { .. }, MalFunc { .. }) => false,
  364. _ => false,
  365. }
  366. }
  367. }
  368. pub fn func(f: fn(MalArgs) -> MalRet) -> MalVal {
  369. Func(f, Rc::new(Nil))
  370. }
  371. pub fn _assoc(mut hm: HashMap<String, MalVal>, kvs: MalArgs) -> MalRet {
  372. if kvs.len() % 2 != 0 {
  373. return error("odd number of elements");
  374. }
  375. for (k, v) in kvs.iter().tuples() {
  376. match k {
  377. Str(s) => {
  378. hm.insert(s.to_string(), v.clone());
  379. }
  380. _ => return error("key is not string"),
  381. }
  382. }
  383. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  384. }
  385. pub fn _dissoc(mut hm: HashMap<String, MalVal>, ks: MalArgs) -> MalRet {
  386. for k in ks.iter() {
  387. match k {
  388. Str(ref s) => {
  389. hm.remove(s);
  390. }
  391. _ => return error("key is not string"),
  392. }
  393. }
  394. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  395. }
  396. pub fn hash_map(kvs: MalArgs) -> MalRet {
  397. let hm: HashMap<String, MalVal> = HashMap::default();
  398. _assoc(hm, kvs)
  399. }