vm.rs 30 KB

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