vm.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. use halo2_gadgets::{
  2. ecc::{
  3. chip::{EccChip, EccConfig},
  4. FixedPoint, FixedPointBaseField, FixedPointShort, Point, ScalarFixed, ScalarFixedShort,
  5. },
  6. poseidon::{
  7. primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip,
  8. Pow5Config as PoseidonConfig,
  9. },
  10. sinsemilla::{
  11. chip::{SinsemillaChip, SinsemillaConfig},
  12. merkle::{
  13. chip::{MerkleChip, MerkleConfig},
  14. MerklePath,
  15. },
  16. },
  17. utilities::lookup_range_check::LookupRangeCheckConfig,
  18. };
  19. use halo2_proofs::{
  20. circuit::{floor_planner, AssignedCell, Layouter, Value},
  21. pasta::{group::Curve, pallas, Fp},
  22. plonk,
  23. plonk::{Advice, Circuit, Column, ConstraintSystem, Instance as InstanceColumn},
  24. };
  25. use log::{debug, error};
  26. pub use super::vm_stack::{StackVar, Witness};
  27. use super::{
  28. assign_free_advice,
  29. gadget::{
  30. arithmetic::{ArithChip, ArithConfig, ArithInstruction},
  31. less_than::{LessThanChip, LessThanConfig},
  32. native_range_check::{NativeRangeCheckChip, NativeRangeCheckConfig},
  33. small_range_check::{SmallRangeCheckChip, SmallRangeCheckConfig},
  34. },
  35. };
  36. use crate::{
  37. crypto::constants::{
  38. sinsemilla::{OrchardCommitDomains, OrchardHashDomains},
  39. util::gen_const_array,
  40. NullifierK, OrchardFixedBases, OrchardFixedBasesFull, ValueCommitV, MERKLE_DEPTH_ORCHARD,
  41. },
  42. zkas::{
  43. types::{LitType, StackType},
  44. Opcode, ZkBinary,
  45. },
  46. };
  47. #[derive(Clone)]
  48. pub struct VmConfig {
  49. primary: Column<InstanceColumn>,
  50. advices: [Column<Advice>; 10],
  51. ecc_config: EccConfig<OrchardFixedBases>,
  52. merkle_cfg1: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  53. merkle_cfg2: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  54. sinsemilla_cfg1: SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  55. _sinsemilla_cfg2: SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  56. poseidon_config: PoseidonConfig<pallas::Base, 3, 2>,
  57. arith_config: ArithConfig,
  58. native_64_range_check_config: NativeRangeCheckConfig<3, 64, 22>,
  59. native_253_range_check_config: NativeRangeCheckConfig<3, 253, 85>,
  60. lessthan_config: LessThanConfig<3, 253, 85>,
  61. boolcheck_config: SmallRangeCheckConfig,
  62. }
  63. impl VmConfig {
  64. fn ecc_chip(&self) -> EccChip<OrchardFixedBases> {
  65. EccChip::construct(self.ecc_config.clone())
  66. }
  67. fn merkle_chip_1(
  68. &self,
  69. ) -> MerkleChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
  70. MerkleChip::construct(self.merkle_cfg1.clone())
  71. }
  72. fn merkle_chip_2(
  73. &self,
  74. ) -> MerkleChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
  75. MerkleChip::construct(self.merkle_cfg2.clone())
  76. }
  77. fn poseidon_chip(&self) -> PoseidonChip<pallas::Base, 3, 2> {
  78. PoseidonChip::construct(self.poseidon_config.clone())
  79. }
  80. fn arithmetic_chip(&self) -> ArithChip {
  81. ArithChip::construct(self.arith_config.clone())
  82. }
  83. }
  84. pub struct ZkCircuit {
  85. constants: Vec<String>,
  86. witnesses: Vec<Witness>,
  87. literals: Vec<(LitType, String)>,
  88. opcodes: Vec<(Opcode, Vec<(StackType, usize)>)>,
  89. }
  90. impl ZkCircuit {
  91. pub fn new(witnesses: Vec<Witness>, circuit_code: ZkBinary) -> Self {
  92. let constants = circuit_code.constants.iter().map(|x| x.1.clone()).collect();
  93. #[allow(clippy::map_clone)]
  94. let literals = circuit_code.literals.iter().map(|x| x.clone()).collect();
  95. Self { constants, witnesses, literals, opcodes: circuit_code.opcodes }
  96. }
  97. }
  98. impl Circuit<pallas::Base> for ZkCircuit {
  99. type Config = VmConfig;
  100. type FloorPlanner = floor_planner::V1;
  101. fn without_witnesses(&self) -> Self {
  102. Self {
  103. constants: self.constants.clone(),
  104. witnesses: self.witnesses.clone(),
  105. literals: self.literals.clone(),
  106. opcodes: self.opcodes.clone(),
  107. }
  108. }
  109. fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
  110. // Advice columns used in the circuit
  111. let advices = [
  112. meta.advice_column(),
  113. meta.advice_column(),
  114. meta.advice_column(),
  115. meta.advice_column(),
  116. meta.advice_column(),
  117. meta.advice_column(),
  118. meta.advice_column(),
  119. meta.advice_column(),
  120. meta.advice_column(),
  121. meta.advice_column(),
  122. ];
  123. // Fixed columns for the Sinsemilla generator lookup table
  124. let table_idx = meta.lookup_table_column();
  125. let lookup = (table_idx, meta.lookup_table_column(), meta.lookup_table_column());
  126. // Instance column used for public inputs
  127. let primary = meta.instance_column();
  128. meta.enable_equality(primary);
  129. // Permutation over all advice columns
  130. for advice in advices.iter() {
  131. meta.enable_equality(*advice);
  132. }
  133. // Poseidon requires four advice columns, while ECC incomplete addition
  134. // requires six. We can reduce the proof size by sharing fixed columns
  135. // between the ECC and Poseidon chips.
  136. // TODO: For multiple invocations perhaps they could/should be configured
  137. // in parallel rather than sharing?
  138. let lagrange_coeffs = [
  139. meta.fixed_column(),
  140. meta.fixed_column(),
  141. meta.fixed_column(),
  142. meta.fixed_column(),
  143. meta.fixed_column(),
  144. meta.fixed_column(),
  145. meta.fixed_column(),
  146. meta.fixed_column(),
  147. ];
  148. let rc_a = lagrange_coeffs[2..5].try_into().unwrap();
  149. let rc_b = lagrange_coeffs[5..8].try_into().unwrap();
  150. // Also use the first Lagrange coefficient column for loading global constants.
  151. meta.enable_constant(lagrange_coeffs[0]);
  152. // Use one of the right-most advice columns for all of our range checks.
  153. let range_check = LookupRangeCheckConfig::configure(meta, advices[9], table_idx);
  154. // Configuration for curve point operations.
  155. // This uses 10 advice columns and spans the whole circuit.
  156. let ecc_config =
  157. EccChip::<OrchardFixedBases>::configure(meta, advices, lagrange_coeffs, range_check);
  158. // Configuration for the Poseidon hash
  159. let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
  160. meta,
  161. advices[6..9].try_into().unwrap(),
  162. advices[5],
  163. rc_a,
  164. rc_b,
  165. );
  166. // Configuration for the Arithmetic chip
  167. let arith_config = ArithChip::configure(meta, advices[7], advices[8], advices[6]);
  168. // Configuration for a Sinsemilla hash instantiation and a
  169. // Merkle hash instantiation using this Sinsemilla instance.
  170. // Since the Sinsemilla config uses only 5 advice columns,
  171. // we can fit two instances side-by-side.
  172. let (sinsemilla_cfg1, merkle_cfg1) = {
  173. let sinsemilla_cfg1 = SinsemillaChip::configure(
  174. meta,
  175. advices[..5].try_into().unwrap(),
  176. advices[6],
  177. lagrange_coeffs[0],
  178. lookup,
  179. range_check,
  180. );
  181. let merkle_cfg1 = MerkleChip::configure(meta, sinsemilla_cfg1.clone());
  182. (sinsemilla_cfg1, merkle_cfg1)
  183. };
  184. let (_sinsemilla_cfg2, merkle_cfg2) = {
  185. let sinsemilla_cfg2 = SinsemillaChip::configure(
  186. meta,
  187. advices[5..].try_into().unwrap(),
  188. advices[7],
  189. lagrange_coeffs[1],
  190. lookup,
  191. range_check,
  192. );
  193. let merkle_cfg2 = MerkleChip::configure(meta, sinsemilla_cfg2.clone());
  194. (sinsemilla_cfg2, merkle_cfg2)
  195. };
  196. // K-table for 64 bit range check lookups
  197. let k_values_table_64 = meta.lookup_table_column();
  198. let native_64_range_check_config =
  199. NativeRangeCheckChip::<3, 64, 22>::configure(meta, advices[8], k_values_table_64);
  200. // K-table for 253 bit range check lookups
  201. let k_values_table_253 = meta.lookup_table_column();
  202. let native_253_range_check_config =
  203. NativeRangeCheckChip::<3, 253, 85>::configure(meta, advices[8], k_values_table_253);
  204. let lessthan_config = LessThanChip::<3, 253, 85>::configure(
  205. meta,
  206. advices[6],
  207. advices[7],
  208. advices[8],
  209. k_values_table_253,
  210. );
  211. // Configuration for boolean checks, it uses the small_range_check
  212. // chip with a range of 2, which enforces one bit, i.e. 0 or 1.
  213. let boolcheck_config = SmallRangeCheckChip::configure(meta, advices[9], 2);
  214. VmConfig {
  215. primary,
  216. advices,
  217. ecc_config,
  218. merkle_cfg1,
  219. merkle_cfg2,
  220. sinsemilla_cfg1,
  221. _sinsemilla_cfg2,
  222. poseidon_config,
  223. arith_config,
  224. native_64_range_check_config,
  225. native_253_range_check_config,
  226. lessthan_config,
  227. boolcheck_config,
  228. }
  229. }
  230. fn synthesize(
  231. &self,
  232. config: Self::Config,
  233. mut layouter: impl Layouter<pallas::Base>,
  234. ) -> std::result::Result<(), plonk::Error> {
  235. debug!("Entering synthesize()");
  236. // ===================
  237. // VM Setup
  238. //====================
  239. // Our stack which holds every variable we reference and create.
  240. let mut stack: Vec<StackVar> = vec![];
  241. // Our stack which holds all the literal values we have in the circuit.
  242. // For now, we only support u64.
  243. let mut litstack: Vec<u64> = vec![];
  244. // Offset for public inputs
  245. let mut public_inputs_offset = 0;
  246. // Offset for literals
  247. let mut literals_offset = 0;
  248. // Load the Sinsemilla generator lookup table used by the whole circuit.
  249. SinsemillaChip::load(config.sinsemilla_cfg1.clone(), &mut layouter)?;
  250. // Construct the 64-bit NativeRangeCheck and LessThan chips
  251. let rangecheck64_chip = NativeRangeCheckChip::<3, 64, 22>::construct(
  252. config.native_64_range_check_config.clone(),
  253. );
  254. NativeRangeCheckChip::<3, 64, 22>::load_k_table(
  255. &mut layouter,
  256. config.native_64_range_check_config.k_values_table,
  257. )?;
  258. // Construct the 253-bit NativeRangeCheck and LessThan chips.
  259. let rangecheck253_chip = NativeRangeCheckChip::<3, 253, 85>::construct(
  260. config.native_253_range_check_config.clone(),
  261. );
  262. let lessthan_chip = LessThanChip::<3, 253, 85>::construct(config.lessthan_config.clone());
  263. NativeRangeCheckChip::<3, 253, 85>::load_k_table(
  264. &mut layouter,
  265. config.native_253_range_check_config.k_values_table,
  266. )?;
  267. // Construct the ECC chip.
  268. let ecc_chip = config.ecc_chip();
  269. // Construct the Arithmetic chip.
  270. let arith_chip = config.arithmetic_chip();
  271. // Construct the boolean check chip.
  272. let boolcheck_chip = SmallRangeCheckChip::construct(config.boolcheck_config.clone());
  273. // ==========================
  274. // Constants setup
  275. // ==========================
  276. // This constant one is used for short multiplication
  277. let one = assign_free_advice(
  278. layouter.namespace(|| "Load constant one"),
  279. config.advices[0],
  280. Value::known(pallas::Base::one()),
  281. )?;
  282. // Lookup and push constants onto the stack
  283. for constant in &self.constants {
  284. debug!("Pushing constant `{}` to stack index {}", constant.as_str(), stack.len());
  285. match constant.as_str() {
  286. "VALUE_COMMIT_VALUE" => {
  287. let vcv = ValueCommitV;
  288. let vcv = FixedPointShort::from_inner(ecc_chip.clone(), vcv);
  289. stack.push(StackVar::EcFixedPointShort(vcv));
  290. }
  291. "VALUE_COMMIT_RANDOM" => {
  292. let vcr = OrchardFixedBasesFull::ValueCommitR;
  293. let vcr = FixedPoint::from_inner(ecc_chip.clone(), vcr);
  294. stack.push(StackVar::EcFixedPoint(vcr));
  295. }
  296. "NULLIFIER_K" => {
  297. let nfk = NullifierK;
  298. let nfk = FixedPointBaseField::from_inner(ecc_chip.clone(), nfk);
  299. stack.push(StackVar::EcFixedPointBase(nfk));
  300. }
  301. _ => {
  302. error!("Invalid constant name: {}", constant.as_str());
  303. return Err(plonk::Error::Synthesis)
  304. }
  305. }
  306. }
  307. // Load the literals onto the literal stack.
  308. // N.B. Only uint64 is supported right now.
  309. for literal in &self.literals {
  310. match literal.0 {
  311. LitType::Uint64 => match literal.1.parse::<u64>() {
  312. Ok(v) => litstack.push(v),
  313. Err(e) => {
  314. error!("Failed converting u64 literal: {}", e);
  315. return Err(plonk::Error::Synthesis)
  316. }
  317. },
  318. _ => {
  319. error!("Invalid literal: {:?}", literal);
  320. return Err(plonk::Error::Synthesis)
  321. }
  322. }
  323. }
  324. // Push the witnesses onto the stack, and potentially, if the witness
  325. // is in the Base field (like the entire circuit is), load it into a
  326. // table cell.
  327. for witness in &self.witnesses {
  328. match witness {
  329. Witness::EcPoint(w) => {
  330. debug!("Witnessing EcPoint into circuit");
  331. let point = Point::new(
  332. ecc_chip.clone(),
  333. layouter.namespace(|| "Witness EcPoint"),
  334. w.as_ref().map(|cm| cm.to_affine()),
  335. )?;
  336. debug!("Pushing EcPoint to stack index {}", stack.len());
  337. stack.push(StackVar::EcPoint(point));
  338. }
  339. Witness::EcFixedPoint(_) => {
  340. error!("Unable to witness EcFixedPoint, this is unimplemented.");
  341. return Err(plonk::Error::Synthesis)
  342. }
  343. Witness::Base(w) => {
  344. debug!("Witnessing Base into circuit");
  345. let base = assign_free_advice(
  346. layouter.namespace(|| "Witness Base"),
  347. config.advices[0],
  348. *w,
  349. )?;
  350. debug!("Pushing Base to stack index {}", stack.len());
  351. stack.push(StackVar::Base(base));
  352. }
  353. Witness::Scalar(w) => {
  354. debug!("Pushing Scalar to stack index {}", stack.len());
  355. stack.push(StackVar::Scalar(*w));
  356. }
  357. Witness::MerklePath(w) => {
  358. debug!("Witnessing MerklePath into circuit");
  359. let path: Value<[pallas::Base; MERKLE_DEPTH_ORCHARD]> =
  360. w.map(|typed_path| gen_const_array(|i| typed_path[i].inner()));
  361. debug!("Pushing MerklePath to stack index {}", stack.len());
  362. stack.push(StackVar::MerklePath(path));
  363. }
  364. Witness::Uint32(w) => {
  365. debug!("Pushing Uint32 to stack index {}", stack.len());
  366. stack.push(StackVar::Uint32(*w));
  367. }
  368. Witness::Uint64(w) => {
  369. debug!("Pushing Uint64 to stack index {}", stack.len());
  370. stack.push(StackVar::Uint64(*w));
  371. }
  372. }
  373. }
  374. // =============================
  375. // And now, work through opcodes
  376. // =============================
  377. // TODO: Copy constraints
  378. for opcode in &self.opcodes {
  379. match opcode.0 {
  380. Opcode::EcAdd => {
  381. debug!("Executing `EcAdd{:?}` opcode", opcode.1);
  382. let args = &opcode.1;
  383. let lhs: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  384. stack[args[0].1].clone().into();
  385. let rhs: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  386. stack[args[1].1].clone().into();
  387. let ret = lhs.add(layouter.namespace(|| "EcAdd()"), &rhs)?;
  388. debug!("Pushing result to stack index {}", stack.len());
  389. stack.push(StackVar::EcPoint(ret));
  390. }
  391. Opcode::EcMul => {
  392. debug!("Executing `EcMul{:?}` opcode", opcode.1);
  393. let args = &opcode.1;
  394. let lhs: FixedPoint<pallas::Affine, EccChip<OrchardFixedBases>> =
  395. stack[args[1].1].clone().into();
  396. let rhs = ScalarFixed::new(
  397. ecc_chip.clone(),
  398. layouter.namespace(|| "EcMul: ScalarFixed::new()"),
  399. stack[args[0].1].clone().into(),
  400. )?;
  401. let (ret, _) = lhs.mul(layouter.namespace(|| "EcMul()"), rhs)?;
  402. debug!("Pushing result to stack index {}", stack.len());
  403. stack.push(StackVar::EcPoint(ret));
  404. }
  405. Opcode::EcMulBase => {
  406. debug!("Executing `EcMulBase{:?}` opcode", opcode.1);
  407. let args = &opcode.1;
  408. let lhs: FixedPointBaseField<pallas::Affine, EccChip<OrchardFixedBases>> =
  409. stack[args[1].1].clone().into();
  410. let rhs: AssignedCell<Fp, Fp> = stack[args[0].1].clone().into();
  411. let ret = lhs.mul(layouter.namespace(|| "EcMulBase()"), rhs)?;
  412. debug!("Pushing result to stack index {}", stack.len());
  413. stack.push(StackVar::EcPoint(ret));
  414. }
  415. Opcode::EcMulShort => {
  416. debug!("Executing `EcMulShort{:?}` opcode", opcode.1);
  417. let args = &opcode.1;
  418. let lhs: FixedPointShort<pallas::Affine, EccChip<OrchardFixedBases>> =
  419. stack[args[1].1].clone().into();
  420. let rhs = ScalarFixedShort::new(
  421. ecc_chip.clone(),
  422. layouter.namespace(|| "EcMulShort: ScalarFixedShort::new()"),
  423. (stack[args[0].1].clone().into(), one.clone()),
  424. )?;
  425. let (ret, _) = lhs.mul(layouter.namespace(|| "EcMulShort()"), rhs)?;
  426. debug!("Pushing result to stack index {}", stack.len());
  427. stack.push(StackVar::EcPoint(ret));
  428. }
  429. Opcode::EcGetX => {
  430. debug!("Executing `EcGetX{:?}` opcode", opcode.1);
  431. let args = &opcode.1;
  432. let point: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  433. stack[args[0].1].clone().into();
  434. let ret = point.inner().x();
  435. debug!("Pushing result to stack index {}", stack.len());
  436. stack.push(StackVar::Base(ret));
  437. }
  438. Opcode::EcGetY => {
  439. debug!("Executing `EcGetY{:?}` opcode", opcode.1);
  440. let args = &opcode.1;
  441. let point: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  442. stack[args[0].1].clone().into();
  443. let ret = point.inner().y();
  444. debug!("Pushing result to stack index {}", stack.len());
  445. stack.push(StackVar::Base(ret));
  446. }
  447. Opcode::PoseidonHash => {
  448. debug!("Executing `PoseidonHash{:?}` opcode", opcode.1);
  449. let args = &opcode.1;
  450. let mut poseidon_message: Vec<AssignedCell<Fp, Fp>> =
  451. Vec::with_capacity(args.len());
  452. for idx in args {
  453. poseidon_message.push(stack[idx.1].clone().into());
  454. }
  455. macro_rules! poseidon_hash {
  456. ($len:expr, $hasher:ident, $output:ident, $cell:ident) => {
  457. let $hasher = PoseidonHash::<
  458. _,
  459. _,
  460. poseidon::P128Pow5T3,
  461. poseidon::ConstantLength<$len>,
  462. 3,
  463. 2,
  464. >::init(
  465. config.poseidon_chip(),
  466. layouter.namespace(|| "PoseidonHash init"),
  467. )?;
  468. let $output = $hasher.hash(
  469. layouter.namespace(|| "PoseidonHash hash"),
  470. poseidon_message.try_into().unwrap(),
  471. )?;
  472. let $cell: AssignedCell<Fp, Fp> = $output.into();
  473. debug!("Pushing hash to stack index {}", stack.len());
  474. stack.push(StackVar::Base($cell));
  475. };
  476. }
  477. macro_rules! vla {
  478. ($args:ident, $a:ident, $b:ident, $c:ident, $($num:tt)*) => {
  479. match $args.len() {
  480. $($num => {
  481. poseidon_hash!($num, $a, $b, $c);
  482. })*
  483. _ => {
  484. error!("Unsupported poseidon hash for {} elements", $args.len());
  485. return Err(plonk::Error::Synthesis)
  486. }
  487. }
  488. };
  489. }
  490. vla!(args, a, b, c, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);
  491. }
  492. Opcode::MerkleRoot => {
  493. debug!("Executing `MerkleRoot{:?}` opcode", opcode.1);
  494. let args = &opcode.1;
  495. let leaf_pos = stack[args[0].1].clone().into();
  496. let merkle_path = stack[args[1].1].clone().into();
  497. let leaf = stack[args[2].1].clone().into();
  498. let merkle_inputs = MerklePath::construct(
  499. [config.merkle_chip_1(), config.merkle_chip_2()],
  500. OrchardHashDomains::MerkleCrh,
  501. leaf_pos,
  502. merkle_path,
  503. );
  504. let root = merkle_inputs
  505. .calculate_root(layouter.namespace(|| "MerkleRoot()"), leaf)?;
  506. debug!("Pushing merkle root to stack index {}", stack.len());
  507. stack.push(StackVar::Base(root));
  508. }
  509. Opcode::BaseAdd => {
  510. debug!("Executing `BaseAdd{:?}` opcode", opcode.1);
  511. let args = &opcode.1;
  512. let lhs = &stack[args[0].1].clone().into();
  513. let rhs = &stack[args[1].1].clone().into();
  514. let sum = arith_chip.add(layouter.namespace(|| "BaseAdd()"), lhs, rhs)?;
  515. debug!("Pushing sum to stack index {}", stack.len());
  516. stack.push(StackVar::Base(sum));
  517. }
  518. Opcode::BaseMul => {
  519. debug!("Executing `BaseSub{:?}` opcode", opcode.1);
  520. let args = &opcode.1;
  521. let lhs = &stack[args[0].1].clone().into();
  522. let rhs = &stack[args[1].1].clone().into();
  523. let product = arith_chip.mul(layouter.namespace(|| "BaseMul()"), lhs, rhs)?;
  524. debug!("Pushing product to stack index {}", stack.len());
  525. stack.push(StackVar::Base(product));
  526. }
  527. Opcode::BaseSub => {
  528. debug!("Executing `BaseSub{:?}` opcode", opcode.1);
  529. let args = &opcode.1;
  530. let lhs = &stack[args[0].1].clone().into();
  531. let rhs = &stack[args[1].1].clone().into();
  532. let difference =
  533. arith_chip.sub(layouter.namespace(|| "BaseSub()"), lhs, rhs)?;
  534. debug!("Pushing difference to stack index {}", stack.len());
  535. stack.push(StackVar::Base(difference));
  536. }
  537. Opcode::WitnessBase => {
  538. debug!("Executing `WitnessBase{:?}` opcode", opcode.1);
  539. //let args = &opcode.1;
  540. let lit = litstack[literals_offset];
  541. literals_offset += 1;
  542. let witness = assign_free_advice(
  543. layouter.namespace(|| "Witness literal"),
  544. config.advices[0],
  545. Value::known(pallas::Base::from(lit)),
  546. )?;
  547. debug!("Pushing assignment to stack index {}", stack.len());
  548. stack.push(StackVar::Base(witness));
  549. }
  550. Opcode::RangeCheck => {
  551. debug!("Executing `RangeCheck{:?}` opcode", opcode.1);
  552. let args = &opcode.1;
  553. let lit = litstack[literals_offset];
  554. literals_offset += 1;
  555. let arg = stack[args[1].1].clone();
  556. match lit {
  557. 64 => {
  558. rangecheck64_chip.copy_range_check(
  559. layouter.namespace(|| "copy range check 64"),
  560. arg.into(),
  561. true,
  562. )?;
  563. }
  564. 253 => {
  565. rangecheck253_chip.copy_range_check(
  566. layouter.namespace(|| "copy range check 253"),
  567. arg.into(),
  568. true,
  569. )?;
  570. }
  571. x => {
  572. error!("Unsupported bit-range {} for range_check", x);
  573. return Err(plonk::Error::Synthesis)
  574. }
  575. }
  576. }
  577. Opcode::LessThan => {
  578. debug!("Executing `LessThan{:?}` opcode", opcode.1);
  579. let args = &opcode.1;
  580. let a = stack[args[0].1].clone().into();
  581. let b = stack[args[1].1].clone().into();
  582. lessthan_chip.copy_less_than(
  583. layouter.namespace(|| "copy a<b check"),
  584. a,
  585. b,
  586. 0,
  587. true,
  588. )?;
  589. }
  590. Opcode::BoolCheck => {
  591. debug!("Executing `BoolCheck{:?}` opcode", opcode.1);
  592. let args = &opcode.1;
  593. let w = stack[args[0].1].clone().into();
  594. boolcheck_chip
  595. .small_range_check(layouter.namespace(|| "copy boolean check"), w)?;
  596. }
  597. Opcode::ConstrainInstance => {
  598. debug!("Executing `ConstrainInstance{:?}` opcode", opcode.1);
  599. let args = &opcode.1;
  600. let var: AssignedCell<Fp, Fp> = stack[args[0].1].clone().into();
  601. layouter.constrain_instance(
  602. var.cell(),
  603. config.primary,
  604. public_inputs_offset,
  605. )?;
  606. public_inputs_offset += 1;
  607. }
  608. _ => {
  609. error!("Unsupported opcode");
  610. return Err(plonk::Error::Synthesis)
  611. }
  612. }
  613. }
  614. debug!("Exiting synthesize() successfully");
  615. Ok(())
  616. }
  617. }