kimchi/circuits/polynomials/poseidon.rs
1//! This module implements the Poseidon constraint polynomials.
2
3//~ The poseidon gate encodes 5 rounds of the poseidon permutation.
4//~ A state is represents by 3 field elements. For example,
5//~ the first state is represented by `(s0, s0, s0)`,
6//~ and the next state, after permutation, is represented by `(s1, s1, s1)`.
7//~
8//~ Below is how we store each state in the register table:
9//~
10//~ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
11//~ |:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|
12//~ | s0 | s0 | s0 | s4 | s4 | s4 | s1 | s1 | s1 | s2 | s2 | s2 | s3 | s3 | s3 |
13//~ | s5 | s5 | s5 | | | | | | | | | | | | |
14//~
15//~ The last state is stored on the next row. This last state is either used:
16//~
17//~ * with another Poseidon gate on that next row, representing the next 5 rounds.
18//~ * or with a Zero gate, and a permutation to use the output elsewhere in the circuit.
19//~ * or with another gate expecting an input of 3 field elements in its first registers.
20//~
21//~ ```admonish
22//~ As some of the poseidon hash variants might not use $5k$ rounds (for some $k$),
23//~ the result of the 4-th round is stored directly after the initial state.
24//~ This makes that state accessible to the permutation.
25//~ ```
26//~
27
28use crate::{
29 circuits::{
30 argument::{Argument, ArgumentEnv, ArgumentType},
31 berkeley_columns::BerkeleyChallengeTerm,
32 expr::{constraints::ExprOps, Cache},
33 gate::{CircuitGate, CurrOrNext, GateType},
34 polynomial::COLUMNS,
35 wires::{GateWires, Wire},
36 },
37 curve::KimchiCurve,
38};
39use ark_ff::{Field, PrimeField};
40use core::{marker::PhantomData, ops::Range};
41use mina_poseidon::{
42 constants::{PlonkSpongeConstantsKimchi, SpongeConstants},
43 poseidon::{sbox, ArithmeticSponge, ArithmeticSpongeParams, Sponge},
44};
45use CurrOrNext::{Curr, Next};
46
47//
48// Constants
49//
50
51/// Width of the sponge
52pub const SPONGE_WIDTH: usize = PlonkSpongeConstantsKimchi::SPONGE_WIDTH;
53
54/// Number of rows
55pub const ROUNDS_PER_ROW: usize = COLUMNS / SPONGE_WIDTH;
56
57/// Number of rounds
58pub const ROUNDS_PER_HASH: usize = PlonkSpongeConstantsKimchi::PERM_ROUNDS_FULL;
59
60/// Number of PLONK rows required to implement Poseidon
61pub const POS_ROWS_PER_HASH: usize = ROUNDS_PER_HASH / ROUNDS_PER_ROW;
62
63/// The order in a row in which we store states before and after permutations
64pub const STATE_ORDER: [usize; ROUNDS_PER_ROW] = [
65 0, // the first state is stored first
66 // we skip the next column for subsequent states
67 2, 3, 4,
68 // we store the last state directly after the first state,
69 // so that it can be used in the permutation argument
70 1,
71];
72
73/// Given a Poseidon round from 0 to 4 (inclusive),
74/// returns the columns (as a range) that are used in this round.
75pub const fn round_to_cols(i: usize) -> Range<usize> {
76 let slot = STATE_ORDER[i];
77 let start = slot * SPONGE_WIDTH;
78 start..(start + SPONGE_WIDTH)
79}
80
81impl<F: PrimeField> CircuitGate<F> {
82 pub fn create_poseidon(
83 wires: GateWires,
84 // Coefficients are passed in in the logical order
85 coeffs: [[F; SPONGE_WIDTH]; ROUNDS_PER_ROW],
86 ) -> Self {
87 let coeffs = coeffs.iter().flatten().copied().collect();
88 CircuitGate::new(GateType::Poseidon, wires, coeffs)
89 }
90
91 /// `create_poseidon_gadget(row, first_and_last_row, round_constants)`
92 /// creates an entire set of constraint for a Poseidon hash.
93 ///
94 /// For that, you need to pass:
95 /// - the index of the first `row`
96 /// - the first and last rows' wires (because they are used in the permutation)
97 /// - the round constants
98 ///
99 /// The function returns a set of gates, as well as the next pointer to the
100 /// circuit (next empty absolute row)
101 pub fn create_poseidon_gadget(
102 // the absolute row in the circuit
103 row: usize,
104 // first and last row of the poseidon circuit (because they are used in the permutation)
105 first_and_last_row: [GateWires; 2],
106 round_constants: &[Vec<F>],
107 ) -> (Vec<Self>, usize) {
108 let mut gates = vec![];
109
110 // create the gates
111 let relative_rows = 0..POS_ROWS_PER_HASH;
112 let last_row = row + POS_ROWS_PER_HASH;
113 let absolute_rows = row..last_row;
114
115 for (abs_row, rel_row) in absolute_rows.zip(relative_rows) {
116 // the 15 wires for this row
117 let wires = if rel_row == 0 {
118 first_and_last_row[0]
119 } else {
120 core::array::from_fn(|col| Wire { col, row: abs_row })
121 };
122
123 // round constant for this row
124 let coeffs = core::array::from_fn(|offset| {
125 let round = rel_row * ROUNDS_PER_ROW + offset;
126 core::array::from_fn(|field_el| round_constants[round][field_el])
127 });
128
129 // create poseidon gate for this row
130 gates.push(CircuitGate::create_poseidon(wires, coeffs));
131 }
132
133 // final (zero) gate that contains the output of poseidon
134 gates.push(CircuitGate::zero(first_and_last_row[1]));
135
136 //
137 (gates, last_row)
138 }
139
140 /// Checks if a witness verifies a poseidon gate
141 ///
142 /// # Errors
143 ///
144 /// Will give error if `self.typ` is not `Poseidon` gate, or `state` does not match after `permutation`.
145 pub fn verify_poseidon<G: KimchiCurve<ScalarField = F>>(
146 &self,
147 row: usize,
148 // TODO(mimoo): we should just pass two rows instead of the whole witness
149 witness: &[Vec<F>; COLUMNS],
150 ) -> Result<(), String> {
151 ensure_eq!(
152 self.typ,
153 GateType::Poseidon,
154 "incorrect gate type (should be poseidon)"
155 );
156
157 // fetch each state in the right order
158 let mut states = vec![];
159 for round in 0..ROUNDS_PER_ROW {
160 let cols = round_to_cols(round);
161 let state: Vec<F> = witness[cols].iter().map(|col| col[row]).collect();
162 states.push(state);
163 }
164 // (last state is in next row)
165 let cols = round_to_cols(0);
166 let next_row = row + 1;
167 let last_state: Vec<F> = witness[cols].iter().map(|col| col[next_row]).collect();
168 states.push(last_state);
169
170 // round constants
171 let rc = self.rc();
172 let mds = &G::sponge_params().mds;
173
174 // for each round, check that the permutation was applied correctly
175 for round in 0..ROUNDS_PER_ROW {
176 for (i, mds_row) in mds.iter().enumerate() {
177 // i-th(new_state) = i-th(rc) + mds(sbox(state))
178 let state = &states[round];
179 let mut new_state = rc[round][i];
180 for (&s, mds) in state.iter().zip(mds_row.iter()) {
181 let sboxed = sbox::<F, PlonkSpongeConstantsKimchi>(s);
182 new_state += sboxed * mds;
183 }
184
185 ensure_eq!(
186 new_state,
187 states[round + 1][i],
188 format!(
189 "poseidon: permutation of state[{}] -> state[{}][{}] is incorrect",
190 round,
191 round + 1,
192 i
193 )
194 );
195 }
196 }
197
198 Ok(())
199 }
200
201 pub fn ps(&self) -> F {
202 if self.typ == GateType::Poseidon {
203 F::one()
204 } else {
205 F::zero()
206 }
207 }
208
209 /// round constant that are relevant for this specific gate
210 pub fn rc(&self) -> [[F; SPONGE_WIDTH]; ROUNDS_PER_ROW] {
211 core::array::from_fn(|round| {
212 core::array::from_fn(|col| {
213 if self.typ == GateType::Poseidon {
214 self.coeffs[SPONGE_WIDTH * round + col]
215 } else {
216 F::zero()
217 }
218 })
219 })
220 }
221}
222
223/// `generate_witness(row, params, witness_cols, input)` uses a sponge initialized with
224/// `params` to generate a witness for starting at row `row` in `witness_cols`,
225/// and with input `input`.
226///
227/// # Panics
228///
229/// Will panic if the `circuit` has `INITIAL_ARK`.
230#[allow(clippy::assertions_on_constants)]
231pub fn generate_witness<F: Field>(
232 row: usize,
233 params: &'static ArithmeticSpongeParams<F>,
234 witness_cols: &mut [Vec<F>; COLUMNS],
235 input: [F; SPONGE_WIDTH],
236) {
237 // add the input into the witness
238 witness_cols[0][row] = input[0];
239 witness_cols[1][row] = input[1];
240 witness_cols[2][row] = input[2];
241
242 // set the sponge state
243 let mut sponge = ArithmeticSponge::<F, PlonkSpongeConstantsKimchi>::new(params);
244 sponge.state = input.into();
245
246 // for the poseidon rows
247 for row_idx in 0..POS_ROWS_PER_HASH {
248 let row = row + row_idx;
249 for round in 0..ROUNDS_PER_ROW {
250 // the last round makes use of the next row
251 let maybe_next_row = if round == ROUNDS_PER_ROW - 1 {
252 row + 1
253 } else {
254 row
255 };
256
257 //
258 let abs_round = round + row_idx * ROUNDS_PER_ROW;
259
260 // apply the sponge and record the result in the witness
261 assert!(
262 !PlonkSpongeConstantsKimchi::PERM_INITIAL_ARK,
263 "this won't work if the circuit has an INITIAL_ARK"
264 );
265 sponge.full_round(abs_round);
266
267 // apply the sponge and record the result in the witness
268 let cols_to_update = round_to_cols((round + 1) % ROUNDS_PER_ROW);
269 witness_cols[cols_to_update]
270 .iter_mut()
271 .zip(sponge.state.iter())
272 // update the state (last update is on the next row)
273 .for_each(|(w, s)| w[maybe_next_row] = *s);
274 }
275 }
276}
277
278/// An equation of the form `(curr | next)[i] = round(curr[j])`
279struct RoundEquation {
280 pub source: usize,
281 pub target: (CurrOrNext, usize),
282}
283
284/// For each round, the tuple (row, round) its state permutes to
285const ROUND_EQUATIONS: [RoundEquation; ROUNDS_PER_ROW] = [
286 RoundEquation {
287 source: 0,
288 target: (Curr, 1),
289 },
290 RoundEquation {
291 source: 1,
292 target: (Curr, 2),
293 },
294 RoundEquation {
295 source: 2,
296 target: (Curr, 3),
297 },
298 RoundEquation {
299 source: 3,
300 target: (Curr, 4),
301 },
302 RoundEquation {
303 source: 4,
304 target: (Next, 0),
305 },
306];
307
308/// Implementation of the Poseidon gate
309/// Poseidon quotient poly contribution computation `f^7 + c(x) - f(wx)`
310/// Conjunction of:
311///
312/// ```ignore
313/// curr[round_range(1)] = round(curr[round_range(0)])
314/// curr[round_range(2)] = round(curr[round_range(1)])
315/// curr[round_range(3)] = round(curr[round_range(2)])
316/// curr[round_range(4)] = round(curr[round_range(3)])
317/// next[round_range(0)] = round(curr[round_range(4)])
318///
319/// which expands e.g., to
320/// curr[round_range(1)][0] =
321/// mds[0][0] * sbox(curr[round_range(0)][0])
322/// + mds[0][1] * sbox(curr[round_range(0)][1])
323/// + mds[0][2] * sbox(curr[round_range(0)][2])
324/// + rcm[round_range(1)][0]
325/// curr[round_range(1)][1] =
326/// mds[1][0] * sbox(curr[round_range(0)][0])
327/// + mds[1][1] * sbox(curr[round_range(0)][1])
328/// + mds[1][2] * sbox(curr[round_range(0)][2])
329/// + rcm[round_range(1)][1]
330/// ...
331/// ```
332///
333/// The rth position in this array contains the alphas used for the equations that
334/// constrain the values of the (r+1)th state.
335#[derive(Default)]
336pub struct Poseidon<F>(PhantomData<F>);
337
338impl<F> Poseidon<F> where F: Field {}
339
340impl<F> Argument<F> for Poseidon<F>
341where
342 F: PrimeField,
343{
344 const ARGUMENT_TYPE: ArgumentType = ArgumentType::Gate(GateType::Poseidon);
345 const CONSTRAINTS: u32 = 15;
346
347 fn constraint_checks<T: ExprOps<F, BerkeleyChallengeTerm>>(
348 env: &ArgumentEnv<F, T>,
349 cache: &mut Cache,
350 ) -> Vec<T> {
351 let mut res = vec![];
352
353 let mut idx = 0;
354
355 //~ We define $M_{r, c}$ as the MDS matrix at row $r$ and column $c$.
356 let mds: Vec<Vec<_>> = (0..SPONGE_WIDTH)
357 .map(|row| (0..SPONGE_WIDTH).map(|col| env.mds(row, col)).collect())
358 .collect();
359
360 for e in &ROUND_EQUATIONS {
361 let &RoundEquation {
362 source,
363 target: (target_row, target_round),
364 } = e;
365 //~
366 //~ We define the S-box operation as $w^S$ for $S$ the `SPONGE_BOX` constant.
367 let sboxed: Vec<_> = round_to_cols(source)
368 .map(|i| {
369 cache.cache(
370 env.witness_curr(i)
371 .pow(u64::from(PlonkSpongeConstantsKimchi::PERM_SBOX)),
372 )
373 })
374 .collect();
375
376 for (j, col) in round_to_cols(target_round).enumerate() {
377 //~
378 //~ We store the 15 round constants $r_i$ required for the 5 rounds (3 per round) in the coefficient table:
379 //~
380 //~ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
381 //~ |:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|
382 //~ | r0 | r1 | r2 | r3 | r4 | r5 | r6 | r7 | r8 | r9 | r10 | r11 | r12 | r13 | r14 |
383 let rc = env.coeff(idx);
384
385 idx += 1;
386
387 //~
388 //~ The initial state, stored in the first three registers, are not constrained.
389 //~ The following 4 states (of 3 field elements), including 1 in the next row,
390 //~ are constrained to represent the 5 rounds of permutation.
391 //~ Each of the associated 15 registers is associated to a constraint, calculated as:
392 //~
393 //~ first round:
394 //~
395 //~ * $w_6 - \left(r_0 + (M_{0, 0} w_0^S + M_{0, 1} w_1^S + M_{0, 2} w_2^S)\right)$
396 //~ * $w_7 - \left(r_1 + (M_{1, 0} w_0^S + M_{1, 1} w_1^S + M_{1, 2} w_2^S)\right)$
397 //~ * $w_8 - \left(r_2 + (M_{2, 0} w_0^S + M_{2, 1} w_1^S + M_{2, 2} w_2^S)\right)$
398 //~
399 //~ second round:
400 //~
401 //~ * $w_9 - \left(r_3 + (M_{0, 0} w_6^S + M_{0, 1} w_7^S + M_{0, 2} w_8^S)\right)$
402 //~ * $w_{10} - \left(r_4 + (M_{1, 0} w_6^S + M_{1, 1} w_7^S + M_{1, 2} w_8^S)\right)$
403 //~ * $w_{11} - \left(r_5 + (M_{2, 0} w_6^S + M_{2, 1} w_7^S + M_{2, 2} w_8^S)\right)$
404 //~
405 //~ third round:
406 //~
407 //~ * $w_{12} - \left(r_6 + (M_{0, 0} w_9^S + M_{0, 1} w_{10}^S + M_{0, 2} w_{11}^S)\right)$
408 //~ * $w_{13} - \left(r_7 + (M_{1, 0} w_9^S + M_{1, 1} w_{10}^S + M_{1, 2} w_{11}^S)\right)$
409 //~ * $w_{14} - \left(r_8 + (M_{2, 0} w_9^S + M_{2, 1} w_{10}^S + M_{2, 2} w_{11}^S)\right)$
410 //~
411 //~ fourth round:
412 //~
413 //~ * $w_3 - \left(r_9 + (M_{0, 0} w_{12}^S + M_{0, 1} w_{13}^S + M_{0, 2} w_{14}^S)\right)$
414 //~ * $w_4 - \left(r_{10} + (M_{1, 0} w_{12}^S + M_{1, 1} w_{13}^S + M_{1, 2} w_{14}^S)\right)$
415 //~ * $w_5 - \left(r_{11} + (M_{2, 0} w_{12}^S + M_{2, 1} w_{13}^S + M_{2, 2} w_{14}^S)\right)$
416 //~
417 //~ fifth round:
418 //~
419 //~ * $w_{0, next} - \left(r_{12} + (M_{0, 0} w_3^S + M_{0, 1} w_4^S + M_{0, 2} w_5^S)\right)$
420 //~ * $w_{1, next} - \left(r_{13} + (M_{1, 0} w_3^S + M_{1, 1} w_4^S + M_{1, 2} w_5^S)\right)$
421 //~ * $w_{2, next} - \left(r_{14} + (M_{2, 0} w_3^S + M_{2, 1} w_4^S + M_{2, 2} w_5^S)\right)$
422 //~
423 //~ where $w_{i, next}$ is the polynomial $w_i(\omega x)$ which points to the next row.
424 let constraint = env.witness(target_row, col)
425 - sboxed
426 .iter()
427 .zip(mds[j].iter())
428 .fold(rc, |acc, (x, c)| acc + c.clone() * x.clone());
429 res.push(constraint);
430 }
431 }
432 res
433 }
434}