pism.py 14 KB

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