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