pism.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 _compile_header(self):
  151. code = "pub struct %s {\n" % to_initial_caps(self.name)
  152. for param_name, param_type in self.params.items():
  153. try:
  154. mapped_type = types_map[param_type]
  155. except KeyError:
  156. return None
  157. code += " pub %s: Option<%s>,\n" % (param_name, mapped_type)
  158. code += "}\n"
  159. return code
  160. def _compile_body(self):
  161. self.stack = {}
  162. code = "\n"
  163. #indent = " " * 8
  164. for command, args, line in self.program:
  165. if (code_text := self._compile_line(command, args, line)) is None:
  166. return None
  167. code += code_text + "\n"
  168. return code
  169. def _preprocess_args(self, args, line):
  170. nargs = []
  171. for arg in args:
  172. if not arg.startswith("param:"):
  173. nargs.append((arg, False))
  174. continue
  175. _, argname = arg.split(":", 1)
  176. if argname not in self.params:
  177. eprint("error: non-existant param referenced")
  178. eprint(line)
  179. return None
  180. nargs.append((argname, True))
  181. return nargs
  182. def type_checking(self, command, args, line):
  183. assert command in command_desc
  184. type_list = command_desc[command]
  185. if len(type_list) != len(args):
  186. eprint("error: wrong number of arguments!")
  187. eprint(line)
  188. return False
  189. for (expected_type, new_val), (argname, is_param) in \
  190. zip(type_list, args):
  191. # Only type check input arguments, not output values
  192. if new_val:
  193. continue
  194. if is_param:
  195. actual_type = self.params[argname]
  196. else:
  197. # Check the stack here
  198. if argname not in self.stack:
  199. eprint("error: cannot find value '%s' on the stack!" %
  200. argname)
  201. eprint(line)
  202. return False
  203. actual_type = self.stack[argname]
  204. return True
  205. def _check_args(self, command, args, line):
  206. assert command in command_desc
  207. type_list = command_desc[command]
  208. assert len(type_list) == len(args)
  209. for (_, is_new_val), (arg, is_param) in zip(type_list, args):
  210. if is_param:
  211. continue
  212. if is_new_val:
  213. continue
  214. if arg in self.stack:
  215. continue
  216. if arg in self.constants:
  217. continue
  218. eprint("error: cannot find '%s' in the stack" % arg)
  219. eprint(line)
  220. return False
  221. return True
  222. def _compile_line(self, command, args, line):
  223. if (args := self._preprocess_args(args, line)) is None:
  224. return None
  225. if not self.type_checking(command, args, line):
  226. return None
  227. if not self._check_args(command, args, line):
  228. return None
  229. self.modify_stack(command, args)
  230. args = [self.carg(arg) for arg in args]
  231. if command == "witness":
  232. out, point = args
  233. return \
  234. r"""let %s = ecc::EdwardsPoint::witness(
  235. cs.namespace(|| "%s"),
  236. %s.map(jubjub::ExtendedPoint::from))?;""" % (out, line, point)
  237. elif command == "fr_as_binary_le":
  238. out, fr = args
  239. return \
  240. r"""let %s = boolean::field_into_boolean_vec_le(
  241. cs.namespace(|| "%s"), %s)?;""" % (out, line, fr)
  242. elif command == "ec_mul_const":
  243. out, fr, base = args
  244. return \
  245. r"""let %s = ecc::fixed_base_multiplication(
  246. cs.namespace(|| "%s"),
  247. &%s,
  248. &%s,
  249. )?;""" % (out, line, fr, base)
  250. elif command == "emit_ec":
  251. point = args[0]
  252. return '%s.inputize(cs.namespace(|| "%s"))?;' % (point, line)
  253. def carg(self, arg):
  254. argname, is_param = arg
  255. if is_param:
  256. return "self.%s" % argname
  257. if argname in self.rename_consts:
  258. return self.rename_consts[argname]
  259. return argname
  260. def modify_stack(self, command, args):
  261. type_list = command_desc[command]
  262. assert len(type_list) == len(args)
  263. for (expected_type, new_val), (argname, is_param) in \
  264. zip(type_list, args):
  265. if is_param:
  266. assert not new_val
  267. continue
  268. # Now apply the new values to the stack
  269. if new_val:
  270. self.stack[argname] = expected_type
  271. def compile(self, constants, aux):
  272. self.constants = constants
  273. code = ""
  274. self.rename_consts = {}
  275. if "constants" in aux:
  276. for const_name, value in aux["constants"].items():
  277. if "module_includes" not in value:
  278. continue
  279. if "maps_to" not in value:
  280. eprint("error: bad aux config '%s', missing maps_to" %
  281. const_name)
  282. mapped_type = value["maps_to"]
  283. code += "use %s::%s;\n" % (value["module_includes"], mapped_type)
  284. self.rename_consts[const_name] = mapped_type
  285. code += "\n"
  286. if (header := self._compile_header()) is None:
  287. return None
  288. code += header
  289. code += \
  290. r"""impl Circuit<bls12_381::Scalar> for %s {
  291. fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
  292. self,
  293. cs: &mut CS,
  294. ) -> Result<(), SynthesisError> {
  295. """ % to_initial_caps(self.name)
  296. if (body := self._compile_body()) is None:
  297. return None
  298. code += body
  299. code += "}\n"
  300. return code
  301. def process(contents, aux):
  302. contents = clean(contents)
  303. constants, segments = make_segments(contents)
  304. if (constants := build_constants_table(constants)) is None:
  305. return False
  306. codes = []
  307. for segment in segments:
  308. contract = extract(segment)
  309. if (code := contract.compile(constants, aux)) is None:
  310. return False
  311. codes.append(code)
  312. # Success! Output finished product.
  313. [print(code) for code in codes]
  314. return True
  315. def main(argv):
  316. if len(argv) != 2:
  317. eprint("pism FILENAME")
  318. return -1
  319. src_filename = argv[1]
  320. basename, _ = os.path.splitext(src_filename)
  321. aux_filename = basename + ".aux"
  322. aux = json.loads(open(aux_filename).read())
  323. contents = open(src_filename).read()
  324. if not process(contents, aux):
  325. return -2
  326. return 0
  327. if __name__ == "__main__":
  328. sys.exit(main(sys.argv))