arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
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 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 the same as the security level, that is 128-bits.
 59    ///
 60    /// #### Collision resistance
 61    ///
 62    /// However, our setup of the capacity registers might drop it to 126.
 63    ///
 64    /// Related issue: [#69](https://github.com/0xPolygonMiden/crypto/issues/69)
 65    const COLLISION_RESISTANCE: u32 = 128;
 66
 67    type Digest = RpoDigest;
 68
 69    fn hash(bytes: &[u8]) -> Self::Digest {
 70        // initialize the state with zeroes
 71        let mut state = [ZERO; STATE_WIDTH];
 72
 73        // set the capacity (first element) to a flag on whether or not the input length is evenly
 74        // divided by the rate. this will prevent collisions between padded and non-padded inputs,
 75        // and will rule out the need to perform an extra permutation in case of evenly divided
 76        // inputs.
 77        let is_rate_multiple = bytes.len() % RATE_WIDTH == 0;
 78        if !is_rate_multiple {
 79            state[CAPACITY_RANGE.start] = ONE;
 80        }
 81
 82        // initialize a buffer to receive the little-endian elements.
 83        let mut buf = [0_u8; 8];
 84
 85        // iterate the chunks of bytes, creating a field element from each chunk and copying it
 86        // into the state.
 87        //
 88        // every time the rate range is filled, a permutation is performed. if the final value of
 89        // `i` is not zero, then the chunks count wasn't enough to fill the state range, and an
 90        // additional permutation must be performed.
 91        let i = bytes.chunks(BINARY_CHUNK_SIZE).fold(0, |i, chunk| {
 92            // the last element of the iteration may or may not be a full chunk. if it's not, then
 93            // we need to pad the remainder bytes of the chunk with zeroes, separated by a `1`.
 94            // this will avoid collisions.
 95            if chunk.len() == BINARY_CHUNK_SIZE {
 96                buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
 97            } else {
 98                buf.fill(0);
 99                buf[..chunk.len()].copy_from_slice(chunk);
100                buf[chunk.len()] = 1;
101            }
102
103            // set the current rate element to the input. since we take at most 7 bytes, we are
104            // guaranteed that the inputs data will fit into a single field element.
105            state[RATE_RANGE.start + i] = Felt::new(u64::from_le_bytes(buf));
106
107            // proceed filling the range. if it's full, then we apply a permutation and reset the
108            // counter to the beginning of the range.
109            if i == RATE_WIDTH - 1 {
110                Self::apply_permutation(&mut state);
111                0
112            } else {
113                i + 1
114            }
115        });
116
117        // if we absorbed some elements but didn't apply a permutation to them (would happen when
118        // the number of elements is not a multiple of RATE_WIDTH), apply the RPO permutation. we
119        // don't need to apply any extra padding because the first capacity element contains a
120        // flag indicating whether the input is evenly divisible by the rate.
121        if i != 0 {
122            state[RATE_RANGE.start + i..RATE_RANGE.end].fill(ZERO);
123            state[RATE_RANGE.start + i] = ONE;
124            Self::apply_permutation(&mut state);
125        }
126
127        // return the first 4 elements of the rate as hash result.
128        RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
129    }
130
131    fn merge(values: &[Self::Digest; 2]) -> Self::Digest {
132        // initialize the state by copying the digest elements into the rate portion of the state
133        // (8 total elements), and set the capacity elements to 0.
134        let mut state = [ZERO; STATE_WIDTH];
135        let it = Self::Digest::digests_as_elements(values.iter());
136        for (i, v) in it.enumerate() {
137            state[RATE_RANGE.start + i] = *v;
138        }
139
140        // apply the RPO permutation and return the first four elements of the state
141        Self::apply_permutation(&mut state);
142        RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
143    }
144
145    fn merge_with_int(seed: Self::Digest, value: u64) -> Self::Digest {
146        // initialize the state as follows:
147        // - seed is copied into the first 4 elements of the rate portion of the state.
148        // - if the value fits into a single field element, copy it into the fifth rate element
149        //   and set the sixth rate element to 1.
150        // - if the value doesn't fit into a single field element, split it into two field
151        //   elements, copy them into rate elements 5 and 6, and set the seventh rate element
152        //   to 1.
153        // - set the first capacity element to 1
154        let mut state = [ZERO; STATE_WIDTH];
155        state[INPUT1_RANGE].copy_from_slice(seed.as_elements());
156        state[INPUT2_RANGE.start] = Felt::new(value);
157        if value < Felt::MODULUS {
158            state[INPUT2_RANGE.start + 1] = ONE;
159        } else {
160            state[INPUT2_RANGE.start + 1] = Felt::new(value / Felt::MODULUS);
161            state[INPUT2_RANGE.start + 2] = ONE;
162        }
163
164        // common padding for both cases
165        state[CAPACITY_RANGE.start] = ONE;
166
167        // apply the RPO permutation and return the first four elements of the state
168        Self::apply_permutation(&mut state);
169        RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
170    }
171}
172
173impl ElementHasher for Rpo256 {
174    type BaseField = Felt;
175
176    fn hash_elements<E: FieldElement<BaseField = Self::BaseField>>(elements: &[E]) -> Self::Digest {
177        // convert the elements into a list of base field elements
178        let elements = E::slice_as_base_elements(elements);
179
180        // initialize state to all zeros, except for the first element of the capacity part, which
181        // is set to 1 if the number of elements is not a multiple of RATE_WIDTH.
182        let mut state = [ZERO; STATE_WIDTH];
183        if elements.len() % RATE_WIDTH != 0 {
184            state[CAPACITY_RANGE.start] = ONE;
185        }
186
187        // absorb elements into the state one by one until the rate portion of the state is filled
188        // up; then apply the Rescue permutation and start absorbing again; repeat until all
189        // elements have been absorbed
190        let mut i = 0;
191        for &element in elements.iter() {
192            state[RATE_RANGE.start + i] = element;
193            i += 1;
194            if i % RATE_WIDTH == 0 {
195                Self::apply_permutation(&mut state);
196                i = 0;
197            }
198        }
199
200        // if we absorbed some elements but didn't apply a permutation to them (would happen when
201        // the number of elements is not a multiple of RATE_WIDTH), apply the RPO permutation after
202        // padding by appending a 1 followed by as many 0 as necessary to make the input length a
203        // multiple of the RATE_WIDTH.
204        if i > 0 {
205            state[RATE_RANGE.start + i] = ONE;
206            i += 1;
207            while i != RATE_WIDTH {
208                state[RATE_RANGE.start + i] = ZERO;
209                i += 1;
210            }
211            Self::apply_permutation(&mut state);
212        }
213
214        // return the first 4 elements of the state as hash result
215        RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
216    }
217}
218
219// HASH FUNCTION IMPLEMENTATION
220// ================================================================================================
221
222impl Rpo256 {
223    // CONSTANTS
224    // --------------------------------------------------------------------------------------------
225
226    /// The number of rounds is set to 7 to target 128-bit security level.
227    pub const NUM_ROUNDS: usize = NUM_ROUNDS;
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 a RPO round.
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 RPO 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 RPO 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]) -> RpoDigest {
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: &[RpoDigest; 2]) -> RpoDigest {
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]) -> RpoDigest {
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: &[RpoDigest; 2], domain: Felt) -> RpoDigest {
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 = RpoDigest::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 RPO permutation and return the first four elements of the state
291        Self::apply_permutation(&mut state);
292        RpoDigest::new(state[DIGEST_RANGE].try_into().unwrap())
293    }
294
295    // RESCUE PERMUTATION
296    // --------------------------------------------------------------------------------------------
297
298    /// Applies RPO permutation to the provided state.
299    #[inline(always)]
300    pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
301        for i in 0..NUM_ROUNDS {
302            Self::apply_round(state, i);
303        }
304    }
305
306    /// RPO round function.
307    #[inline(always)]
308    pub fn apply_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
309        // apply first half of RPO round
310        apply_mds(state);
311        if !add_constants_and_apply_sbox(state, &ARK1[round]) {
312            add_constants(state, &ARK1[round]);
313            apply_sbox(state);
314        }
315
316        // apply second half of RPO round
317        apply_mds(state);
318        if !add_constants_and_apply_inv_sbox(state, &ARK2[round]) {
319            add_constants(state, &ARK2[round]);
320            apply_inv_sbox(state);
321        }
322    }
323}