miden-crypto/src/hash/rescue/rpx/mod.rs
src/hash/rescue/rpx/mod.rsRaw
1use super::{
2 add_constants, add_constants_and_apply_inv_sbox, add_constants_and_apply_sbox, apply_inv_sbox,
3 apply_mds, apply_sbox, CubeExtension, Digest, ElementHasher, Felt, FieldElement, Hasher,
4 StarkField, ARK1, ARK2, BINARY_CHUNK_SIZE, CAPACITY_RANGE, DIGEST_BYTES, DIGEST_RANGE,
5 DIGEST_SIZE, INPUT1_RANGE, INPUT2_RANGE, MDS, NUM_ROUNDS, ONE, RATE_RANGE, RATE_WIDTH,
6 STATE_WIDTH, ZERO,
7};
8use core::{convert::TryInto, ops::Range};
9
10mod digest;
11pub use digest::RpxDigest;
12
13pub type CubicExtElement = CubeExtension<Felt>;
14
15// HASHER IMPLEMENTATION
16// ================================================================================================
17
18/// Implementation of the Rescue Prime eXtension hash function with 256-bit output.
19///
20/// The hash function is based on the XHash12 construction in [specifications](https://eprint.iacr.org/2023/1045)
21///
22/// The parameters used to instantiate the function are:
23/// * Field: 64-bit prime field with modulus 2^64 - 2^32 + 1.
24/// * State width: 12 field elements.
25/// * Capacity size: 4 field elements.
26/// * S-Box degree: 7.
27/// * Rounds: There are 3 different types of rounds:
28/// - (FB): `apply_mds` → `add_constants` → `apply_sbox` → `apply_mds` → `add_constants` → `apply_inv_sbox`.
29/// - (E): `add_constants` → `ext_sbox` (which is raising to power 7 in the degree 3 extension field).
30/// - (M): `apply_mds` → `add_constants`.
31/// * Permutation: (FB) (E) (FB) (E) (FB) (E) (M).
32///
33/// The above parameters target 128-bit security level. The digest consists of four field elements
34/// and it can be serialized into 32 bytes (256 bits).
35///
36/// ## Hash output consistency
37/// Functions [hash_elements()](Rpx256::hash_elements), [merge()](Rpx256::merge), and
38/// [merge_with_int()](Rpx256::merge_with_int) are internally consistent. That is, computing
39/// a hash for the same set of elements using these functions will always produce the same
40/// result. For example, merging two digests using [merge()](Rpx256::merge) will produce the
41/// same result as hashing 8 elements which make up these digests using
42/// [hash_elements()](Rpx256::hash_elements) function.
43///
44/// However, [hash()](Rpx256::hash) function is not consistent with functions mentioned above.
45/// For example, if we take two field elements, serialize them to bytes and hash them using
46/// [hash()](Rpx256::hash), the result will differ from the result obtained by hashing these
47/// elements directly using [hash_elements()](Rpx256::hash_elements) function. The reason for
48/// this difference is that [hash()](Rpx256::hash) function needs to be able to handle
49/// arbitrary binary strings, which may or may not encode valid field elements - and thus,
50/// deserialization procedure used by this function is different from the procedure used to
51/// deserialize valid field elements.
52///
53/// Thus, if the underlying data consists of valid field elements, it might make more sense
54/// to deserialize them into field elements and then hash them using
55/// [hash_elements()](Rpx256::hash_elements) function rather then hashing the serialized bytes
56/// using [hash()](Rpx256::hash) function.
57#[derive(Debug, Copy, Clone, Eq, PartialEq)]
58pub struct Rpx256();
59
60impl Hasher for Rpx256 {
61 /// Rpx256 collision resistance is the same as the security level, that is 128-bits.
62 ///
63 /// #### Collision resistance
64 ///
65 /// However, our setup of the capacity registers might drop it to 126.
66 ///
67 /// Related issue: [#69](https://github.com/0xPolygonMiden/crypto/issues/69)
68 const COLLISION_RESISTANCE: u32 = 128;
69
70 type Digest = RpxDigest;
71
72 fn hash(bytes: &[u8]) -> Self::Digest {
73 // initialize the state with zeroes
74 let mut state = [ZERO; STATE_WIDTH];
75
76 // set the capacity (first element) to a flag on whether or not the input length is evenly
77 // divided by the rate. this will prevent collisions between padded and non-padded inputs,
78 // and will rule out the need to perform an extra permutation in case of evenly divided
79 // inputs.
80 let is_rate_multiple = bytes.len() % RATE_WIDTH == 0;
81 if !is_rate_multiple {
82 state[CAPACITY_RANGE.start] = ONE;
83 }
84
85 // initialize a buffer to receive the little-endian elements.
86 let mut buf = [0_u8; 8];
87
88 // iterate the chunks of bytes, creating a field element from each chunk and copying it
89 // into the state.
90 //
91 // every time the rate range is filled, a permutation is performed. if the final value of
92 // `i` is not zero, then the chunks count wasn't enough to fill the state range, and an
93 // additional permutation must be performed.
94 let i = bytes.chunks(BINARY_CHUNK_SIZE).fold(0, |i, chunk| {
95 // the last element of the iteration may or may not be a full chunk. if it's not, then
96 // we need to pad the remainder bytes of the chunk with zeroes, separated by a `1`.
97 // this will avoid collisions.
98 if chunk.len() == BINARY_CHUNK_SIZE {
99 buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
100 } else {
101 buf.fill(0);
102 buf[..chunk.len()].copy_from_slice(chunk);
103 buf[chunk.len()] = 1;
104 }
105
106 // set the current rate element to the input. since we take at most 7 bytes, we are
107 // guaranteed that the inputs data will fit into a single field element.
108 state[RATE_RANGE.start + i] = Felt::new(u64::from_le_bytes(buf));
109
110 // proceed filling the range. if it's full, then we apply a permutation and reset the
111 // counter to the beginning of the range.
112 if i == RATE_WIDTH - 1 {
113 Self::apply_permutation(&mut state);
114 0
115 } else {
116 i + 1
117 }
118 });
119
120 // if we absorbed some elements but didn't apply a permutation to them (would happen when
121 // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation. we
122 // don't need to apply any extra padding because the first capacity element contains a
123 // flag indicating whether the input is evenly divisible by the rate.
124 if i != 0 {
125 state[RATE_RANGE.start + i..RATE_RANGE.end].fill(ZERO);
126 state[RATE_RANGE.start + i] = ONE;
127 Self::apply_permutation(&mut state);
128 }
129
130 // return the first 4 elements of the rate as hash result.
131 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
132 }
133
134 fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
135 // initialize the state by copying the digest elements into the rate portion of the state
136 // (8 total elements), and set the capacity elements to 0.
137 let mut state = [ZERO; STATE_WIDTH];
138 let it = Self::Digest::digests_as_elements(values.iter());
139 for (i, v) in it.enumerate() {
140 state[RATE_RANGE.start + i] = *v;
141 }
142
143 // apply the RPX permutation and return the first four elements of the state
144 Self::apply_permutation(&mut state);
145 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
146 }
147
148 fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
149 // initialize the state as follows:
150 // - seed is copied into the first 4 elements of the rate portion of the state.
151 // - if the value fits into a single field element, copy it into the fifth rate element
152 // and set the sixth rate element to 1.
153 // - if the value doesn't fit into a single field element, split it into two field
154 // elements, copy them into rate elements 5 and 6, and set the seventh rate element
155 // to 1.
156 // - set the first capacity element to 1
157 let mut state = [ZERO; STATE_WIDTH];
158 state[INPUT1_RANGE].copy_from_slice(seed.as_elements());
159 state[INPUT2_RANGE.start] = Felt::new(value);
160 if value < Felt::MODULUS {
161 state[INPUT2_RANGE.start + 1] = ONE;
162 } else {
163 state[INPUT2_RANGE.start + 1] = Felt::new(value / Felt::MODULUS);
164 state[INPUT2_RANGE.start + 2] = ONE;
165 }
166
167 // common padding for both cases
168 state[CAPACITY_RANGE.start] = ONE;
169
170 // apply the RPX permutation and return the first four elements of the state
171 Self::apply_permutation(&mut state);
172 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
173 }
174}
175
176impl ElementHasher for Rpx256 {
177 type BaseField = Felt;
178
179 fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
180 // convert the elements into a list of base field elements
181 let elements = E::slice_as_base_elements(elements);
182
183 // initialize state to all zeros, except for the first element of the capacity part, which
184 // is set to 1 if the number of elements is not a multiple of RATE_WIDTH.
185 let mut state = [ZERO; STATE_WIDTH];
186 if elements.len() % RATE_WIDTH != 0 {
187 state[CAPACITY_RANGE.start] = ONE;
188 }
189
190 // absorb elements into the state one by one until the rate portion of the state is filled
191 // up; then apply the Rescue permutation and start absorbing again; repeat until all
192 // elements have been absorbed
193 let mut i = 0;
194 for &element in elements.iter() {
195 state[RATE_RANGE.start + i] = element;
196 i += 1;
197 if i % RATE_WIDTH == 0 {
198 Self::apply_permutation(&mut state);
199 i = 0;
200 }
201 }
202
203 // if we absorbed some elements but didn't apply a permutation to them (would happen when
204 // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation after
205 // padding by appending a 1 followed by as many 0 as necessary to make the input length a
206 // multiple of the RATE_WIDTH.
207 if i > 0 {
208 state[RATE_RANGE.start + i] = ONE;
209 i += 1;
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}