types.rs 14 KB

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