vm.rs 37 KB

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