vm.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. use halo2_gadgets::{
  2. ecc::{
  3. chip::{EccChip, EccConfig},
  4. FixedPoint, FixedPointBaseField, FixedPointShort, Point, ScalarFixed, ScalarFixedShort,
  5. },
  6. poseidon::{
  7. primitives as poseidon, Hash as PoseidonHash, Pow5Chip as PoseidonChip,
  8. Pow5Config as PoseidonConfig,
  9. },
  10. sinsemilla::{
  11. chip::{SinsemillaChip, SinsemillaConfig},
  12. merkle::{
  13. chip::{MerkleChip, MerkleConfig},
  14. MerklePath,
  15. },
  16. },
  17. utilities::lookup_range_check::LookupRangeCheckConfig,
  18. };
  19. use halo2_proofs::{
  20. circuit::{AssignedCell, Layouter, SimpleFloorPlanner, Value},
  21. plonk,
  22. plonk::{Advice, Circuit, Column, ConstraintSystem, Instance as InstanceColumn},
  23. };
  24. use log::debug;
  25. use pasta_curves::{group::Curve, pallas, Fp};
  26. use super::gadget::arithmetic::{ArithChip, ArithConfig, ArithInstruction};
  27. use super::assign_free_advice;
  28. pub use super::vm_stack::{StackVar, Witness};
  29. use crate::{
  30. crypto::constants::{
  31. sinsemilla::{OrchardCommitDomains, OrchardHashDomains},
  32. util::gen_const_array,
  33. NullifierK, OrchardFixedBases, OrchardFixedBasesFull, ValueCommitV, MERKLE_DEPTH_ORCHARD,
  34. },
  35. zkas::{decoder::ZkBinary, opcode::Opcode},
  36. };
  37. #[derive(Clone)]
  38. pub struct VmConfig {
  39. primary: Column<InstanceColumn>,
  40. advices: [Column<Advice>; 10],
  41. ecc_config: EccConfig<OrchardFixedBases>,
  42. merkle_cfg1: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  43. merkle_cfg2: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  44. sinsemilla_cfg1: SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  45. _sinsemilla_cfg2: SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  46. poseidon_config: PoseidonConfig<pallas::Base, 3, 2>,
  47. arith_config: ArithConfig,
  48. }
  49. impl VmConfig {
  50. fn ecc_chip(&self) -> EccChip<OrchardFixedBases> {
  51. EccChip::construct(self.ecc_config.clone())
  52. }
  53. /*
  54. fn sinsemilla_chip_1(
  55. &self,
  56. ) -> SinsemillaChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
  57. SinsemillaChip::construct(self.sinsemilla_cfg1.clone())
  58. }
  59. fn sinsemilla_chip_2(
  60. &self,
  61. ) -> SinsemillaChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
  62. SinsemillaChip::construct(self.sinsemilla_cfg2.clone())
  63. }
  64. */
  65. fn merkle_chip_1(
  66. &self,
  67. ) -> MerkleChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
  68. MerkleChip::construct(self.merkle_cfg1.clone())
  69. }
  70. fn merkle_chip_2(
  71. &self,
  72. ) -> MerkleChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
  73. MerkleChip::construct(self.merkle_cfg2.clone())
  74. }
  75. fn poseidon_chip(&self) -> PoseidonChip<pallas::Base, 3, 2> {
  76. PoseidonChip::construct(self.poseidon_config.clone())
  77. }
  78. fn arithmetic_chip(&self) -> ArithChip {
  79. ArithChip::construct(self.arith_config.clone())
  80. }
  81. }
  82. #[derive(Clone, Default)]
  83. pub struct ZkCircuit {
  84. constants: Vec<String>,
  85. witnesses: Vec<Witness>,
  86. opcodes: Vec<(Opcode, Vec<usize>)>,
  87. }
  88. impl ZkCircuit {
  89. pub fn new(witnesses: Vec<Witness>, circuit_code: ZkBinary) -> Self {
  90. let constants = circuit_code.constants.iter().map(|x| x.1.clone()).collect();
  91. Self { constants, witnesses, opcodes: circuit_code.opcodes }
  92. }
  93. }
  94. impl Circuit<pallas::Base> for ZkCircuit {
  95. type Config = VmConfig;
  96. type FloorPlanner = SimpleFloorPlanner;
  97. fn without_witnesses(&self) -> Self {
  98. Self {
  99. constants: self.constants.clone(),
  100. witnesses: self.witnesses.clone(),
  101. opcodes: self.opcodes.clone(),
  102. }
  103. }
  104. fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
  105. // Advice columns used in the circuit
  106. let advices = [
  107. meta.advice_column(),
  108. meta.advice_column(),
  109. meta.advice_column(),
  110. meta.advice_column(),
  111. meta.advice_column(),
  112. meta.advice_column(),
  113. meta.advice_column(),
  114. meta.advice_column(),
  115. meta.advice_column(),
  116. meta.advice_column(),
  117. //meta.advice_column(),
  118. //meta.advice_column(),
  119. ];
  120. // Fixed columns for the Sinsemilla generator lookup table
  121. let table_idx = meta.lookup_table_column();
  122. let lookup = (table_idx, meta.lookup_table_column(), meta.lookup_table_column());
  123. // Instance column used for public inputs
  124. let primary = meta.instance_column();
  125. meta.enable_equality(primary);
  126. // Permutation over all advice columns
  127. for advice in advices.iter() {
  128. meta.enable_equality(*advice);
  129. }
  130. // Poseidon requires four advice columns, while ECC incomplete addition
  131. // requires six. We can reduce the proof size by sharing fixed columns
  132. // between the ECC and Poseidon chips.
  133. // TODO: For multiple invocations perhaps they could/should be configured
  134. // in parallel rather than sharing?
  135. let lagrange_coeffs = [
  136. meta.fixed_column(),
  137. meta.fixed_column(),
  138. meta.fixed_column(),
  139. meta.fixed_column(),
  140. meta.fixed_column(),
  141. meta.fixed_column(),
  142. meta.fixed_column(),
  143. meta.fixed_column(),
  144. ];
  145. let rc_a = lagrange_coeffs[2..5].try_into().unwrap();
  146. let rc_b = lagrange_coeffs[5..8].try_into().unwrap();
  147. // Also use the first Lagrange coefficient column for loading global constants.
  148. meta.enable_constant(lagrange_coeffs[0]);
  149. // Use one of the right-most advice columns for all of our range checks.
  150. let range_check = LookupRangeCheckConfig::configure(meta, advices[9], table_idx);
  151. // Configuration for curve point operations.
  152. // This uses 10 advice columns and spans the whole circuit.
  153. let ecc_config =
  154. EccChip::<OrchardFixedBases>::configure(meta, advices, lagrange_coeffs, range_check);
  155. // Configuration for the Poseidon hash
  156. let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
  157. meta,
  158. advices[6..9].try_into().unwrap(),
  159. advices[5],
  160. rc_a,
  161. rc_b,
  162. );
  163. // Configuration for the Arithmetic chip
  164. let arith_config = ArithChip::configure(meta, advices[7], advices[8], advices[6]);
  165. // Configuration for a Sinsemilla hash instantiation and a
  166. // Merkle hash instantiation using this Sinsemilla instance.
  167. // Since the Sinsemilla config uses only 5 advice columns,
  168. // we can fit two instances side-by-side.
  169. let (sinsemilla_cfg1, merkle_cfg1) = {
  170. let sinsemilla_cfg1 = SinsemillaChip::configure(
  171. meta,
  172. advices[..5].try_into().unwrap(),
  173. advices[6],
  174. lagrange_coeffs[0],
  175. lookup,
  176. range_check,
  177. );
  178. let merkle_cfg1 = MerkleChip::configure(meta, sinsemilla_cfg1.clone());
  179. (sinsemilla_cfg1, merkle_cfg1)
  180. };
  181. let (_sinsemilla_cfg2, merkle_cfg2) = {
  182. let sinsemilla_cfg2 = SinsemillaChip::configure(
  183. meta,
  184. advices[5..].try_into().unwrap(),
  185. advices[7],
  186. lagrange_coeffs[1],
  187. lookup,
  188. range_check,
  189. );
  190. let merkle_cfg2 = MerkleChip::configure(meta, sinsemilla_cfg2.clone());
  191. (sinsemilla_cfg2, merkle_cfg2)
  192. };
  193. VmConfig {
  194. primary,
  195. advices,
  196. ecc_config,
  197. merkle_cfg1,
  198. merkle_cfg2,
  199. sinsemilla_cfg1,
  200. _sinsemilla_cfg2,
  201. poseidon_config,
  202. arith_config,
  203. }
  204. }
  205. fn synthesize(
  206. &self,
  207. config: Self::Config,
  208. mut layouter: impl Layouter<pallas::Base>,
  209. ) -> std::result::Result<(), plonk::Error> {
  210. debug!("Entering synthesize()");
  211. // Our stack which holds everything we reference.
  212. let mut stack: Vec<StackVar> = vec![];
  213. // Offset for public inputs
  214. let mut public_inputs_offset = 0;
  215. // Load the Sinsemilla generator lookup table used by the whole circuit.
  216. SinsemillaChip::load(config.sinsemilla_cfg1.clone(), &mut layouter)?;
  217. // Construct the ECC chip.
  218. let ecc_chip = config.ecc_chip();
  219. // Construct the Arithmetic chip.
  220. let arith_chip = config.arithmetic_chip();
  221. // This constant one is used for short multiplication
  222. let one = assign_free_advice(
  223. layouter.namespace(|| "Load constant one"),
  224. config.advices[0],
  225. Value::known(pallas::Base::one()),
  226. )?;
  227. // Lookup and push the constants onto the stack
  228. for constant in &self.constants {
  229. debug!("Pushing constant `{}` to stack index {}", constant.as_str(), stack.len());
  230. match constant.as_str() {
  231. "VALUE_COMMIT_VALUE" => {
  232. let vcv = ValueCommitV;
  233. let vcv = FixedPointShort::from_inner(ecc_chip.clone(), vcv);
  234. stack.push(StackVar::EcFixedPointShort(vcv));
  235. }
  236. "VALUE_COMMIT_RANDOM" => {
  237. let vcr = OrchardFixedBasesFull::ValueCommitR;
  238. let vcr = FixedPoint::from_inner(ecc_chip.clone(), vcr);
  239. stack.push(StackVar::EcFixedPoint(vcr));
  240. }
  241. "NULLIFIER_K" => {
  242. let nfk = NullifierK;
  243. let nfk = FixedPointBaseField::from_inner(ecc_chip.clone(), nfk);
  244. stack.push(StackVar::EcFixedPointBase(nfk));
  245. }
  246. _ => unimplemented!(),
  247. }
  248. }
  249. // Push the witnesses onto the stack, and potentially, if the witness
  250. // is in the Base field (like the entire circuit is), load it into a
  251. // table cell.
  252. for witness in &self.witnesses {
  253. match witness {
  254. Witness::EcPoint(w) => {
  255. debug!("Witnessing EcPoint into circuit");
  256. let point = Point::new(
  257. ecc_chip.clone(),
  258. layouter.namespace(|| "Witness EcPoint"),
  259. w.as_ref().map(|cm| cm.to_affine()),
  260. )?;
  261. debug!("Pushing EcPoint to stack index {}", stack.len());
  262. stack.push(StackVar::EcPoint(point));
  263. }
  264. Witness::EcFixedPoint(_) => {
  265. unimplemented!()
  266. }
  267. Witness::Base(w) => {
  268. debug!("Witnessing Base into circuit");
  269. let base = assign_free_advice(
  270. layouter.namespace(|| "Witness Base"),
  271. config.advices[0],
  272. *w,
  273. )?;
  274. debug!("Pushing Base to stack index {}", stack.len());
  275. stack.push(StackVar::Base(base));
  276. }
  277. Witness::Scalar(w) => {
  278. debug!("Pushing Scalar to stack index {}", stack.len());
  279. stack.push(StackVar::Scalar(*w));
  280. }
  281. Witness::MerklePath(w) => {
  282. debug!("Witnessing MerklePath into circuit");
  283. let path: Value<[pallas::Base; MERKLE_DEPTH_ORCHARD]> =
  284. w.map(|typed_path| gen_const_array(|i| typed_path[i].inner()));
  285. debug!("Pushing MerklePath to stack index {}", stack.len());
  286. stack.push(StackVar::MerklePath(path));
  287. }
  288. Witness::Uint32(w) => {
  289. debug!("Pushing Uint32 to stack index {}", stack.len());
  290. stack.push(StackVar::Uint32(*w));
  291. }
  292. Witness::Uint64(w) => {
  293. debug!("Pushing Uint64 to stack index {}", stack.len());
  294. stack.push(StackVar::Uint64(*w));
  295. }
  296. }
  297. }
  298. // And now, work through opcodes
  299. for opcode in &self.opcodes {
  300. match opcode.0 {
  301. Opcode::EcAdd => {
  302. debug!("Executing `EcAdd{:?}` opcode", opcode.1);
  303. let args = &opcode.1;
  304. let lhs: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  305. stack[args[0]].clone().into();
  306. let rhs: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  307. stack[args[1]].clone().into();
  308. let ret = lhs.add(layouter.namespace(|| "EcAdd()"), &rhs)?;
  309. debug!("Pushing result to stack index {}", stack.len());
  310. stack.push(StackVar::EcPoint(ret));
  311. }
  312. Opcode::EcMul => {
  313. debug!("Executing `EcMul{:?}` opcode", opcode.1);
  314. let args = &opcode.1;
  315. let lhs: FixedPoint<pallas::Affine, EccChip<OrchardFixedBases>> =
  316. stack[args[1]].clone().into();
  317. let rhs = ScalarFixed::new(
  318. ecc_chip.clone(),
  319. layouter.namespace(|| "EcMul: ScalarFixed::new()"),
  320. stack[args[0]].clone().into(),
  321. )?;
  322. let (ret, _) = lhs.mul(layouter.namespace(|| "EcMul()"), rhs)?;
  323. debug!("Pushing result to stack index {}", stack.len());
  324. stack.push(StackVar::EcPoint(ret));
  325. }
  326. Opcode::EcMulBase => {
  327. debug!("Executing `EcMulBase{:?}` opcode", opcode.1);
  328. let args = &opcode.1;
  329. let lhs: FixedPointBaseField<pallas::Affine, EccChip<OrchardFixedBases>> =
  330. stack[args[1]].clone().into();
  331. let rhs: AssignedCell<Fp, Fp> = stack[args[0]].clone().into();
  332. let ret = lhs.mul(layouter.namespace(|| "EcMulBase()"), rhs)?;
  333. debug!("Pushing result to stack index {}", stack.len());
  334. stack.push(StackVar::EcPoint(ret));
  335. }
  336. Opcode::EcMulShort => {
  337. debug!("Executing `EcMulShort{:?}` opcode", opcode.1);
  338. let args = &opcode.1;
  339. let lhs: FixedPointShort<pallas::Affine, EccChip<OrchardFixedBases>> =
  340. stack[args[1]].clone().into();
  341. let rhs = ScalarFixedShort::new(
  342. ecc_chip.clone(),
  343. layouter.namespace(|| "EcMulShort: ScalarFixedShort::new()"),
  344. (stack[args[0]].clone().into(), one.clone()),
  345. )?;
  346. let (ret, _) = lhs.mul(layouter.namespace(|| "EcMulShort()"), rhs)?;
  347. debug!("Pushing result to stack index {}", stack.len());
  348. stack.push(StackVar::EcPoint(ret));
  349. }
  350. Opcode::EcGetX => {
  351. debug!("Executing `EcGetX{:?}` opcode", opcode.1);
  352. let args = &opcode.1;
  353. let point: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  354. stack[args[0]].clone().into();
  355. let ret = point.inner().x();
  356. debug!("Pushing result to stack index {}", stack.len());
  357. stack.push(StackVar::Base(ret));
  358. }
  359. Opcode::EcGetY => {
  360. debug!("Executing `EcGetY{:?}` opcode", opcode.1);
  361. let args = &opcode.1;
  362. let point: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
  363. stack[args[0]].clone().into();
  364. let ret = point.inner().y();
  365. debug!("Pushing result to stack index {}", stack.len());
  366. stack.push(StackVar::Base(ret));
  367. }
  368. Opcode::PoseidonHash => {
  369. debug!("Executing `PoseidonHash{:?}` opcode", opcode.1);
  370. let args = &opcode.1;
  371. let mut poseidon_message: Vec<AssignedCell<Fp, Fp>> =
  372. Vec::with_capacity(args.len());
  373. for idx in args {
  374. poseidon_message.push(stack[*idx].clone().into());
  375. }
  376. macro_rules! poseidon_hash {
  377. ($len:expr, $hasher:ident, $output:ident, $cell:ident) => {
  378. let $hasher = PoseidonHash::<
  379. _,
  380. _,
  381. poseidon::P128Pow5T3,
  382. poseidon::ConstantLength<$len>,
  383. 3,
  384. 2,
  385. >::init(
  386. config.poseidon_chip(),
  387. layouter.namespace(|| "PoseidonHash init"),
  388. )?;
  389. let $output = $hasher.hash(
  390. layouter.namespace(|| "PoseidonHash hash"),
  391. poseidon_message.try_into().unwrap(),
  392. )?;
  393. let $cell: AssignedCell<Fp, Fp> = $output.into();
  394. debug!("Pushing hash to stack index {}", stack.len());
  395. stack.push(StackVar::Base($cell));
  396. };
  397. }
  398. macro_rules! vla {
  399. ($args:ident, $a: ident, $b:ident, $c:ident, $($num:tt)*) => {
  400. match $args.len() {
  401. $($num => {
  402. poseidon_hash!($num, $a, $b, $c);
  403. })*
  404. _ => unimplemented!()
  405. }
  406. };
  407. }
  408. vla!(args, a, b, c, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);
  409. }
  410. Opcode::CalculateMerkleRoot => {
  411. debug!("Executing `CalculateMerkleRoot{:?}` opcode", opcode.1);
  412. let args = &opcode.1;
  413. let leaf_pos = stack[args[0]].clone().into();
  414. let merkle_path = stack[args[1]].clone().into();
  415. let leaf = stack[args[2]].clone().into();
  416. let merkle_inputs = MerklePath::construct(
  417. [config.merkle_chip_1(), config.merkle_chip_2()],
  418. OrchardHashDomains::MerkleCrh,
  419. leaf_pos,
  420. merkle_path,
  421. );
  422. let root = merkle_inputs
  423. .calculate_root(layouter.namespace(|| "CalculateMerkleRoot()"), leaf)?;
  424. debug!("Pushing merkle root to stack index {}", stack.len());
  425. stack.push(StackVar::Base(root));
  426. }
  427. Opcode::BaseAdd => {
  428. debug!("Executing `BaseAdd{:?}` opcode", opcode.1);
  429. let args = &opcode.1;
  430. let lhs = &stack[args[0]].clone().into();
  431. let rhs = &stack[args[1]].clone().into();
  432. let sum = arith_chip.add(layouter.namespace(|| "BaseAdd()"), lhs, rhs)?;
  433. debug!("Pushing sum to stack index {}", stack.len());
  434. stack.push(StackVar::Base(sum));
  435. }
  436. Opcode::BaseMul => {
  437. debug!("Executing `BaseMul{:?}` opcode", opcode.1);
  438. let args = &opcode.1;
  439. let lhs = &stack[args[0]].clone().into();
  440. let rhs = &stack[args[1]].clone().into();
  441. let product = arith_chip.mul(layouter.namespace(|| "BaseMul()"), lhs, rhs)?;
  442. debug!("Pushing product to stack index {}", stack.len());
  443. stack.push(StackVar::Base(product));
  444. }
  445. Opcode::BaseSub => {
  446. debug!("Executing `BaseSub{:?}` opcode", opcode.1);
  447. let args = &opcode.1;
  448. let lhs = &stack[args[0]].clone().into();
  449. let rhs = &stack[args[1]].clone().into();
  450. let difference =
  451. arith_chip.sub(layouter.namespace(|| "BaseSub()"), lhs, rhs)?;
  452. debug!("Pushing difference to stack index {}", stack.len());
  453. stack.push(StackVar::Base(difference));
  454. }
  455. /*
  456. Opcode::GreaterThan => {
  457. debug!("Executing `GreaterThan{:?}` opcode", opcode.1);
  458. let args = &opcode.1;
  459. let lhs: AssignedCell<Fp, Fp> = stack[args[0]].clone().into();
  460. let rhs: AssignedCell<Fp, Fp> = stack[args[1]].clone().into();
  461. eb_chip.decompose(layouter.namespace(|| "lhs range check"), lhs.clone())?;
  462. eb_chip.decompose(layouter.namespace(|| "rhs range check"), rhs.clone())?;
  463. let (helper, greater_than) = gt_chip.greater_than(
  464. layouter.namespace(|| "lhs > rhs"),
  465. lhs.into(),
  466. rhs.into(),
  467. )?;
  468. eb_chip.decompose(layouter.namespace(|| "helper range check"), helper.0)?;
  469. debug!("Pushing comparison result to stack index {}", stack.len());
  470. stack.push(StackVar::Base(greater_than.0));
  471. }
  472. */
  473. Opcode::ConstrainInstance => {
  474. debug!("Executing `ConstrainInstance{:?}` opcode", opcode.1);
  475. let args = &opcode.1;
  476. let var: AssignedCell<Fp, Fp> = stack[args[0]].clone().into();
  477. layouter.constrain_instance(
  478. var.cell(),
  479. config.primary,
  480. public_inputs_offset,
  481. )?;
  482. public_inputs_offset += 1;
  483. }
  484. _ => todo!("Handle gracefully"),
  485. }
  486. }
  487. debug!("Exiting synthesize()");
  488. Ok(())
  489. }
  490. }