vm.rs 19 KB

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