miden_crypto/hash/algebraic_sponge/poseidon2/mod.rs
1use once_cell::sync::Lazy;
2use p3_goldilocks::Goldilocks;
3use p3_symmetric::Permutation;
4
5use super::{
6 AlgebraicSponge, CAPACITY_RANGE, DIGEST_RANGE, Felt, RATE_RANGE, RATE0_RANGE, RATE1_RANGE,
7 Range, STATE_WIDTH, Word,
8};
9use crate::{
10 ZERO,
11 hash::algebraic_sponge::poseidon2::constants::{
12 ARK_EXT_INITIAL, ARK_EXT_TERMINAL, ARK_INT, MAT_DIAG,
13 },
14};
15
16mod constants;
17use constants::{NUM_EXTERNAL_ROUNDS_HALF, NUM_INTERNAL_ROUNDS};
18
19#[cfg(test)]
20mod test;
21
22static P3_POSEIDON2: Lazy<p3_goldilocks::Poseidon2Goldilocks<12>> =
23 Lazy::new(p3_goldilocks::default_goldilocks_poseidon2_12);
24
25/// Applies Plonky3's optimized Poseidon2 permutation to a `[Felt; 12]` state.
26///
27/// `Felt` is `#[repr(transparent)]` over `Goldilocks`, so the transmute is safe.
28/// A process-global lazy static holds the permutation so round constants are not reallocated on
29/// every call (including `no_std`, via `once_cell` and the `critical-section` crate).
30#[inline(always)]
31fn p3_permute(state: &mut [Felt; STATE_WIDTH]) {
32 // SAFETY: Felt is #[repr(transparent)] over Goldilocks.
33 let gl_state =
34 unsafe { &mut *(state as *mut [Felt; STATE_WIDTH] as *mut [Goldilocks; STATE_WIDTH]) };
35
36 P3_POSEIDON2.permute_mut(gl_state);
37}
38
39/// Implementation of the Poseidon2 hash function with 256-bit output.
40///
41/// The permutation is delegated to Plonky3's optimized `Poseidon2Goldilocks<12>`, which provides
42/// hardware-accelerated implementations on aarch64 (NEON inline assembly) and an optimized generic
43/// implementation on other architectures. The internal MDS diagonal uses small special values
44/// (-2, 1, 2, 1/2, 3, 4, ...) that enable multiplication via shifts and halves rather than full
45/// field multiplications.
46///
47/// The parameters used to instantiate the function are:
48/// * Field: 64-bit prime field with modulus 2^64 - 2^32 + 1.
49/// * State width: 12 field elements.
50/// * Capacity size: 4 field elements.
51/// * S-Box degree: 7.
52/// * Rounds: There are 2 different types of rounds, called internal and external, and are
53/// structured as follows:
54/// - Initial External rounds (IE): `add_constants` → `apply_sbox` → `apply_matmul_external`.
55/// - Internal rounds: `add_constants` → `apply_sbox` → `apply_matmul_internal`, where the constant
56/// addition and sbox application apply only to the first entry of the state.
57/// - Terminal External rounds (TE): `add_constants` → `apply_sbox` → `apply_matmul_external`.
58/// - An additional `apply_matmul_external` is inserted at the beginning in order to protect against
59/// some recent attacks.
60///
61/// The above parameters target a 128-bit security level. The digest consists of four field elements
62/// and it can be serialized into 32 bytes (256 bits).
63///
64/// ## Hash output consistency
65/// Functions [hash_elements()](Poseidon2::hash_elements), and [merge()](Poseidon2::merge), are
66/// internally consistent. That is, computing a hash for the same set of elements using these
67/// functions will always produce the same result. For example, merging two digests using
68/// [merge()](Poseidon2::merge) will produce the same result as hashing 8 elements which make up
69/// these digests using [hash_elements()](Poseidon2::hash_elements) function.
70///
71/// However, [hash()](Poseidon2::hash) function is not consistent with functions mentioned above.
72/// For example, if we take two field elements, serialize them to bytes and hash them using
73/// [hash()](Poseidon2::hash), the result will differ from the result obtained by hashing these
74/// elements directly using [hash_elements()](Poseidon2::hash_elements) function. The reason for
75/// this difference is that [hash()](Poseidon2::hash) function needs to be able to handle
76/// arbitrary binary strings, which may or may not encode valid field elements - and thus,
77/// deserialization procedure used by this function is different from the procedure used to
78/// deserialize valid field elements.
79///
80/// Thus, if the underlying data consists of valid field elements, it might make more sense
81/// to deserialize them into field elements and then hash them using
82/// [hash_elements()](Poseidon2::hash_elements) function rather than hashing the serialized bytes
83/// using [hash()](Poseidon2::hash) function.
84///
85/// ## Domain separation
86/// [merge_in_domain()](Poseidon2::merge_in_domain) hashes two digests into one digest with some
87/// domain identifier and the current implementation sets the second capacity element to the value
88/// of this domain identifier. Using a similar argument to the one formulated for domain separation
89/// in Appendix C of the [specifications](https://eprint.iacr.org/2023/1045), one sees that doing
90/// so degrades only pre-image resistance, from its initial bound of c.log_2(p), by as much as
91/// the log_2 of the size of the domain identifier space. Since pre-image resistance becomes
92/// the bottleneck for the security bound of the sponge in overwrite-mode only when it is
93/// lower than 2^128, we see that the target 128-bit security level is maintained as long as
94/// the size of the domain identifier space, including for padding, is less than 2^128.
95///
96/// ## Hashing of empty input
97/// The current implementation hashes empty input to the zero digest [0, 0, 0, 0]. This has
98/// the benefit of requiring no calls to the Poseidon2 permutation when hashing empty input.
99#[allow(rustdoc::private_intra_doc_links)]
100#[derive(Debug, Copy, Clone, Eq, PartialEq)]
101pub struct Poseidon2();
102
103impl AlgebraicSponge for Poseidon2 {
104 fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
105 p3_permute(state);
106 }
107}
108
109impl Poseidon2 {
110 // CONSTANTS
111 // --------------------------------------------------------------------------------------------
112
113 /// Target collision resistance level in bits.
114 pub const COLLISION_RESISTANCE: u32 = 128;
115
116 /// Number of initial or terminal external rounds.
117 pub const NUM_EXTERNAL_ROUNDS_HALF: usize = NUM_EXTERNAL_ROUNDS_HALF;
118 /// Number of internal rounds.
119 pub const NUM_INTERNAL_ROUNDS: usize = NUM_INTERNAL_ROUNDS;
120
121 /// Sponge state is set to 12 field elements or 768 bytes; 8 elements are reserved for the
122 /// rate and the remaining 4 elements are reserved for the capacity.
123 pub const STATE_WIDTH: usize = STATE_WIDTH;
124
125 /// The rate portion of the state is located in elements 0 through 7 (inclusive).
126 pub const RATE_RANGE: Range<usize> = RATE_RANGE;
127
128 /// The first 4-element word of the rate portion.
129 pub const RATE0_RANGE: Range<usize> = RATE0_RANGE;
130
131 /// The second 4-element word of the rate portion.
132 pub const RATE1_RANGE: Range<usize> = RATE1_RANGE;
133
134 /// The capacity portion of the state is located in elements 8, 9, 10, and 11.
135 pub const CAPACITY_RANGE: Range<usize> = CAPACITY_RANGE;
136
137 /// The output of the hash function can be read from state elements 0, 1, 2, and 3 (the first
138 /// word of the state).
139 pub const DIGEST_RANGE: Range<usize> = DIGEST_RANGE;
140
141 /// Matrix used for computing the linear layers of internal rounds.
142 pub const MAT_DIAG: [Felt; STATE_WIDTH] = MAT_DIAG;
143
144 /// Round constants added to the hasher state.
145 pub const ARK_EXT_INITIAL: [[Felt; STATE_WIDTH]; NUM_EXTERNAL_ROUNDS_HALF] = ARK_EXT_INITIAL;
146 pub const ARK_EXT_TERMINAL: [[Felt; STATE_WIDTH]; NUM_EXTERNAL_ROUNDS_HALF] = ARK_EXT_TERMINAL;
147 pub const ARK_INT: [Felt; NUM_INTERNAL_ROUNDS] = ARK_INT;
148
149 // HASH FUNCTIONS
150 // --------------------------------------------------------------------------------------------
151
152 /// Returns a hash of the provided sequence of bytes.
153 #[inline(always)]
154 pub fn hash(bytes: &[u8]) -> Word {
155 <Self as AlgebraicSponge>::hash(bytes)
156 }
157
158 /// Applies the Poseidon2 permutation to the provided state in-place.
159 #[inline(always)]
160 pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
161 <Self as AlgebraicSponge>::apply_permutation(state);
162 }
163
164 /// Returns a hash of the provided field elements.
165 #[inline(always)]
166 pub fn hash_elements<E: BasedVectorSpace<Felt>>(elements: &[E]) -> Word {
167 <Self as AlgebraicSponge>::hash_elements(elements)
168 }
169
170 /// Returns a hash of two digests. This method is intended for use in construction of
171 /// Merkle trees and verification of Merkle paths.
172 #[inline(always)]
173 pub fn merge(values: &[Word; 2]) -> Word {
174 <Self as AlgebraicSponge>::merge(values)
175 }
176
177 /// Returns a hash of multiple digests.
178 #[inline(always)]
179 pub fn merge_many(values: &[Word]) -> Word {
180 <Self as AlgebraicSponge>::merge_many(values)
181 }
182
183 /// Returns a hash of two digests and a domain identifier.
184 #[inline(always)]
185 pub fn merge_in_domain(values: &[Word; 2], domain: Felt) -> Word {
186 <Self as AlgebraicSponge>::merge_in_domain(values, domain)
187 }
188
189 /// Returns a hash of the provided `elements` and a domain identifier.
190 #[inline(always)]
191 pub fn hash_elements_in_domain<E: BasedVectorSpace<Felt>>(
192 elements: &[E],
193 domain: Felt,
194 ) -> Word {
195 <Self as AlgebraicSponge>::hash_elements_in_domain(elements, domain)
196 }
197
198 // POSEIDON2 PERMUTATION
199 // --------------------------------------------------------------------------------------------
200
201 /// Applies the M_E (external) linear layer to the state in-place.
202 ///
203 /// This basically takes any 4 x 4 MDS matrix M and computes the matrix-vector product with
204 /// the matrix defined by `[[2M, M, ..., M], [M, 2M, ..., M], ..., [M, M, ..., 2M]]`.
205 ///
206 /// Given the structure of the above matrix, we can compute the product of the state with
207 /// matrix `[M, M, ..., M]` and compute the final result using a few addition.
208 #[inline(always)]
209 pub fn apply_matmul_external(state: &mut [Felt; STATE_WIDTH]) {
210 // multiply the state by `[M, M, ..., M]` block-wise
211 Self::matmul_m4(state);
212
213 // accumulate column-wise sums
214 let number_blocks = STATE_WIDTH / 4;
215 let mut stored = [ZERO; 4];
216 for j in 0..number_blocks {
217 let base = j * 4;
218 for l in 0..4 {
219 stored[l] += state[base + l];
220 }
221 }
222
223 // add stored column-sums to each element
224 for (i, val) in state.iter_mut().enumerate() {
225 *val += stored[i % 4];
226 }
227 }
228
229 /// Multiply a 4-element vector x by:
230 /// [ 2 3 1 1 ]
231 /// [ 1 2 3 1 ]
232 /// [ 1 1 2 3 ]
233 /// [ 3 1 1 2 ].
234 #[inline(always)]
235 fn matmul_m4(state: &mut [Felt; STATE_WIDTH]) {
236 const N_CHUNKS: usize = STATE_WIDTH / 4;
237
238 for i in 0..N_CHUNKS {
239 let base = i * 4;
240 let x = &mut state[base..base + 4];
241
242 let t01 = x[0] + x[1];
243 let t23 = x[2] + x[3];
244 let t0123 = t01 + t23;
245 let t01123 = t0123 + x[1];
246 let t01233 = t0123 + x[3];
247
248 // The order here is important. Need to overwrite x[0] and x[2] after x[1] and x[3].
249 x[3] = t01233 + x[0].double(); // 3*x[0] + x[1] + x[2] + 2*x[3]
250 x[1] = t01123 + x[2].double(); // x[0] + 2*x[1] + 3*x[2] + x[3]
251 x[0] = t01123 + t01; // 2*x[0] + 3*x[1] + x[2] + x[3]
252 x[2] = t01233 + t23; // x[0] + x[1] + 2*x[2] + 3*x[3]
253 }
254 }
255
256 /// Applies the M_I (internal) linear layer to the state in-place.
257 ///
258 /// The matrix is given by its diagonal entries with the remaining entries set equal to 1.
259 /// Hence, given the sum of the state entries, the matrix-vector product is computed using
260 /// a multiply-and-add per state entry.
261 #[inline(always)]
262 pub fn matmul_internal(state: &mut [Felt; STATE_WIDTH], mat_diag: [Felt; 12]) {
263 let mut sum = ZERO;
264 for s in state.iter().take(STATE_WIDTH) {
265 sum += *s
266 }
267
268 for i in 0..state.len() {
269 state[i] = state[i] * mat_diag[i] + sum;
270 }
271 }
272
273 /// Adds the round constants to the state in-place.
274 #[inline(always)]
275 pub fn add_rc(state: &mut [Felt; STATE_WIDTH], ark: &[Felt; 12]) {
276 state.iter_mut().zip(ark).for_each(|(s, &k)| *s += k);
277 }
278
279 /// Applies the S-box (x^7) to each element of the state in-place.
280 #[inline(always)]
281 pub fn apply_sbox(state: &mut [Felt; STATE_WIDTH]) {
282 state[0] = state[0].exp_const_u64::<7>();
283 state[1] = state[1].exp_const_u64::<7>();
284 state[2] = state[2].exp_const_u64::<7>();
285 state[3] = state[3].exp_const_u64::<7>();
286 state[4] = state[4].exp_const_u64::<7>();
287 state[5] = state[5].exp_const_u64::<7>();
288 state[6] = state[6].exp_const_u64::<7>();
289 state[7] = state[7].exp_const_u64::<7>();
290 state[8] = state[8].exp_const_u64::<7>();
291 state[9] = state[9].exp_const_u64::<7>();
292 state[10] = state[10].exp_const_u64::<7>();
293 state[11] = state[11].exp_const_u64::<7>();
294 }
295}
296
297// PLONKY3 INTEGRATION
298// ================================================================================================
299
300use p3_challenger::DuplexChallenger;
301use p3_symmetric::{CryptographicPermutation, PaddingFreeSponge, TruncatedPermutation};
302
303use crate::field::BasedVectorSpace;
304
305/// Plonky3-compatible Poseidon2 permutation.
306///
307/// This zero-sized wrapper delegates to Plonky3's optimized `Poseidon2Goldilocks<12>` and
308/// implements the `Permutation` and `CryptographicPermutation` traits.
309///
310/// The permutation operates on a state of 12 field elements (STATE_WIDTH = 12), with:
311/// - Rate: 8 elements (positions 0-7)
312/// - Capacity: 4 elements (positions 8-11)
313/// - Digest output: 4 elements (positions 0-3)
314#[derive(Debug, Copy, Clone, Eq, PartialEq)]
315pub struct Poseidon2Permutation256;
316
317impl Poseidon2Permutation256 {
318 // CONSTANTS
319 // --------------------------------------------------------------------------------------------
320
321 /// Number of initial or terminal external rounds.
322 pub const NUM_EXTERNAL_ROUNDS_HALF: usize = Poseidon2::NUM_EXTERNAL_ROUNDS_HALF;
323
324 /// Number of internal rounds.
325 pub const NUM_INTERNAL_ROUNDS: usize = Poseidon2::NUM_INTERNAL_ROUNDS;
326
327 /// Sponge state is set to 12 field elements or 768 bytes; 8 elements are reserved for rate and
328 /// the remaining 4 elements are reserved for capacity.
329 pub const STATE_WIDTH: usize = STATE_WIDTH;
330
331 /// The rate portion of the state is located in elements 0 through 7 (inclusive).
332 pub const RATE_RANGE: Range<usize> = Poseidon2::RATE_RANGE;
333
334 /// The capacity portion of the state is located in elements 8, 9, 10, and 11.
335 pub const CAPACITY_RANGE: Range<usize> = Poseidon2::CAPACITY_RANGE;
336
337 /// The output of the hash function can be read from state elements 0, 1, 2, and 3.
338 pub const DIGEST_RANGE: Range<usize> = Poseidon2::DIGEST_RANGE;
339
340 // POSEIDON2 PERMUTATION
341 // --------------------------------------------------------------------------------------------
342
343 /// Applies Poseidon2 permutation to the provided state.
344 ///
345 /// This delegates to the Poseidon2 implementation.
346 #[inline(always)]
347 pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
348 Poseidon2::apply_permutation(state);
349 }
350}
351
352// PLONKY3 TRAIT IMPLEMENTATIONS
353// ================================================================================================
354
355impl Permutation<[Felt; STATE_WIDTH]> for Poseidon2Permutation256 {
356 fn permute_mut(&self, state: &mut [Felt; STATE_WIDTH]) {
357 p3_permute(state);
358 }
359}
360
361impl CryptographicPermutation<[Felt; STATE_WIDTH]> for Poseidon2Permutation256 {}
362
363// TYPE ALIASES FOR PLONKY3 INTEGRATION
364// ================================================================================================
365
366/// Poseidon2-based hasher using Plonky3's PaddingFreeSponge.
367///
368/// This provides a sponge-based hash function with:
369/// - WIDTH: 12 field elements (total state size)
370/// - RATE: 8 field elements (input/output rate)
371/// - OUT: 4 field elements (digest size)
372pub type Poseidon2Hasher = PaddingFreeSponge<Poseidon2Permutation256, 12, 8, 4>;
373
374/// Poseidon2-based compression function using Plonky3's TruncatedPermutation.
375///
376/// This provides a 2-to-1 compression function for Merkle tree construction with:
377/// - CHUNK: 2 (number of input chunks - i.e., 2 digests of 4 elements each = 8 elements)
378/// - N: 4 (output size in field elements)
379/// - WIDTH: 12 (total state size)
380///
381/// The compression function takes 8 field elements (2 digests) as input and produces
382/// 4 field elements (1 digest) as output.
383pub type Poseidon2Compression = TruncatedPermutation<Poseidon2Permutation256, 2, 4, 12>;
384
385/// Poseidon2-based challenger using Plonky3's DuplexChallenger.
386///
387/// This provides a Fiat-Shamir transform implementation for interactive proof protocols,
388/// with:
389/// - F: Generic field type (typically the same as Felt)
390/// - WIDTH: 12 field elements (sponge state size)
391/// - RATE: 8 field elements (rate of absorption/squeezing)
392pub type Poseidon2Challenger<F> = DuplexChallenger<F, Poseidon2Permutation256, 12, 8>;