vm.rs 33 KB

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