types.rs 12 KB

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