miden-crypto/src/hash/rescue/rpx/mod.rs
src/hash/rescue/rpx/mod.rsRaw
1use core::ops::Range;
2
3use super::{
4 add_constants, add_constants_and_apply_inv_sbox, add_constants_and_apply_sbox, apply_inv_sbox,
5 apply_mds, apply_sbox, CubeExtension, Digest, ElementHasher, Felt, FieldElement, Hasher,
6 StarkField, ARK1, ARK2, BINARY_CHUNK_SIZE, CAPACITY_RANGE, DIGEST_BYTES, DIGEST_RANGE,
7 DIGEST_SIZE, INPUT1_RANGE, INPUT2_RANGE, MDS, NUM_ROUNDS, RATE_RANGE, RATE_WIDTH, STATE_WIDTH,
8 ZERO,
9};
10
11mod digest;
12pub use digest::{RpxDigest, RpxDigestError};
13
14#[cfg(test)]
15mod tests;
16
17pub type CubicExtElement = CubeExtension<Felt>;
18
19// HASHER IMPLEMENTATION
20// ================================================================================================
21
22/// Implementation of the Rescue Prime eXtension hash function with 256-bit output.
23///
24/// The hash function is based on the XHash12 construction in [specifications](https://eprint.iacr.org/2023/1045)
25///
26/// The parameters used to instantiate the function are:
27/// * Field: 64-bit prime field with modulus 2^64 - 2^32 + 1.
28/// * State width: 12 field elements.
29/// * Capacity size: 4 field elements.
30/// * S-Box degree: 7.
31/// * Rounds: There are 3 different types of rounds:
32/// - (FB): `apply_mds` → `add_constants` → `apply_sbox` → `apply_mds` → `add_constants` →
33/// `apply_inv_sbox`.
34/// - (E): `add_constants` → `ext_sbox` (which is raising to power 7 in the degree 3 extension
35/// field).
36/// - (M): `apply_mds` → `add_constants`.
37/// * Permutation: (FB) (E) (FB) (E) (FB) (E) (M).
38///
39/// The above parameters target a 128-bit security level. The digest consists of four field elements
40/// and it can be serialized into 32 bytes (256 bits).
41///
42/// ## Hash output consistency
43/// Functions [hash_elements()](Rpx256::hash_elements), [merge()](Rpx256::merge), and
44/// [merge_with_int()](Rpx256::merge_with_int) are internally consistent. That is, computing
45/// a hash for the same set of elements using these functions will always produce the same
46/// result. For example, merging two digests using [merge()](Rpx256::merge) will produce the
47/// same result as hashing 8 elements which make up these digests using
48/// [hash_elements()](Rpx256::hash_elements) function.
49///
50/// However, [hash()](Rpx256::hash) function is not consistent with functions mentioned above.
51/// For example, if we take two field elements, serialize them to bytes and hash them using
52/// [hash()](Rpx256::hash), the result will differ from the result obtained by hashing these
53/// elements directly using [hash_elements()](Rpx256::hash_elements) function. The reason for
54/// this difference is that [hash()](Rpx256::hash) function needs to be able to handle
55/// arbitrary binary strings, which may or may not encode valid field elements - and thus,
56/// deserialization procedure used by this function is different from the procedure used to
57/// deserialize valid field elements.
58///
59/// Thus, if the underlying data consists of valid field elements, it might make more sense
60/// to deserialize them into field elements and then hash them using
61/// [hash_elements()](Rpx256::hash_elements) function rather than hashing the serialized bytes
62/// using [hash()](Rpx256::hash) function.
63///
64/// ## Domain separation
65/// [merge_in_domain()](Rpx256::merge_in_domain) hashes two digests into one digest with some domain
66/// identifier and the current implementation sets the second capacity element to the value of
67/// this domain identifier. Using a similar argument to the one formulated for domain separation
68/// in Appendix C of the [specifications](https://eprint.iacr.org/2023/1045), one sees that doing
69/// so degrades only pre-image resistance, from its initial bound of c.log_2(p), by as much as
70/// the log_2 of the size of the domain identifier space. Since pre-image resistance becomes
71/// the bottleneck for the security bound of the sponge in overwrite-mode only when it is
72/// lower than 2^128, we see that the target 128-bit security level is maintained as long as
73/// the size of the domain identifier space, including for padding, is less than 2^128.
74///
75/// ## Hashing of empty input
76/// The current implementation hashes empty input to the zero digest [0, 0, 0, 0]. This has
77/// the benefit of requiring no calls to the RPX permutation when hashing empty input.
78#[derive(Debug, Copy, Clone, Eq, PartialEq)]
79pub struct Rpx256();
80
81impl Hasher for Rpx256 {
82 /// Rpx256 collision resistance is 128-bits.
83 const COLLISION_RESISTANCE: u32 = 128;
84
85 type Digest = RpxDigest;
86
87 fn hash(bytes: &[u8]) -> Self::Digest {
88 // initialize the state with zeroes
89 let mut state = [ZERO; STATE_WIDTH];
90
91 // determine the number of field elements needed to encode `bytes` when each field element
92 // represents at most 7 bytes.
93 let num_field_elem = bytes.len().div_ceil(BINARY_CHUNK_SIZE);
94
95 // set the first capacity element to `RATE_WIDTH + (num_field_elem % RATE_WIDTH)`. We do
96 // this to achieve:
97 // 1. Domain separating hashing of `[u8]` from hashing of `[Felt]`.
98 // 2. Avoiding collisions at the `[Felt]` representation of the encoded bytes.
99 state[CAPACITY_RANGE.start] =
100 Felt::from((RATE_WIDTH + (num_field_elem % RATE_WIDTH)) as u8);
101
102 // initialize a buffer to receive the little-endian elements.
103 let mut buf = [0_u8; 8];
104
105 // iterate the chunks of bytes, creating a field element from each chunk and copying it
106 // into the state.
107 //
108 // every time the rate range is filled, a permutation is performed. if the final value of
109 // `rate_pos` is not zero, then the chunks count wasn't enough to fill the state range,
110 // and an additional permutation must be performed.
111 let mut current_chunk_idx = 0_usize;
112 // handle the case of an empty `bytes`
113 let last_chunk_idx = if num_field_elem == 0 {
114 current_chunk_idx
115 } else {
116 num_field_elem - 1
117 };
118 let rate_pos = bytes.chunks(BINARY_CHUNK_SIZE).fold(0, |rate_pos, chunk| {
119 // copy the chunk into the buffer
120 if current_chunk_idx != last_chunk_idx {
121 buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
122 } else {
123 // on the last iteration, we pad `buf` with a 1 followed by as many 0's as are
124 // needed to fill it
125 buf.fill(0);
126 buf[..chunk.len()].copy_from_slice(chunk);
127 buf[chunk.len()] = 1;
128 }
129 current_chunk_idx += 1;
130
131 // set the current rate element to the input. since we take at most 7 bytes, we are
132 // guaranteed that the inputs data will fit into a single field element.
133 state[RATE_RANGE.start + rate_pos] = Felt::new(u64::from_le_bytes(buf));
134
135 // proceed filling the range. if it's full, then we apply a permutation and reset the
136 // counter to the beginning of the range.
137 if rate_pos == RATE_WIDTH - 1 {
138 Self::apply_permutation(&mut state);
139 0
140 } else {
141 rate_pos + 1
142 }
143 });
144
145 // if we absorbed some elements but didn't apply a permutation to them (would happen when
146 // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation. we
147 // don't need to apply any extra padding because the first capacity element contains a
148 // flag indicating the number of field elements constituting the last block when the latter
149 // is not divisible by `RATE_WIDTH`.
150 if rate_pos != 0 {
151 state[RATE_RANGE.start + rate_pos..RATE_RANGE.end].fill(ZERO);
152 Self::apply_permutation(&mut state);
153 }
154
155 // return the first 4 elements of the rate as hash result.
156 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
157 }
158
159 fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
160 // initialize the state by copying the digest elements into the rate portion of the state
161 // (8 total elements), and set the capacity elements to 0.
162 let mut state = [ZERO; STATE_WIDTH];
163 let it = Self::Digest::digests_as_elements(values.iter());
164 for (i, v) in it.enumerate() {
165 state[RATE_RANGE.start + i] = *v;
166 }
167
168 // apply the RPX permutation and return the first four elements of the state
169 Self::apply_permutation(&mut state);
170 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
171 }
172
173 fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
174 // initialize the state as follows:
175 // - seed is copied into the first 4 elements of the rate portion of the state.
176 // - if the value fits into a single field element, copy it into the fifth rate element and
177 // set the first capacity element to 5.
178 // - if the value doesn't fit into a single field element, split it into two field elements,
179 // copy them into rate elements 5 and 6 and set the first capacity element to 6.
180 let mut state = [ZERO; STATE_WIDTH];
181 state[INPUT1_RANGE].copy_from_slice(seed.as_elements());
182 state[INPUT2_RANGE.start] = Felt::new(value);
183 if value < Felt::MODULUS {
184 state[CAPACITY_RANGE.start] = Felt::from(5_u8);
185 } else {
186 state[INPUT2_RANGE.start + 1] = Felt::new(value / Felt::MODULUS);
187 state[CAPACITY_RANGE.start] = Felt::from(6_u8);
188 }
189
190 // apply the RPX permutation and return the first four elements of the rate
191 Self::apply_permutation(&mut state);
192 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
193 }
194}
195
196impl ElementHasher for Rpx256 {
197 type BaseField = Felt;
198
199 fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
200 // convert the elements into a list of base field elements
201 let elements = E::slice_as_base_elements(elements);
202
203 // initialize state to all zeros, except for the first element of the capacity part, which
204 // is set to `elements.len() % RATE_WIDTH`.
205 let mut state = [ZERO; STATE_WIDTH];
206 state[CAPACITY_RANGE.start] = Self::BaseField::from((elements.len() % RATE_WIDTH) as u8);
207
208 // absorb elements into the state one by one until the rate portion of the state is filled
209 // up; then apply the Rescue permutation and start absorbing again; repeat until all
210 // elements have been absorbed
211 let mut i = 0;
212 for &element in elements.iter() {
213 state[RATE_RANGE.start + i] = element;
214 i += 1;
215 if i % RATE_WIDTH == 0 {
216 Self::apply_permutation(&mut state);
217 i = 0;
218 }
219 }
220
221 // if we absorbed some elements but didn't apply a permutation to them (would happen when
222 // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation after
223 // padding by as many 0 as necessary to make the input length a multiple of the RATE_WIDTH.
224 if i > 0 {
225 while i != RATE_WIDTH {
226 state[RATE_RANGE.start + i] = ZERO;
227 i += 1;
228 }
229 Self::apply_permutation(&mut state);
230 }
231
232 // return the first 4 elements of the state as hash result
233 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
234 }
235}
236
237// HASH FUNCTION IMPLEMENTATION
238// ================================================================================================
239
240impl Rpx256 {
241 // CONSTANTS
242 // --------------------------------------------------------------------------------------------
243
244 /// Sponge state is set to 12 field elements or 768 bytes; 8 elements are reserved for rate and
245 /// the remaining 4 elements are reserved for capacity.
246 pub const STATE_WIDTH: usize = STATE_WIDTH;
247
248 /// The rate portion of the state is located in elements 4 through 11 (inclusive).
249 pub const RATE_RANGE: Range<usize> = RATE_RANGE;
250
251 /// The capacity portion of the state is located in elements 0, 1, 2, and 3.
252 pub const CAPACITY_RANGE: Range<usize> = CAPACITY_RANGE;
253
254 /// The output of the hash function can be read from state elements 4, 5, 6, and 7.
255 pub const DIGEST_RANGE: Range<usize> = DIGEST_RANGE;
256
257 /// MDS matrix used for computing the linear layer in the (FB) and (E) rounds.
258 pub const MDS: [[Felt; STATE_WIDTH]; STATE_WIDTH] = MDS;
259
260 /// Round constants added to the hasher state in the first half of the round.
261 pub const ARK1: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK1;
262
263 /// Round constants added to the hasher state in the second half of the round.
264 pub const ARK2: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK2;
265
266 // TRAIT PASS-THROUGH FUNCTIONS
267 // --------------------------------------------------------------------------------------------
268
269 /// Returns a hash of the provided sequence of bytes.
270 #[inline(always)]
271 pub fn hash(bytes: &[u8]) -> RpxDigest {
272 <Self as Hasher>::hash(bytes)
273 }
274
275 /// Returns a hash of two digests. This method is intended for use in construction of
276 /// Merkle trees and verification of Merkle paths.
277 #[inline(always)]
278 pub fn merge(values: &[RpxDigest; 2]) -> RpxDigest {
279 <Self as Hasher>::merge(values)
280 }
281
282 /// Returns a hash of the provided field elements.
283 #[inline(always)]
284 pub fn hash_elements<E: FieldElement<BaseField = Felt>>(elements: &[E]) -> RpxDigest {
285 <Self as ElementHasher>::hash_elements(elements)
286 }
287
288 // DOMAIN IDENTIFIER
289 // --------------------------------------------------------------------------------------------
290
291 /// Returns a hash of two digests and a domain identifier.
292 pub fn merge_in_domain(values: &[RpxDigest; 2], domain: Felt) -> RpxDigest {
293 // initialize the state by copying the digest elements into the rate portion of the state
294 // (8 total elements), and set the capacity elements to 0.
295 let mut state = [ZERO; STATE_WIDTH];
296 let it = RpxDigest::digests_as_elements(values.iter());
297 for (i, v) in it.enumerate() {
298 state[RATE_RANGE.start + i] = *v;
299 }
300
301 // set the second capacity element to the domain value. The first capacity element is used
302 // for padding purposes.
303 state[CAPACITY_RANGE.start + 1] = domain;
304
305 // apply the RPX permutation and return the first four elements of the state
306 Self::apply_permutation(&mut state);
307 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
308 }
309
310 // RPX PERMUTATION
311 // --------------------------------------------------------------------------------------------
312
313 /// Applies RPX permutation to the provided state.
314 #[inline(always)]
315 pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
316 Self::apply_fb_round(state, 0);
317 Self::apply_ext_round(state, 1);
318 Self::apply_fb_round(state, 2);
319 Self::apply_ext_round(state, 3);
320 Self::apply_fb_round(state, 4);
321 Self::apply_ext_round(state, 5);
322 Self::apply_final_round(state, 6);
323 }
324
325 // RPX PERMUTATION ROUND FUNCTIONS
326 // --------------------------------------------------------------------------------------------
327
328 /// (FB) round function.
329 #[inline(always)]
330 pub fn apply_fb_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
331 apply_mds(state);
332 if !add_constants_and_apply_sbox(state, &ARK1[round]) {
333 add_constants(state, &ARK1[round]);
334 apply_sbox(state);
335 }
336
337 apply_mds(state);
338 if !add_constants_and_apply_inv_sbox(state, &ARK2[round]) {
339 add_constants(state, &ARK2[round]);
340 apply_inv_sbox(state);
341 }
342 }
343
344 /// (E) round function.
345 #[inline(always)]
346 pub fn apply_ext_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
347 // add constants
348 add_constants(state, &ARK1[round]);
349
350 // decompose the state into 4 elements in the cubic extension field and apply the power 7
351 // map to each of the elements
352 let [s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11] = *state;
353 let ext0 = Self::exp7(CubicExtElement::new(s0, s1, s2));
354 let ext1 = Self::exp7(CubicExtElement::new(s3, s4, s5));
355 let ext2 = Self::exp7(CubicExtElement::new(s6, s7, s8));
356 let ext3 = Self::exp7(CubicExtElement::new(s9, s10, s11));
357
358 // decompose the state back into 12 base field elements
359 let arr_ext = [ext0, ext1, ext2, ext3];
360 *state = CubicExtElement::slice_as_base_elements(&arr_ext)
361 .try_into()
362 .expect("shouldn't fail");
363 }
364
365 /// (M) round function.
366 #[inline(always)]
367 pub fn apply_final_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
368 apply_mds(state);
369 add_constants(state, &ARK1[round]);
370 }
371
372 /// Computes an exponentiation to the power 7 in cubic extension field.
373 #[inline(always)]
374 pub fn exp7(x: CubeExtension<Felt>) -> CubeExtension<Felt> {
375 let x2 = x.square();
376 let x4 = x2.square();
377
378 let x3 = x2 * x;
379 x3 * x4
380 }
381}