pism.py 13 KB

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