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