pism.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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_push": (
  72. ("Vec<Boolean>", False),
  73. ("Boolean", False),
  74. ),
  75. "binary_truncate": (
  76. ("Vec<Boolean>", False),
  77. ("BinarySize", False),
  78. ),
  79. "static_assert_binary_size": (
  80. ("Vec<Boolean>", False),
  81. ("INTEGER", False),
  82. ),
  83. "blake2s": (
  84. ("Vec<Boolean>", True),
  85. ("Vec<Boolean>", False),
  86. ("BlakePersonalization", False),
  87. ),
  88. "pedersen_hash": (
  89. ("EdwardsPoint", True),
  90. ("Vec<Boolean>", False),
  91. ("PedersenPersonalization", False),
  92. ),
  93. "emit_binary": (
  94. ("Vec<Boolean>", False),
  95. ),
  96. "alloc_bit": (
  97. ("Boolean", True),
  98. ("Bool", False),
  99. ),
  100. "alloc_const_bit": (
  101. ("Boolean", True),
  102. ("BOOL_CONST", False),
  103. ),
  104. "clone_bit": (
  105. ("Boolean", True),
  106. ("Boolean", False),
  107. ),
  108. "alloc_scalar": (
  109. ("ScalarNum", True),
  110. ("Scalar", False),
  111. ),
  112. "scalar_as_binary": (
  113. ("Vec<Boolean>", True),
  114. ("ScalarNum", False),
  115. ),
  116. "emit_scalar": (
  117. ("ScalarNum", False),
  118. ),
  119. "scalar_enforce_equal": (
  120. ("ScalarNum", False),
  121. ("ScalarNum", False),
  122. ),
  123. "conditionally_reverse": (
  124. ("Scalar", True),
  125. ("Scalar", True),
  126. ("Scalar", False),
  127. ("Scalar", False),
  128. ("Boolean", False),
  129. ),
  130. }
  131. def eprint(*args):
  132. print(*args, file=sys.stderr)
  133. class Line:
  134. def __init__(self, text, line_number):
  135. self.text = text
  136. self.orig = text
  137. self.lineno = line_number
  138. self.clean()
  139. def clean(self):
  140. # Remove the comments
  141. self.text = self.text.split("#", 1)[0]
  142. # Remove whitespace
  143. self.text = self.text.strip()
  144. def is_empty(self):
  145. return bool(self.text)
  146. def __repr__(self):
  147. return "Line %s: %s" % (self.lineno, self.orig.lstrip())
  148. def command(self):
  149. if not self.is_empty():
  150. return None
  151. return self.text.split(" ")[0]
  152. def args(self):
  153. if not self.is_empty():
  154. return None
  155. return self.text.split(" ")[1:]
  156. def clean(contents):
  157. # Split input into lines
  158. contents = contents.split("\n")
  159. contents = [Line(line, i) for i, line in enumerate(contents)]
  160. # Remove empty blank lines
  161. contents = [line for line in contents if line.is_empty()]
  162. return contents
  163. def make_segments(contents):
  164. constants = [line for line in contents if line.command() == "constant"]
  165. segments = []
  166. current_segment = []
  167. for line in contents:
  168. if line.command() == "contract":
  169. current_segment = []
  170. current_segment.append(line)
  171. if line.command() == "end":
  172. segments.append(current_segment)
  173. current_segment = []
  174. return constants, segments
  175. def build_constants_table(constants):
  176. table = {}
  177. for line in constants:
  178. args = line.args()
  179. if len(args) != 2:
  180. eprint("error: wrong number of args")
  181. eprint(line)
  182. return None
  183. name, type = args
  184. table[name] = type
  185. return table
  186. def extract(segment):
  187. assert segment
  188. # Does it have a declaration?
  189. if not segment[0].command() == "contract":
  190. eprint("error: missing contract declaration")
  191. eprint(segment[0])
  192. return None
  193. # Does it have an end?
  194. if not segment[-1].command() == "end":
  195. eprint("error: missing contract end")
  196. eprint(segment[-1])
  197. return None
  198. # Does it have a start?
  199. if not [line for line in segment if line.command() == "start"]:
  200. eprint("error: missing contract start")
  201. eprint(segment[0])
  202. return None
  203. for line in segment:
  204. command, args = line.command(), line.args()
  205. if command in symbol_table:
  206. if symbol_table[command] != len(args):
  207. eprint("error: wrong number of args for command '%s'" % command)
  208. eprint(line)
  209. return None
  210. elif command in command_desc:
  211. if len(command_desc[command]) != len(args):
  212. eprint("error: wrong number of args for command '%s'" % command)
  213. eprint(line)
  214. return None
  215. else:
  216. eprint("error: missing symbol for command '%s'" % command)
  217. eprint(line)
  218. return None
  219. contract_name = segment[0].args()[0]
  220. start_index = [index for index, line in enumerate(segment)
  221. if line.command() == "start"]
  222. if len(start_index) > 1:
  223. eprint("error: multiple start statements in contract '%s'" %
  224. contract_name)
  225. for index in start_index:
  226. eprint(segment[index])
  227. eprint("Aborting.")
  228. return None
  229. assert len(start_index) == 1
  230. start_index = start_index[0]
  231. header = segment[1:start_index]
  232. code = segment[start_index + 1:-1]
  233. params = {}
  234. for param_decl in header:
  235. args = param_decl.args()
  236. assert len(args) == 2
  237. name, type = args
  238. params[name] = type
  239. program = []
  240. for line in code:
  241. command, args = line.command(), line.args()
  242. program.append((command, args, line))
  243. return Contract(contract_name, params, program)
  244. def to_initial_caps(snake_str):
  245. components = snake_str.split("_")
  246. return "".join(x.title() for x in components)
  247. class Contract:
  248. def __init__(self, name, params, program):
  249. self.name = name
  250. self.params = params
  251. self.program = program
  252. def _includes(self):
  253. return \
  254. r"""use bellman::{
  255. gadgets::{
  256. boolean,
  257. boolean::{AllocatedBit, Boolean},
  258. multipack,
  259. blake2s,
  260. num,
  261. Assignment,
  262. },
  263. groth16, Circuit, ConstraintSystem, SynthesisError,
  264. };
  265. use bls12_381::Bls12;
  266. use ff::{PrimeField, Field};
  267. use group::Curve;
  268. use zcash_proofs::circuit::{ecc, pedersen_hash};
  269. """
  270. def _compile_header(self):
  271. code = "pub struct %s {\n" % to_initial_caps(self.name)
  272. for param_name, param_type in self.params.items():
  273. try:
  274. mapped_type = types_map[param_type]
  275. except KeyError:
  276. return None
  277. code += " pub %s: Option<%s>,\n" % (param_name, mapped_type)
  278. code += "}\n"
  279. return code
  280. def _compile_body(self):
  281. self.stack = {}
  282. code = "\n"
  283. #indent = " " * 8
  284. for command, args, line in self.program:
  285. if (code_text := self._compile_line(command, args, line)) is None:
  286. return None
  287. code += "// %s\n" % str(line)
  288. code += code_text + "\n\n"
  289. return code
  290. def _preprocess_args(self, args, line):
  291. nargs = []
  292. for arg in args:
  293. if not arg.startswith("param:"):
  294. nargs.append((arg, False))
  295. continue
  296. _, argname = arg.split(":", 1)
  297. if argname not in self.params:
  298. eprint("error: non-existant param referenced")
  299. eprint(line)
  300. return None
  301. nargs.append((argname, True))
  302. return nargs
  303. def type_checking(self, command, args, line):
  304. assert command in command_desc
  305. type_list = command_desc[command]
  306. if len(type_list) != len(args):
  307. eprint("error: wrong number of arguments!")
  308. eprint(line)
  309. return False
  310. for (expected_type, new_val), (argname, is_param) in \
  311. zip(type_list, args):
  312. # Only type check input arguments, not output values
  313. if new_val:
  314. continue
  315. if expected_type == "INTEGER" or expected_type == "BOOL_CONST":
  316. continue
  317. if is_param:
  318. actual_type = self.params[argname]
  319. elif argname in self.constants:
  320. actual_type = self.constants[argname]
  321. else:
  322. # Check the stack here
  323. if argname not in self.stack:
  324. eprint("error: cannot find value '%s' on the stack!" %
  325. argname)
  326. eprint(line)
  327. return False
  328. actual_type = self.stack[argname]
  329. return True
  330. def _check_args(self, command, args, line):
  331. assert command in command_desc
  332. type_list = command_desc[command]
  333. assert len(type_list) == len(args)
  334. for (expected_type, is_new_val), (arg, is_param) in zip(type_list, args):
  335. if is_param:
  336. continue
  337. if is_new_val:
  338. continue
  339. if arg in self.stack:
  340. continue
  341. if arg in self.constants:
  342. continue
  343. if expected_type == "INTEGER" or expected_type == "BOOL_CONST":
  344. continue
  345. eprint("error: cannot find '%s' in the stack" % arg)
  346. eprint(line)
  347. return False
  348. return True
  349. def _compile_line(self, command, args, line):
  350. if (args := self._preprocess_args(args, line)) is None:
  351. return None
  352. if not self.type_checking(command, args, line):
  353. return None
  354. if not self._check_args(command, args, line):
  355. return None
  356. self.modify_stack(command, args)
  357. args = [self.carg(arg) for arg in args]
  358. try:
  359. codegen_method = getattr(codegen, command)
  360. except AttributeError:
  361. eprint("error: missing command '%s' does not exist" % command)
  362. eprint(line)
  363. return None
  364. return codegen_method(line, *args)
  365. def carg(self, arg):
  366. argname, is_param = arg
  367. if is_param:
  368. return "self.%s" % argname
  369. if argname in self.rename_consts:
  370. return self.rename_consts[argname]
  371. return argname
  372. def modify_stack(self, command, args):
  373. type_list = command_desc[command]
  374. assert len(type_list) == len(args)
  375. for (expected_type, new_val), (argname, is_param) in \
  376. zip(type_list, args):
  377. if is_param:
  378. assert not new_val
  379. continue
  380. # Now apply the new values to the stack
  381. if new_val:
  382. self.stack[argname] = expected_type
  383. def compile(self, constants, aux):
  384. self.constants = constants
  385. code = ""
  386. code += self._includes()
  387. self.rename_consts = {}
  388. if "constants" in aux:
  389. for const_name, value in aux["constants"].items():
  390. if "maps_to" not in value:
  391. eprint("error: bad aux config '%s', missing maps_to" %
  392. const_name)
  393. return None
  394. mapped_type = value["maps_to"]
  395. self.rename_consts[const_name] = mapped_type
  396. code += "\n"
  397. if (header := self._compile_header()) is None:
  398. return None
  399. code += header
  400. code += \
  401. r"""impl Circuit<bls12_381::Scalar> for %s {
  402. fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
  403. self,
  404. cs: &mut CS,
  405. ) -> Result<(), SynthesisError> {
  406. """ % to_initial_caps(self.name)
  407. if (body := self._compile_body()) is None:
  408. return None
  409. code += body
  410. code += "Ok(())\n"
  411. code += " }\n"
  412. code += "}\n"
  413. return code
  414. def process(contents, aux):
  415. contents = clean(contents)
  416. constants, segments = make_segments(contents)
  417. if (constants := build_constants_table(constants)) is None:
  418. return False
  419. codes = []
  420. for segment in segments:
  421. if (contract := extract(segment)) is None:
  422. return False
  423. if (code := contract.compile(constants, aux)) is None:
  424. return False
  425. codes.append(code)
  426. # Success! Output finished product.
  427. [print(code) for code in codes]
  428. return True
  429. def main(argv):
  430. if len(argv) != 3:
  431. eprint("pism FILENAME AUX_FILENAME")
  432. return -1
  433. aux_filename = argv[2]
  434. aux = json.loads(open(aux_filename).read())
  435. src_filename = argv[1]
  436. contents = open(src_filename).read()
  437. if not process(contents, aux):
  438. return -2
  439. return 0
  440. if __name__ == "__main__":
  441. sys.exit(main(sys.argv))