types.rs 12 KB

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