types.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError};
  2. use sapvi::bls_extensions::BlsStringConversion;
  3. use std::{cell::RefCell, collections::HashMap};
  4. use std::ops::{Add, AddAssign, MulAssign, SubAssign};
  5. use std::rc::Rc;
  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. _ => { println!("not a valid param {:?}", value) }
  136. }
  137. }
  138. }
  139. println!("left: a {:?} b {:?} val_b: {:?}", a, b, val_b);
  140. }
  141. for values in alloc_value.right.iter() {
  142. let (a, b) = values;
  143. let mut val_b = CS::one();
  144. if b != "cs::one" {
  145. val_b = *variables.get(b).unwrap();
  146. }
  147. if a == "scalar::one" {
  148. right = right + (coeff, val_b);
  149. } else if a == "scalar::one::neg" {
  150. right = right + (coeff.neg(), val_b);
  151. } else {
  152. if let Some(value) = params_const.get(a) {
  153. match value {
  154. MalVal::ZKScalar(val) => {
  155. right = right + (*val, val_b);
  156. }
  157. MalVal::Str(s) => {
  158. let val = bls12_381::Scalar::from_string(&s.to_string());
  159. right = right + (val, val_b);
  160. }
  161. _ => { println!("not a valid param {:?}", value) }
  162. }
  163. }
  164. }
  165. println!("right: a {:?} b {:?} val_b: {:?}", a, b, val_b);
  166. }
  167. for values in alloc_value.output.iter() {
  168. let (a, b) = values;
  169. let mut val_b = CS::one();
  170. if b != "cs::one" {
  171. println!("{:?}", b);
  172. val_b = *variables.get(b).unwrap();
  173. }
  174. if a == "scalar::one" {
  175. output = output + (coeff, val_b);
  176. } else if a == "scalar::one::neg" {
  177. output = output + (coeff.neg(), val_b);
  178. } else {
  179. if let Some(value) = params_const.get(a) {
  180. match value {
  181. MalVal::ZKScalar(val) => {
  182. output = output + (*val, val_b);
  183. }
  184. MalVal::Str(s) => {
  185. let val = bls12_381::Scalar::from_string(&s.to_string());
  186. output = output + (val, val_b);
  187. }
  188. _ => { println!("not a valid param {:?}", value) }
  189. }
  190. }
  191. }
  192. println!("output: a {:?} b {:?} val_b: {:?}", a, b, val_b);
  193. }
  194. println!("Enforcing ...");
  195. cs.enforce(
  196. || "constraint",
  197. |_| left.clone(),
  198. |_| right.clone(),
  199. |_| output.clone(),
  200. );
  201. }
  202. Ok(())
  203. }
  204. }
  205. #[derive(Debug)]
  206. pub enum MalErr {
  207. ErrString(String),
  208. ErrMalVal(MalVal),
  209. }
  210. impl From<SynthesisError> for MalErr {
  211. fn from(err: SynthesisError) -> MalErr {
  212. ErrString(err.to_string())
  213. }
  214. }
  215. pub type MalArgs = Vec<MalVal>;
  216. pub type MalRet = Result<MalVal, MalErr>;
  217. // type utility macros
  218. macro_rules! list {
  219. ($seq:expr) => {{
  220. List(Rc::new($seq),Rc::new(Nil))
  221. }};
  222. [$($args:expr),*] => {{
  223. let v: Vec<MalVal> = vec![$($args),*];
  224. List(Rc::new(v),Rc::new(Nil))
  225. }}
  226. }
  227. macro_rules! vector {
  228. ($seq:expr) => {{
  229. Vector(Rc::new($seq),Rc::new(Nil))
  230. }};
  231. [$($args:expr),*] => {{
  232. let v: Vec<MalVal> = vec![$($args),*];
  233. Vector(Rc::new(v),Rc::new(Nil))
  234. }}
  235. }
  236. // type utility functions
  237. pub fn error(s: &str) -> MalRet {
  238. Err(ErrString(s.to_string()))
  239. }
  240. pub fn format_error(e: MalErr) -> String {
  241. match e {
  242. ErrString(s) => s.clone(),
  243. ErrMalVal(mv) => mv.pr_str(true),
  244. }
  245. }
  246. pub fn atom(mv: &MalVal) -> MalVal {
  247. Atom(Rc::new(RefCell::new(mv.clone())))
  248. }
  249. impl MalVal {
  250. pub fn keyword(&self) -> MalRet {
  251. match self {
  252. Str(s) if s.starts_with("\u{29e}") => Ok(Str(s.to_string())),
  253. Str(s) => Ok(Str(format!("\u{29e}{}", s))),
  254. _ => error("invalid type for keyword"),
  255. }
  256. }
  257. pub fn empty_q(&self) -> MalRet {
  258. match self {
  259. List(l, _) | Vector(l, _) => Ok(Bool(l.len() == 0)),
  260. Nil => Ok(Bool(true)),
  261. _ => error("invalid type for empty?"),
  262. }
  263. }
  264. pub fn count(&self) -> MalRet {
  265. match self {
  266. List(l, _) | Vector(l, _) => Ok(Int(l.len() as i64)),
  267. Nil => Ok(Int(0)),
  268. _ => error("invalid type for count"),
  269. }
  270. }
  271. pub fn apply(&self, args: MalArgs) -> MalRet {
  272. match *self {
  273. Func(f, _) => f(args),
  274. MalFunc {
  275. eval,
  276. ref ast,
  277. ref env,
  278. ref params,
  279. ..
  280. } => {
  281. let a = &**ast;
  282. let p = &**params;
  283. let fn_env = env_bind(Some(env.clone()), p.clone(), args)?;
  284. Ok(eval(a.clone(), fn_env)?)
  285. }
  286. _ => error("attempt to call non-function"),
  287. }
  288. }
  289. pub fn keyword_q(&self) -> bool {
  290. match self {
  291. Str(s) if s.starts_with("\u{29e}") => true,
  292. _ => false,
  293. }
  294. }
  295. pub fn deref(&self) -> MalRet {
  296. match self {
  297. Atom(a) => Ok(a.borrow().clone()),
  298. _ => error("attempt to deref a non-Atom"),
  299. }
  300. }
  301. pub fn reset_bang(&self, new: &MalVal) -> MalRet {
  302. match self {
  303. Atom(a) => {
  304. *a.borrow_mut() = new.clone();
  305. Ok(new.clone())
  306. }
  307. _ => error("attempt to reset! a non-Atom"),
  308. }
  309. }
  310. pub fn swap_bang(&self, args: &MalArgs) -> MalRet {
  311. match self {
  312. Atom(a) => {
  313. let f = &args[0];
  314. let mut fargs = args[1..].to_vec();
  315. fargs.insert(0, a.borrow().clone());
  316. *a.borrow_mut() = f.apply(fargs)?;
  317. Ok(a.borrow().clone())
  318. }
  319. _ => error("attempt to swap! a non-Atom"),
  320. }
  321. }
  322. pub fn get_meta(&self) -> MalRet {
  323. match self {
  324. List(_, meta) | Vector(_, meta) | Hash(_, meta) => Ok((&**meta).clone()),
  325. Func(_, meta) => Ok((&**meta).clone()),
  326. MalFunc { meta, .. } => Ok((&**meta).clone()),
  327. _ => error("meta not supported by type"),
  328. }
  329. }
  330. pub fn with_meta(&mut self, new_meta: &MalVal) -> MalRet {
  331. match self {
  332. List(_, ref mut meta)
  333. | Vector(_, ref mut meta)
  334. | Hash(_, ref mut meta)
  335. | Func(_, ref mut meta)
  336. | MalFunc { ref mut meta, .. } => {
  337. *meta = Rc::new((&*new_meta).clone());
  338. }
  339. _ => return error("with-meta not supported by type"),
  340. };
  341. Ok(self.clone())
  342. }
  343. }
  344. impl PartialEq for MalVal {
  345. fn eq(&self, other: &MalVal) -> bool {
  346. match (self, other) {
  347. (Nil, Nil) => true,
  348. (Bool(ref a), Bool(ref b)) => a == b,
  349. (Int(ref a), Int(ref b)) => a == b,
  350. (Str(ref a), Str(ref b)) => a == b,
  351. (Sym(ref a), Sym(ref b)) => a == b,
  352. (List(ref a, _), List(ref b, _))
  353. | (Vector(ref a, _), Vector(ref b, _))
  354. | (List(ref a, _), Vector(ref b, _))
  355. | (Vector(ref a, _), List(ref b, _)) => a == b,
  356. (Hash(ref a, _), Hash(ref b, _)) => a == b,
  357. (MalFunc { .. }, MalFunc { .. }) => false,
  358. _ => false,
  359. }
  360. }
  361. }
  362. pub fn func(f: fn(MalArgs) -> MalRet) -> MalVal {
  363. Func(f, Rc::new(Nil))
  364. }
  365. pub fn _assoc(mut hm: HashMap<String, MalVal>, kvs: MalArgs) -> MalRet {
  366. if kvs.len() % 2 != 0 {
  367. return error("odd number of elements");
  368. }
  369. for (k, v) in kvs.iter().tuples() {
  370. match k {
  371. Str(s) => {
  372. hm.insert(s.to_string(), v.clone());
  373. }
  374. _ => return error("key is not string"),
  375. }
  376. }
  377. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  378. }
  379. pub fn _dissoc(mut hm: HashMap<String, MalVal>, ks: MalArgs) -> MalRet {
  380. for k in ks.iter() {
  381. match k {
  382. Str(ref s) => {
  383. hm.remove(s);
  384. }
  385. _ => return error("key is not string"),
  386. }
  387. }
  388. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  389. }
  390. pub fn hash_map(kvs: MalArgs) -> MalRet {
  391. let hm: HashMap<String, MalVal> = HashMap::default();
  392. _assoc(hm, kvs)
  393. }