miden-crypto/src/hash/rescue/rpo/mod.rs
src/hash/rescue/rpo/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, Digest, ElementHasher, Felt, FieldElement, Hasher, StarkField, ARK1,
6 ARK2, BINARY_CHUNK_SIZE, CAPACITY_RANGE, DIGEST_BYTES, DIGEST_RANGE, DIGEST_SIZE, INPUT1_RANGE,
7 INPUT2_RANGE, MDS, NUM_ROUNDS, ONE, RATE_RANGE, RATE_WIDTH, STATE_WIDTH, ZERO,
8};
9
10mod digest;
11pub use digest::RpoDigest;
12
13#[cfg(test)]
14mod tests;
15
16// HASHER IMPLEMENTATION
17// ================================================================================================
18
19/// Implementation of the Rescue Prime Optimized hash function with 256-bit output.
20///
21/// The hash function is implemented according to the Rescue Prime Optimized
22/// [specifications](https://eprint.iacr.org/2022/1577)
23///
24/// The parameters used to instantiate the function are:
25/// * Field: 64-bit prime field with modulus 2^64 - 2^32 + 1.
26/// * State width: 12 field elements.
27/// * Capacity size: 4 field elements.
28/// * Number of founds: 7.
29/// * S-Box degree: 7.
30///
31/// The above parameters target a 128-bit security level. The digest consists of four field elements
32/// and it can be serialized into 32 bytes (256 bits).
33///
34/// ## Hash output consistency
35/// Functions [hash_elements()](Rpo256::hash_elements), [merge()](Rpo256::merge), and
36/// [merge_with_int()](Rpo256::merge_with_int) are internally consistent. That is, computing
37/// a hash for the same set of elements using these functions will always produce the same
38/// result. For example, merging two digests using [merge()](Rpo256::merge) will produce the
39/// same result as hashing 8 elements which make up these digests using
40/// [hash_elements()](Rpo256::hash_elements) function.
41///
42/// However, [hash()](Rpo256::hash) function is not consistent with functions mentioned above.
43/// For example, if we take two field elements, serialize them to bytes and hash them using
44/// [hash()](Rpo256::hash), the result will differ from the result obtained by hashing these
45/// elements directly using [hash_elements()](Rpo256::hash_elements) function. The reason for
46/// this difference is that [hash()](Rpo256::hash) function needs to be able to handle
47/// arbitrary binary strings, which may or may not encode valid field elements - and thus,
48/// deserialization procedure used by this function is different from the procedure used to
49/// deserialize valid field elements.
50///
51/// Thus, if the underlying data consists of valid field elements, it might make more sense
52/// to deserialize them into field elements and then hash them using
53/// [hash_elements()](Rpo256::hash_elements) function rather then hashing the serialized bytes
54/// using [hash()](Rpo256::hash) function.
55#[derive(Debug, Copy, Clone, Eq, PartialEq)]
56pub struct Rpo256();
57
58impl Hasher for Rpo256 {
59 /// Rpo256 collision resistance is 128-bits.
60 const COLLISION_RESISTANCE: u32 = 128;
61
62 type Digest = RpoDigest;
63
64 fn hash(bytes: &[u8]) -> Self::Digest {
65 // initialize the state with zeroes
66 let mut state = [ZERO; STATE_WIDTH];
67
68 // set the capacity (first element) to a flag on whether or not the input length is evenly
69 // divided by the rate. this will prevent collisions between padded and non-padded inputs,
70 // and will rule out the need to perform an extra permutation in case of evenly divided
71 // inputs.
72 let is_rate_multiple = bytes.len() % RATE_WIDTH == 0;
73 if !is_rate_multiple {
74 state[CAPACITY_RANGE.start] = ONE;
75 }
76
77 // initialize a buffer to receive the little-endian elements.
78 let mut buf = [0_u8; 8];
79
80 // iterate the chunks of bytes, creating a field element from each chunk and copying it
81 // into the state.
82 //
83 // every time the rate range is filled, a permutation is performed. if the final value of
84 // `i` is not zero, then the chunks count wasn't enough to fill the state range, and an
85 // additional permutation must be performed.
86 let i = bytes.chunks(BINARY_CHUNK_SIZE).fold(0, |i, chunk| {
87 // the last element of the iteration may or may not be a full chunk. if it's not, then
88 // we need to pad the remainder bytes of the chunk with zeroes, separated by a `1`.
89 // this will avoid collisions.
90 if chunk.len() == BINARY_CHUNK_SIZE {
91 buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
92 } else {
93 buf.fill(0);
94 buf[..chunk.len()].copy_from_slice(chunk);
95 buf[chunk.len()] = 1;
96 }
97
98 // set the current rate element to the input. since we take at most 7 bytes, we are
99 // guaranteed that the inputs data will fit into a single field element.
100 state[RATE_RANGE.start + i] = Felt::new(u64::from_le_bytes(buf));
101
102 // proceed filling the range. if it's full, then we apply a permutation and reset the
103 // counter to the beginning of the range.
104 if i == RATE_WIDTH - 1 {
105 Self::apply_permutation(&mut state);
106 0
107 } else {
108 i + 1
109 }
110 });
111
112 // if we absorbed some elements but didn't apply a permutation to them (would happen when
113 // the number of elements is not a multiple of RATE_WIDTH), apply the RPO permutation. we
114 // don't need to apply any extra padding because the first capacity element contains a
115 // flag indicating whether the input is evenly divisible by the rate.
116 if i != 0 {
117 state[RATE_RANGE.start + i..RATE_RANGE.end].fill(ZERO);
118 state[RATE_RANGE.start + i] = ONE;
119 Self::apply_permutation(&mut state);
120 }
121
122 // return the first 4 elements of the rate as hash result.
123 RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
124 }
125
126 fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
127 // initialize the state by copying the digest elements into the rate portion of the state
128 // (8 total elements), and set the capacity elements to 0.
129 let mut state = [ZERO; STATE_WIDTH];
130 let it = Self::Digest::digests_as_elements(values.iter());
131 for (i, v) in it.enumerate() {
132 state[RATE_RANGE.start + i] = *v;
133 }
134
135 // apply the RPO permutation and return the first four elements of the state
136 Self::apply_permutation(&mut state);
137 RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
138 }
139
140 fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
141 // initialize the state as follows:
142 // - seed is copied into the first 4 elements of the rate portion of the state.
143 // - if the value fits into a single field element, copy it into the fifth rate element
144 // and set the sixth rate element to 1.
145 // - if the value doesn't fit into a single field element, split it into two field
146 // elements, copy them into rate elements 5 and 6, and set the seventh rate element
147 // to 1.
148 // - set the first capacity element to 1
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[INPUT2_RANGE.start + 1] = ONE;
154 } else {
155 state[INPUT2_RANGE.start + 1] = Felt::new(value / Felt::MODULUS);
156 state[INPUT2_RANGE.start + 2] = ONE;
157 }
158
159 // common padding for both cases
160 state[CAPACITY_RANGE.start] = ONE;
161
162 // apply the RPO permutation and return the first four elements of the state
163 Self::apply_permutation(&mut state);
164 RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
165 }
166}
167
168impl ElementHasher for Rpo256 {
169 type BaseField = Felt;
170
171 fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
172 // convert the elements into a list of base field elements
173 let elements = E::slice_as_base_elements(elements);
174
175 // initialize state to all zeros, except for the first element of the capacity part, which
176 // is set to 1 if the number of elements is not a multiple of RATE_WIDTH.
177 let mut state = [ZERO; STATE_WIDTH];
178 if elements.len() % RATE_WIDTH != 0 {
179 state[CAPACITY_RANGE.start] = ONE;
180 }
181
182 // absorb elements into the state one by one until the rate portion of the state is filled
183 // up; then apply the Rescue permutation and start absorbing again; repeat until all
184 // elements have been absorbed
185 let mut i = 0;
186 for &element in elements.iter() {
187 state[RATE_RANGE.start + i] = element;
188 i += 1;
189 if i % RATE_WIDTH == 0 {
190 Self::apply_permutation(&mut state);
191 i = 0;
192 }
193 }
194
195 // if we absorbed some elements but didn't apply a permutation to them (would happen when
196 // the number of elements is not a multiple of RATE_WIDTH), apply the RPO permutation after
197 // padding by appending a 1 followed by as many 0 as necessary to make the input length a
198 // multiple of the RATE_WIDTH.
199 if i > 0 {
200 state[RATE_RANGE.start + i] = ONE;
201 i += 1;
202 while i != RATE_WIDTH {
203 state[RATE_RANGE.start + i] = ZERO;
204 i += 1;
205 }
206 Self::apply_permutation(&mut state);
207 }
208
209 // return the first 4 elements of the state as hash result
210 RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
211 }
212}
213
214// HASH FUNCTION IMPLEMENTATION
215// ================================================================================================
216
217impl Rpo256 {
218 // CONSTANTS
219 // --------------------------------------------------------------------------------------------
220
221 /// The number of rounds is set to 7 to target 128-bit security level.
222 pub const NUM_ROUNDS: usize = NUM_ROUNDS;
223
224 /// Sponge state is set to 12 field elements or 768 bytes; 8 elements are reserved for rate and
225 /// the remaining 4 elements are reserved for capacity.
226 pub const STATE_WIDTH: usize = STATE_WIDTH;
227
228 /// The rate portion of the state is located in elements 4 through 11 (inclusive).
229 pub const RATE_RANGE: Range<usize> = RATE_RANGE;
230
231 /// The capacity portion of the state is located in elements 0, 1, 2, and 3.
232 pub const CAPACITY_RANGE: Range<usize> = CAPACITY_RANGE;
233
234 /// The output of the hash function can be read from state elements 4, 5, 6, and 7.
235 pub const DIGEST_RANGE: Range<usize> = DIGEST_RANGE;
236
237 /// MDS matrix used for computing the linear layer in a RPO round.
238 pub const MDS: [[Felt; STATE_WIDTH]; STATE_WIDTH] = MDS;
239
240 /// Round constants added to the hasher state in the first half of the RPO round.
241 pub const ARK1: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK1;
242
243 /// Round constants added to the hasher state in the second half of the RPO round.
244 pub const ARK2: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK2;
245
246 // TRAIT PASS-THROUGH FUNCTIONS
247 // --------------------------------------------------------------------------------------------
248
249 /// Returns a hash of the provided sequence of bytes.
250 #[inline(always)]
251 pub fn hash(bytes: &[u8]) -> RpoDigest {
252 <Self as Hasher>::hash(bytes)
253 }
254
255 /// Returns a hash of two digests. This method is intended for use in construction of
256 /// Merkle trees and verification of Merkle paths.
257 #[inline(always)]
258 pub fn merge(values: &[RpoDigest; 2]) -> RpoDigest {
259 <Self as Hasher>::merge(values)
260 }
261
262 /// Returns a hash of the provided field elements.
263 #[inline(always)]
264 pub fn hash_elements<E: FieldElement<BaseField = Felt>>(elements: &[E]) -> RpoDigest {
265 <Self as ElementHasher>::hash_elements(elements)
266 }
267
268 // DOMAIN IDENTIFIER
269 // --------------------------------------------------------------------------------------------
270
271 /// Returns a hash of two digests and a domain identifier.
272 pub fn merge_in_domain(values: &[RpoDigest; 2], domain: Felt) -> RpoDigest {
273 // initialize the state by copying the digest elements into the rate portion of the state
274 // (8 total elements), and set the capacity elements to 0.
275 let mut state = [ZERO; STATE_WIDTH];
276 let it = RpoDigest::digests_as_elements(values.iter());
277 for (i, v) in it.enumerate() {
278 state[RATE_RANGE.start + i] = *v;
279 }
280
281 // set the second capacity element to the domain value. The first capacity element is used
282 // for padding purposes.
283 state[CAPACITY_RANGE.start + 1] = domain;
284
285 // apply the RPO permutation and return the first four elements of the state
286 Self::apply_permutation(&mut state);
287 RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
288 }
289
290 // RESCUE PERMUTATION
291 // --------------------------------------------------------------------------------------------
292
293 /// Applies RPO permutation to the provided state.
294 #[inline(always)]
295 pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
296 for i in 0..NUM_ROUNDS {
297 Self::apply_round(state, i);
298 }
299 }
300
301 /// RPO round function.
302 #[inline(always)]
303 pub fn apply_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
304 // apply first half of RPO round
305 apply_mds(state);
306 if !add_constants_and_apply_sbox(state, &ARK1[round]) {
307 add_constants(state, &ARK1[round]);
308 apply_sbox(state);
309 }
310
311 // apply second half of RPO round
312 apply_mds(state);
313 if !add_constants_and_apply_inv_sbox(state, &ARK2[round]) {
314 add_constants(state, &ARK2[round]);
315 apply_inv_sbox(state);
316 }
317 }
318}