poseidon_add.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. use std::time::Instant;
  2. use halo2::{
  3. circuit::{Layouter, SimpleFloorPlanner},
  4. dev::MockProver,
  5. plonk::{
  6. Advice, Circuit, Column, ConstraintSystem, Error, Instance as InstanceColumn, Selector,
  7. },
  8. poly::Rotation,
  9. };
  10. use halo2_gadgets::{
  11. poseidon::{Hash as PoseidonHash, Pow5T3Chip as PoseidonChip, Pow5T3Config as PoseidonConfig},
  12. primitives,
  13. primitives::poseidon::{ConstantLength, P128Pow5T3},
  14. utilities::{copy, CellValue, UtilitiesInstructions, Var},
  15. };
  16. use pasta_curves::pallas;
  17. use drk_halo2::proof::{Proof, ProvingKey, VerifyingKey};
  18. #[derive(Clone, Debug)]
  19. struct Config {
  20. primary: Column<InstanceColumn>,
  21. q_add: Selector,
  22. advices: [Column<Advice>; 10],
  23. poseidon_config: PoseidonConfig<pallas::Base>,
  24. }
  25. impl Config {
  26. fn poseidon_chip(&self) -> PoseidonChip<pallas::Base> {
  27. PoseidonChip::construct(self.poseidon_config.clone())
  28. }
  29. }
  30. #[derive(Default, Debug)]
  31. struct HashCircuit {
  32. a: Option<pallas::Base>,
  33. b: Option<pallas::Base>,
  34. c: Option<pallas::Base>,
  35. }
  36. impl UtilitiesInstructions<pallas::Base> for HashCircuit {
  37. type Var = CellValue<pallas::Base>;
  38. }
  39. impl Circuit<pallas::Base> for HashCircuit {
  40. type Config = Config;
  41. type FloorPlanner = SimpleFloorPlanner;
  42. fn without_witnesses(&self) -> Self {
  43. Self::default()
  44. }
  45. fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
  46. // Advice columns used in the circuit
  47. let advices = [
  48. meta.advice_column(),
  49. meta.advice_column(),
  50. meta.advice_column(),
  51. meta.advice_column(),
  52. meta.advice_column(),
  53. meta.advice_column(),
  54. meta.advice_column(),
  55. meta.advice_column(),
  56. meta.advice_column(),
  57. meta.advice_column(),
  58. ];
  59. // Addition of two field elements
  60. let q_add = meta.selector();
  61. meta.create_gate("poseidon_hash(a, b) + c", |meta| {
  62. let q_add = meta.query_selector(q_add);
  63. let sum = meta.query_advice(advices[6], Rotation::cur());
  64. let hash = meta.query_advice(advices[7], Rotation::cur());
  65. let c = meta.query_advice(advices[8], Rotation::cur());
  66. vec![q_add * (hash + c - sum)]
  67. });
  68. // Instance column used for public inputs
  69. let primary = meta.instance_column();
  70. meta.enable_equality(primary.into());
  71. // Permutation over all advice columns
  72. for advice in advices.iter() {
  73. meta.enable_equality((*advice).into());
  74. }
  75. // Poseidon requires four advice columns, while ECC incomplete addition
  76. // requires six. We can reduce the proof size by sharing fixed columns
  77. // between the ECC and Poseidon chips.
  78. // TODO: For multiple invocations they could/should be configured in
  79. // parallel rather than sharing perhaps?
  80. let lagrange_coeffs = [
  81. meta.fixed_column(),
  82. meta.fixed_column(),
  83. meta.fixed_column(),
  84. meta.fixed_column(),
  85. meta.fixed_column(),
  86. meta.fixed_column(),
  87. meta.fixed_column(),
  88. meta.fixed_column(),
  89. ];
  90. let rc_a = lagrange_coeffs[2..5].try_into().unwrap();
  91. let rc_b = lagrange_coeffs[5..8].try_into().unwrap();
  92. // Also use the first Lagrange coefficient column for loading global constants.
  93. meta.enable_constant(lagrange_coeffs[0]);
  94. // Configuration for the Poseidon hash
  95. let poseidon_config = PoseidonChip::configure(
  96. meta,
  97. P128Pow5T3,
  98. advices[6..9].try_into().unwrap(),
  99. advices[5],
  100. rc_a,
  101. rc_b,
  102. );
  103. Config {
  104. primary,
  105. q_add,
  106. advices,
  107. poseidon_config,
  108. }
  109. }
  110. fn synthesize(
  111. &self,
  112. config: Self::Config,
  113. mut layouter: impl Layouter<pallas::Base>,
  114. ) -> Result<(), Error> {
  115. let a = self.load_private(layouter.namespace(|| "load a"), config.advices[0], self.a)?;
  116. let b = self.load_private(layouter.namespace(|| "load b"), config.advices[0], self.b)?;
  117. let c = self.load_private(layouter.namespace(|| "load c"), config.advices[0], self.c)?;
  118. let hash = {
  119. let poseidon_message = [a, b];
  120. let poseidon_hasher = PoseidonHash::<_, _, P128Pow5T3, _, 3, 2>::init(
  121. config.poseidon_chip(),
  122. layouter.namespace(|| "Poseidon init"),
  123. ConstantLength::<2>,
  124. )?;
  125. let poseidon_output = poseidon_hasher.hash(
  126. layouter.namespace(|| "Poseidon hash (a, b)"),
  127. poseidon_message,
  128. )?;
  129. let poseidon_output: CellValue<pallas::Base> = poseidon_output.inner().into();
  130. poseidon_output
  131. };
  132. // Add hash output to c
  133. let scalar = layouter.assign_region(
  134. || " `scalar` = poseidon_hash(a, b) + c",
  135. |mut region| {
  136. config.q_add.enable(&mut region, 0)?;
  137. copy(&mut region, || "copy hash", config.advices[7], 0, &hash)?;
  138. copy(&mut region, || "copy c", config.advices[8], 0, &c)?;
  139. let scalar_val = hash.value().zip(c.value()).map(|(hash, c)| hash + c);
  140. let cell = region.assign_advice(
  141. || "poseidon_hash(a, b) + c",
  142. config.advices[6],
  143. 0,
  144. || scalar_val.ok_or(Error::SynthesisError),
  145. )?;
  146. Ok(CellValue::new(cell, scalar_val))
  147. },
  148. )?;
  149. // Constrain sum to equal the public input
  150. layouter.constrain_instance(scalar.cell(), config.primary, 0)?;
  151. // At this point we've enforced all of our public inputs.
  152. Ok(())
  153. }
  154. }
  155. fn main() {
  156. // The number of rows in our circuit cannot exceed 2^k
  157. let k: u32 = 6;
  158. let a = pallas::Base::from(13);
  159. let b = pallas::Base::from(69);
  160. let c = pallas::Base::from(42);
  161. let message = [a, b];
  162. let output = primitives::poseidon::Hash::init(P128Pow5T3, ConstantLength::<2>).hash(message);
  163. let circuit = HashCircuit {
  164. a: Some(a),
  165. b: Some(b),
  166. c: Some(c),
  167. };
  168. let sum = output + c;
  169. // Incorrect:
  170. let public_inputs = vec![sum + pallas::Base::one()];
  171. let prover = MockProver::run(k, &circuit, vec![public_inputs]).unwrap();
  172. assert!(prover.verify().is_err());
  173. // Correct:
  174. let public_inputs = vec![sum];
  175. let prover = MockProver::run(k, &circuit, vec![public_inputs.clone()]).unwrap();
  176. assert_eq!(prover.verify(), Ok(()));
  177. // Actual ZK proof
  178. let start = Instant::now();
  179. let pk = ProvingKey::build(k, HashCircuit::default());
  180. println!("Setup Prover: [{:?}]", start.elapsed());
  181. let start = Instant::now();
  182. let proof = Proof::create(&pk, &[circuit], &public_inputs).unwrap();
  183. println!("Prove: [{:?}]", start.elapsed());
  184. let start = Instant::now();
  185. let vk = VerifyingKey::build(k, HashCircuit::default());
  186. println!("Setup Verifier: [{:?}]", start.elapsed());
  187. let start = Instant::now();
  188. assert!(proof.verify(&vk, &public_inputs).is_ok());
  189. println!("Verify: [{:?}]", start.elapsed());
  190. }