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