pism.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import json
  2. import os
  3. import sys
  4. symbol_table = {
  5. "contract": 1,
  6. "param": 2,
  7. "start": 0,
  8. "end": 0,
  9. "witness": 2,
  10. "fr_as_binary_le": 2,
  11. "ec_mul_const": 3,
  12. "emit_ec": 1
  13. }
  14. types_map = {
  15. "U64": "u64",
  16. "Fr": "jubjub::Fr",
  17. "Point": "jubjub::SubgroupPoint",
  18. "Scalar": "bls12_381::Scalar",
  19. "Bool": "bool"
  20. }
  21. command_desc = {
  22. "witness": (
  23. ("EdwardsPoint", True),
  24. ("Point", False)
  25. ),
  26. "fr_as_binary_le": (
  27. ("Vec<Boolean>", True),
  28. ("Fr", False)
  29. ),
  30. "ec_mul_const": (
  31. ("EdwardsPoint", True),
  32. ("Vec<Boolean>", False),
  33. ("FixedGenerator", False)
  34. ),
  35. "emit_ec": (
  36. ("EdwardsPoint", False),
  37. )
  38. }
  39. def eprint(*args):
  40. print(*args, file=sys.stderr)
  41. class Line:
  42. def __init__(self, text, line_number):
  43. self.text = text
  44. self.orig = text
  45. self.lineno = line_number
  46. self.clean()
  47. def clean(self):
  48. # Remove the comments
  49. self.text = self.text.split("#", 1)[0]
  50. # Remove whitespace
  51. self.text = self.text.strip()
  52. def is_empty(self):
  53. return bool(self.text)
  54. def __repr__(self):
  55. return "Line %s: %s" % (self.lineno, self.orig)
  56. def command(self):
  57. if not self.is_empty():
  58. return None
  59. return self.text.split(" ")[0]
  60. def args(self):
  61. if not self.is_empty():
  62. return None
  63. return self.text.split(" ")[1:]
  64. def clean(contents):
  65. # Split input into lines
  66. contents = contents.split("\n")
  67. contents = [Line(line, i) for i, line in enumerate(contents)]
  68. # Remove empty blank lines
  69. contents = [line for line in contents if line.is_empty()]
  70. return contents
  71. def make_segments(contents):
  72. constants = [line for line in contents if line.command() == "constant"]
  73. segments = []
  74. current_segment = []
  75. for line in contents:
  76. if line.command() == "contract":
  77. current_segment = []
  78. current_segment.append(line)
  79. if line.command() == "end":
  80. segments.append(current_segment)
  81. current_segment = []
  82. return constants, segments
  83. def build_constants_table(constants):
  84. table = {}
  85. for line in constants:
  86. args = line.args()
  87. if len(args) != 2:
  88. eprint("error: wrong number of args")
  89. eprint(line)
  90. return None
  91. name, type = args
  92. table[name] = type
  93. return table
  94. def extract(segment):
  95. assert segment
  96. # Does it have a declaration?
  97. if not segment[0].command() == "contract":
  98. eprint("error: missing contract declaration")
  99. eprint(segment[0])
  100. return None
  101. # Does it have an end?
  102. if not segment[-1].command() == "end":
  103. eprint("error: missing contract end")
  104. eprint(segment[-1])
  105. return None
  106. # Does it have a start?
  107. if not [line for line in segment if line.command() == "start"]:
  108. eprint("error: missing contract start")
  109. eprint(segment[0])
  110. return None
  111. for line in segment:
  112. command, args = line.command(), line.args()
  113. if symbol_table[command] != len(args):
  114. eprint("error: wrong number of args for command '%s'" % command)
  115. eprint(line)
  116. return None
  117. contract_name = segment[0].args()[0]
  118. start_index = [index for index, line in enumerate(segment)
  119. if line.command() == "start"]
  120. if len(start_index) > 1:
  121. eprint("error: multiple start statements in contract '%s'" %
  122. contract_name)
  123. for index in start_index:
  124. eprint(segment[index])
  125. eprint("Aborting.")
  126. return None
  127. assert len(start_index) == 1
  128. start_index = start_index[0]
  129. header = segment[1:start_index]
  130. code = segment[start_index + 1:-1]
  131. params = {}
  132. for param_decl in header:
  133. args = param_decl.args()
  134. assert len(args) == 2
  135. name, type = args
  136. params[name] = type
  137. program = []
  138. for line in code:
  139. command, args = line.command(), line.args()
  140. program.append((command, args, line))
  141. return Contract(contract_name, params, program)
  142. def to_initial_caps(snake_str):
  143. components = snake_str.split("_")
  144. return "".join(x.title() for x in components)
  145. class Contract:
  146. def __init__(self, name, params, program):
  147. self.name = name
  148. self.params = params
  149. self.program = program
  150. def _includes(self):
  151. return \
  152. r"""use bellman::{
  153. gadgets::{
  154. boolean,
  155. boolean::{AllocatedBit, Boolean},
  156. multipack,
  157. },
  158. groth16, Circuit, ConstraintSystem, SynthesisError,
  159. };
  160. use bls12_381::Bls12;
  161. use ff::{PrimeField, Field};
  162. use group::Curve;
  163. use zcash_proofs::circuit::ecc;
  164. """
  165. def _compile_header(self):
  166. code = "pub struct %s {\n" % to_initial_caps(self.name)
  167. for param_name, param_type in self.params.items():
  168. try:
  169. mapped_type = types_map[param_type]
  170. except KeyError:
  171. return None
  172. code += " pub %s: Option<%s>,\n" % (param_name, mapped_type)
  173. code += "}\n"
  174. return code
  175. def _compile_body(self):
  176. self.stack = {}
  177. code = "\n"
  178. #indent = " " * 8
  179. for command, args, line in self.program:
  180. if (code_text := self._compile_line(command, args, line)) is None:
  181. return None
  182. code += code_text + "\n"
  183. return code
  184. def _preprocess_args(self, args, line):
  185. nargs = []
  186. for arg in args:
  187. if not arg.startswith("param:"):
  188. nargs.append((arg, False))
  189. continue
  190. _, argname = arg.split(":", 1)
  191. if argname not in self.params:
  192. eprint("error: non-existant param referenced")
  193. eprint(line)
  194. return None
  195. nargs.append((argname, True))
  196. return nargs
  197. def type_checking(self, command, args, line):
  198. assert command in command_desc
  199. type_list = command_desc[command]
  200. if len(type_list) != len(args):
  201. eprint("error: wrong number of arguments!")
  202. eprint(line)
  203. return False
  204. for (expected_type, new_val), (argname, is_param) in \
  205. zip(type_list, args):
  206. # Only type check input arguments, not output values
  207. if new_val:
  208. continue
  209. if is_param:
  210. actual_type = self.params[argname]
  211. else:
  212. # Check the stack here
  213. if argname not in self.stack:
  214. eprint("error: cannot find value '%s' on the stack!" %
  215. argname)
  216. eprint(line)
  217. return False
  218. actual_type = self.stack[argname]
  219. return True
  220. def _check_args(self, command, args, line):
  221. assert command in command_desc
  222. type_list = command_desc[command]
  223. assert len(type_list) == len(args)
  224. for (_, is_new_val), (arg, is_param) in zip(type_list, args):
  225. if is_param:
  226. continue
  227. if is_new_val:
  228. continue
  229. if arg in self.stack:
  230. continue
  231. if arg in self.constants:
  232. continue
  233. eprint("error: cannot find '%s' in the stack" % arg)
  234. eprint(line)
  235. return False
  236. return True
  237. def _compile_line(self, command, args, line):
  238. if (args := self._preprocess_args(args, line)) is None:
  239. return None
  240. if not self.type_checking(command, args, line):
  241. return None
  242. if not self._check_args(command, args, line):
  243. return None
  244. self.modify_stack(command, args)
  245. args = [self.carg(arg) for arg in args]
  246. if command == "witness":
  247. out, point = args
  248. return \
  249. r"""let %s = ecc::EdwardsPoint::witness(
  250. cs.namespace(|| "%s"),
  251. %s.map(jubjub::ExtendedPoint::from))?;""" % (out, line, point)
  252. elif command == "fr_as_binary_le":
  253. out, fr = args
  254. return \
  255. r"""let %s = boolean::field_into_boolean_vec_le(
  256. cs.namespace(|| "%s"), %s)?;""" % (out, line, fr)
  257. elif command == "ec_mul_const":
  258. out, fr, base = args
  259. return \
  260. r"""let %s = ecc::fixed_base_multiplication(
  261. cs.namespace(|| "%s"),
  262. &%s,
  263. &%s,
  264. )?;""" % (out, line, base, fr)
  265. elif command == "emit_ec":
  266. point = args[0]
  267. return '%s.inputize(cs.namespace(|| "%s"))?;' % (point, line)
  268. def carg(self, arg):
  269. argname, is_param = arg
  270. if is_param:
  271. return "self.%s" % argname
  272. if argname in self.rename_consts:
  273. return self.rename_consts[argname]
  274. return argname
  275. def modify_stack(self, command, args):
  276. type_list = command_desc[command]
  277. assert len(type_list) == len(args)
  278. for (expected_type, new_val), (argname, is_param) in \
  279. zip(type_list, args):
  280. if is_param:
  281. assert not new_val
  282. continue
  283. # Now apply the new values to the stack
  284. if new_val:
  285. self.stack[argname] = expected_type
  286. def compile(self, constants, aux):
  287. self.constants = constants
  288. code = ""
  289. code += self._includes()
  290. self.rename_consts = {}
  291. if "constants" in aux:
  292. for const_name, value in aux["constants"].items():
  293. if "module_includes" not in value:
  294. continue
  295. if "maps_to" not in value:
  296. eprint("error: bad aux config '%s', missing maps_to" %
  297. const_name)
  298. mapped_type = value["maps_to"]
  299. code += "use %s::%s;\n" % (value["module_includes"], mapped_type)
  300. self.rename_consts[const_name] = mapped_type
  301. code += "\n"
  302. if (header := self._compile_header()) is None:
  303. return None
  304. code += header
  305. code += \
  306. r"""impl Circuit<bls12_381::Scalar> for %s {
  307. fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
  308. self,
  309. cs: &mut CS,
  310. ) -> Result<(), SynthesisError> {
  311. """ % to_initial_caps(self.name)
  312. if (body := self._compile_body()) is None:
  313. return None
  314. code += body
  315. code += "Ok(())\n"
  316. code += " }\n"
  317. code += "}\n"
  318. return code
  319. def process(contents, aux):
  320. contents = clean(contents)
  321. constants, segments = make_segments(contents)
  322. if (constants := build_constants_table(constants)) is None:
  323. return False
  324. codes = []
  325. for segment in segments:
  326. contract = extract(segment)
  327. if (code := contract.compile(constants, aux)) is None:
  328. return False
  329. codes.append(code)
  330. # Success! Output finished product.
  331. [print(code) for code in codes]
  332. return True
  333. def main(argv):
  334. if len(argv) != 2:
  335. eprint("pism FILENAME")
  336. return -1
  337. src_filename = argv[1]
  338. basename, _ = os.path.splitext(src_filename)
  339. aux_filename = basename + ".aux"
  340. aux = json.loads(open(aux_filename).read())
  341. contents = open(src_filename).read()
  342. if not process(contents, aux):
  343. return -2
  344. return 0
  345. if __name__ == "__main__":
  346. sys.exit(main(sys.argv))