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