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, RATE_RANGE, RATE_WIDTH, STATE_WIDTH,
6 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 a 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 128-bits.
62 const COLLISION_RESISTANCE: u32 = 128;
63
64 type Digest = RpxDigest;
65
66 fn hash(bytes: &[u8]) -> Self::Digest {
67 // initialize the state with zeroes
68 let mut state = [ZERO; STATE_WIDTH];
69
70 // determine the number of field elements needed to encode `bytes` when each field element
71 // represents at most 7 bytes.
72 let num_field_elem = bytes.len().div_ceil(BINARY_CHUNK_SIZE);
73
74 // set the first capacity element to `RATE_WIDTH + (num_field_elem % RATE_WIDTH)`. We do
75 // this to achieve:
76 // 1. Domain separating hashing of `[u8]` from hashing of `[Felt]`.
77 // 2. Avoiding collisions at the `[Felt]` representation of the encoded bytes.
78 state[CAPACITY_RANGE.start] =
79 Felt::from((RATE_WIDTH + (num_field_elem % RATE_WIDTH)) as u8);
80
81 // initialize a buffer to receive the little-endian elements.
82 let mut buf = [0_u8; 8];
83
84 // iterate the chunks of bytes, creating a field element from each chunk and copying it
85 // into the state.
86 //
87 // every time the rate range is filled, a permutation is performed. if the final value of
88 // `i` is not zero, then the chunks count wasn't enough to fill the state range, and an
89 // additional permutation must be performed.
90 let i = bytes.chunks(BINARY_CHUNK_SIZE).fold(0, |i, chunk| {
91 // we always pad `bytes` with a 1 followed by as many 0's to fill up `buf`.
92 if i != num_field_elem - 1 {
93 buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
94 } else {
95 buf.fill(0);
96 buf[..chunk.len()].copy_from_slice(chunk);
97 buf[chunk.len()] = 1;
98 }
99
100 // set the current rate element to the input. since we take at most 7 bytes, we are
101 // guaranteed that the inputs data will fit into a single field element.
102 state[RATE_RANGE.start + i] = Felt::new(u64::from_le_bytes(buf));
103
104 // proceed filling the range. if it's full, then we apply a permutation and reset the
105 // counter to the beginning of the range.
106 if i == RATE_WIDTH - 1 {
107 Self::apply_permutation(&mut state);
108 0
109 } else {
110 i + 1
111 }
112 });
113
114 // if we absorbed some elements but didn't apply a permutation to them (would happen when
115 // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation. we
116 // don't need to apply any extra padding because the first capacity element contains a
117 // flag indicating the number of field elements constituting the last block when the latter
118 // is not divisible by `RATE_WIDTH`.
119 if i != 0 {
120 state[RATE_RANGE.start + i..RATE_RANGE.end].fill(ZERO);
121 Self::apply_permutation(&mut state);
122 }
123
124 // return the first 4 elements of the rate as hash result.
125 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
126 }
127
128 fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
129 // initialize the state by copying the digest elements into the rate portion of the state
130 // (8 total elements), and set the capacity elements to 0.
131 let mut state = [ZERO; STATE_WIDTH];
132 let it = Self::Digest::digests_as_elements(values.iter());
133 for (i, v) in it.enumerate() {
134 state[RATE_RANGE.start + i] = *v;
135 }
136
137 // apply the RPX permutation and return the first four elements of the state
138 Self::apply_permutation(&mut state);
139 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
140 }
141
142 fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
143 // initialize the state as follows:
144 // - seed is copied into the first 4 elements of the rate portion of the state.
145 // - if the value fits into a single field element, copy it into the fifth rate element and
146 // set the first capacity element to 5.
147 // - if the value doesn't fit into a single field element, split it into two field
148 // elements, copy them into rate elements 5 and 6 and set the first capacity element to 6.
149 let mut state = [ZERO; STATE_WIDTH];
150 state[INPUT1_RANGE].copy_from_slice(seed.as_elements());
151 state[INPUT2_RANGE.start] = Felt::new(value);
152 if value < Felt::MODULUS {
153 state[CAPACITY_RANGE.start] = Felt::from(5_u8);
154 } else {
155 state[INPUT2_RANGE.start + 1] = Felt::new(value / Felt::MODULUS);
156 state[CAPACITY_RANGE.start] = Felt::from(6_u8);
157 }
158
159 // apply the RPX permutation and return the first four elements of the state
160 Self::apply_permutation(&mut state);
161 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
162 }
163}
164
165impl ElementHasher for Rpx256 {
166 type BaseField = Felt;
167
168 fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
169 // convert the elements into a list of base field elements
170 let elements = E::slice_as_base_elements(elements);
171
172 // initialize state to all zeros, except for the first element of the capacity part, which
173 // is set to `elements.len() % RATE_WIDTH`.
174 let mut state = [ZERO; STATE_WIDTH];
175 state[CAPACITY_RANGE.start] = Self::BaseField::from((elements.len() % RATE_WIDTH) as u8);
176
177 // absorb elements into the state one by one until the rate portion of the state is filled
178 // up; then apply the Rescue permutation and start absorbing again; repeat until all
179 // elements have been absorbed
180 let mut i = 0;
181 for &element in elements.iter() {
182 state[RATE_RANGE.start + i] = element;
183 i += 1;
184 if i % RATE_WIDTH == 0 {
185 Self::apply_permutation(&mut state);
186 i = 0;
187 }
188 }
189
190 // if we absorbed some elements but didn't apply a permutation to them (would happen when
191 // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation after
192 // padding by as many 0 as necessary to make the input length a multiple of the RATE_WIDTH.
193 if i > 0 {
194 while i != RATE_WIDTH {
195 state[RATE_RANGE.start + i] = ZERO;
196 i += 1;
197 }
198 Self::apply_permutation(&mut state);
199 }
200
201 // return the first 4 elements of the state as hash result
202 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
203 }
204}
205
206// HASH FUNCTION IMPLEMENTATION
207// ================================================================================================
208
209impl Rpx256 {
210 // CONSTANTS
211 // --------------------------------------------------------------------------------------------
212
213 /// Sponge state is set to 12 field elements or 768 bytes; 8 elements are reserved for rate and
214 /// the remaining 4 elements are reserved for capacity.
215 pub const STATE_WIDTH: usize = STATE_WIDTH;
216
217 /// The rate portion of the state is located in elements 4 through 11 (inclusive).
218 pub const RATE_RANGE: Range<usize> = RATE_RANGE;
219
220 /// The capacity portion of the state is located in elements 0, 1, 2, and 3.
221 pub const CAPACITY_RANGE: Range<usize> = CAPACITY_RANGE;
222
223 /// The output of the hash function can be read from state elements 4, 5, 6, and 7.
224 pub const DIGEST_RANGE: Range<usize> = DIGEST_RANGE;
225
226 /// MDS matrix used for computing the linear layer in the (FB) and (E) rounds.
227 pub const MDS: [[Felt; STATE_WIDTH]; STATE_WIDTH] = MDS;
228
229 /// Round constants added to the hasher state in the first half of the round.
230 pub const ARK1: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK1;
231
232 /// Round constants added to the hasher state in the second half of the round.
233 pub const ARK2: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK2;
234
235 // TRAIT PASS-THROUGH FUNCTIONS
236 // --------------------------------------------------------------------------------------------
237
238 /// Returns a hash of the provided sequence of bytes.
239 #[inline(always)]
240 pub fn hash(bytes: &[u8]) -> RpxDigest {
241 <Self as Hasher>::hash(bytes)
242 }
243
244 /// Returns a hash of two digests. This method is intended for use in construction of
245 /// Merkle trees and verification of Merkle paths.
246 #[inline(always)]
247 pub fn merge(values: &[RpxDigest; 2]) -> RpxDigest {
248 <Self as Hasher>::merge(values)
249 }
250
251 /// Returns a hash of the provided field elements.
252 #[inline(always)]
253 pub fn hash_elements<E: FieldElement<BaseField = Felt>>(elements: &[E]) -> RpxDigest {
254 <Self as ElementHasher>::hash_elements(elements)
255 }
256
257 // DOMAIN IDENTIFIER
258 // --------------------------------------------------------------------------------------------
259
260 /// Returns a hash of two digests and a domain identifier.
261 pub fn merge_in_domain(values: &[RpxDigest; 2], domain: Felt) -> RpxDigest {
262 // initialize the state by copying the digest elements into the rate portion of the state
263 // (8 total elements), and set the capacity elements to 0.
264 let mut state = [ZERO; STATE_WIDTH];
265 let it = RpxDigest::digests_as_elements(values.iter());
266 for (i, v) in it.enumerate() {
267 state[RATE_RANGE.start + i] = *v;
268 }
269
270 // set the second capacity element to the domain value. The first capacity element is used
271 // for padding purposes.
272 state[CAPACITY_RANGE.start + 1] = domain;
273
274 // apply the RPX permutation and return the first four elements of the state
275 Self::apply_permutation(&mut state);
276 RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
277 }
278
279 // RPX PERMUTATION
280 // --------------------------------------------------------------------------------------------
281
282 /// Applies RPX permutation to the provided state.
283 #[inline(always)]
284 pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
285 Self::apply_fb_round(state, 0);
286 Self::apply_ext_round(state, 1);
287 Self::apply_fb_round(state, 2);
288 Self::apply_ext_round(state, 3);
289 Self::apply_fb_round(state, 4);
290 Self::apply_ext_round(state, 5);
291 Self::apply_final_round(state, 6);
292 }
293
294 // RPX PERMUTATION ROUND FUNCTIONS
295 // --------------------------------------------------------------------------------------------
296
297 /// (FB) round function.
298 #[inline(always)]
299 pub fn apply_fb_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
300 apply_mds(state);
301 if !add_constants_and_apply_sbox(state, &ARK1[round]) {
302 add_constants(state, &ARK1[round]);
303 apply_sbox(state);
304 }
305
306 apply_mds(state);
307 if !add_constants_and_apply_inv_sbox(state, &ARK2[round]) {
308 add_constants(state, &ARK2[round]);
309 apply_inv_sbox(state);
310 }
311 }
312
313 /// (E) round function.
314 #[inline(always)]
315 pub fn apply_ext_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
316 // add constants
317 add_constants(state, &ARK1[round]);
318
319 // decompose the state into 4 elements in the cubic extension field and apply the power 7
320 // map to each of the elements
321 let [s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11] = *state;
322 let ext0 = Self::exp7(CubicExtElement::new(s0, s1, s2));
323 let ext1 = Self::exp7(CubicExtElement::new(s3, s4, s5));
324 let ext2 = Self::exp7(CubicExtElement::new(s6, s7, s8));
325 let ext3 = Self::exp7(CubicExtElement::new(s9, s10, s11));
326
327 // decompose the state back into 12 base field elements
328 let arr_ext = [ext0, ext1, ext2, ext3];
329 *state = CubicExtElement::slice_as_base_elements(&arr_ext)
330 .try_into()
331 .expect("shouldn't fail");
332 }
333
334 /// (M) round function.
335 #[inline(always)]
336 pub fn apply_final_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
337 apply_mds(state);
338 add_constants(state, &ARK1[round]);
339 }
340
341 /// Computes an exponentiation to the power 7 in cubic extension field.
342 #[inline(always)]
343 pub fn exp7(x: CubeExtension<Felt>) -> CubeExtension<Felt> {
344 let x2 = x.square();
345 let x4 = x2.square();
346
347 let x3 = x2 * x;
348 x3 * x4
349 }
350}