pism.py 14 KB

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