arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/hash/rescue/rpx/mod.rs
src/hash/rescue/rpx/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, CubeExtension, Digest, ElementHasher, Felt, FieldElement, Hasher,
  6    StarkField, ARK1, ARK2, BINARY_CHUNK_SIZE, CAPACITY_RANGE, DIGEST_BYTES, DIGEST_RANGE,
  7    DIGEST_SIZE, INPUT1_RANGE, INPUT2_RANGE, MDS, NUM_ROUNDS, RATE_RANGE, RATE_WIDTH, STATE_WIDTH,
  8    ZERO,
  9};
 10
 11mod digest;
 12pub use digest::RpxDigest;
 13
 14pub type CubicExtElement = CubeExtension<Felt>;
 15
 16// HASHER IMPLEMENTATION
 17// ================================================================================================
 18
 19/// Implementation of the Rescue Prime eXtension hash function with 256-bit output.
 20///
 21/// The hash function is based on the XHash12 construction in [specifications](https://eprint.iacr.org/2023/1045)
 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/// * S-Box degree: 7.
 28/// * Rounds: There are 3 different types of rounds:
 29/// - (FB): `apply_mds` → `add_constants` → `apply_sbox` → `apply_mds` → `add_constants` → `apply_inv_sbox`.
 30/// - (E): `add_constants` → `ext_sbox` (which is raising to power 7 in the degree 3 extension field).
 31/// - (M): `apply_mds` → `add_constants`.
 32/// * Permutation: (FB) (E) (FB) (E) (FB) (E) (M).
 33///
 34/// The above parameters target a 128-bit security level. The digest consists of four field elements
 35/// and it can be serialized into 32 bytes (256 bits).
 36///
 37/// ## Hash output consistency
 38/// Functions [hash_elements()](Rpx256::hash_elements), [merge()](Rpx256::merge), and
 39/// [merge_with_int()](Rpx256::merge_with_int) are internally consistent. That is, computing
 40/// a hash for the same set of elements using these functions will always produce the same
 41/// result. For example, merging two digests using [merge()](Rpx256::merge) will produce the
 42/// same result as hashing 8 elements which make up these digests using
 43/// [hash_elements()](Rpx256::hash_elements) function.
 44///
 45/// However, [hash()](Rpx256::hash) function is not consistent with functions mentioned above.
 46/// For example, if we take two field elements, serialize them to bytes and hash them using
 47/// [hash()](Rpx256::hash), the result will differ from the result obtained by hashing these
 48/// elements directly using [hash_elements()](Rpx256::hash_elements) function. The reason for
 49/// this difference is that [hash()](Rpx256::hash) function needs to be able to handle
 50/// arbitrary binary strings, which may or may not encode valid field elements - and thus,
 51/// deserialization procedure used by this function is different from the procedure used to
 52/// deserialize valid field elements.
 53///
 54/// Thus, if the underlying data consists of valid field elements, it might make more sense
 55/// to deserialize them into field elements and then hash them using
 56/// [hash_elements()](Rpx256::hash_elements) function rather then hashing the serialized bytes
 57/// using [hash()](Rpx256::hash) function.
 58#[derive(Debug, Copy, Clone, Eq, PartialEq)]
 59pub struct Rpx256();
 60
 61impl Hasher for Rpx256 {
 62    /// Rpx256 collision resistance is 128-bits.
 63    const COLLISION_RESISTANCE: u32 = 128;
 64
 65    type Digest = RpxDigest;
 66
 67    fn hash(bytes: &[u8]) -> Self::Digest {
 68        // initialize the state with zeroes
 69        let mut state = [ZERO; STATE_WIDTH];
 70
 71        // determine the number of field elements needed to encode `bytes` when each field element
 72        // represents at most 7 bytes.
 73        let num_field_elem = bytes.len().div_ceil(BINARY_CHUNK_SIZE);
 74
 75        // set the first capacity element to `RATE_WIDTH + (num_field_elem % RATE_WIDTH)`. We do
 76        // this to achieve:
 77        // 1. Domain separating hashing of `[u8]` from hashing of `[Felt]`.
 78        // 2. Avoiding collisions at the `[Felt]` representation of the encoded bytes.
 79        state[CAPACITY_RANGE.start] =
 80            Felt::from((RATE_WIDTH + (num_field_elem % RATE_WIDTH)) as u8);
 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            // copy the chunk into the buffer
 93            if i != num_field_elem - 1 {
 94                buf[..BINARY_CHUNK_SIZE].copy_from_slice(chunk);
 95            } else {
 96                // on the last iteration, we pad `buf` with a 1 followed by as many 0's as are
 97                // needed to fill it
 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 RPX permutation. we
119        // don't need to apply any extra padding because the first capacity element contains a
120        // flag indicating the number of field elements constituting the last block when the latter
121        // is not divisible by `RATE_WIDTH`.
122        if i != 0 {
123            state[RATE_RANGE.start + i..RATE_RANGE.end].fill(ZERO);
124            Self::apply_permutation(&mut state);
125        }
126
127        // return the first 4 elements of the rate as hash result.
128        RpxDigest::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 RPX permutation and return the first four elements of the state
141        Self::apply_permutation(&mut state);
142        RpxDigest::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 and
149        //   set the first capacity element to 5.
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 first capacity element to 6.
152        let mut state = [ZERO; STATE_WIDTH];
153        state[INPUT1_RANGE].copy_from_slice(seed.as_elements());
154        state[INPUT2_RANGE.start] = Felt::new(value);
155        if value < Felt::MODULUS {
156            state[CAPACITY_RANGE.start] = Felt::from(5_u8);
157        } else {
158            state[INPUT2_RANGE.start + 1] = Felt::new(value / Felt::MODULUS);
159            state[CAPACITY_RANGE.start] = Felt::from(6_u8);
160        }
161
162        // apply the RPX permutation and return the first four elements of the state
163        Self::apply_permutation(&mut state);
164        RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
165    }
166}
167
168impl ElementHasher for Rpx256 {
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 `elements.len() % RATE_WIDTH`.
177        let mut state = [ZERO; STATE_WIDTH];
178        state[CAPACITY_RANGE.start] = Self::BaseField::from((elements.len() % RATE_WIDTH) as u8);
179
180        // absorb elements into the state one by one until the rate portion of the state is filled
181        // up; then apply the Rescue permutation and start absorbing again; repeat until all
182        // elements have been absorbed
183        let mut i = 0;
184        for &element in elements.iter() {
185            state[RATE_RANGE.start + i] = element;
186            i += 1;
187            if i % RATE_WIDTH == 0 {
188                Self::apply_permutation(&mut state);
189                i = 0;
190            }
191        }
192
193        // if we absorbed some elements but didn't apply a permutation to them (would happen when
194        // the number of elements is not a multiple of RATE_WIDTH), apply the RPX permutation after
195        // padding by as many 0 as necessary to make the input length a multiple of the RATE_WIDTH.
196        if i > 0 {
197            while i != RATE_WIDTH {
198                state[RATE_RANGE.start + i] = ZERO;
199                i += 1;
200            }
201            Self::apply_permutation(&mut state);
202        }
203
204        // return the first 4 elements of the state as hash result
205        RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
206    }
207}
208
209// HASH FUNCTION IMPLEMENTATION
210// ================================================================================================
211
212impl Rpx256 {
213    // CONSTANTS
214    // --------------------------------------------------------------------------------------------
215
216    /// Sponge state is set to 12 field elements or 768 bytes; 8 elements are reserved for rate and
217    /// the remaining 4 elements are reserved for capacity.
218    pub const STATE_WIDTH: usize = STATE_WIDTH;
219
220    /// The rate portion of the state is located in elements 4 through 11 (inclusive).
221    pub const RATE_RANGE: Range<usize> = RATE_RANGE;
222
223    /// The capacity portion of the state is located in elements 0, 1, 2, and 3.
224    pub const CAPACITY_RANGE: Range<usize> = CAPACITY_RANGE;
225
226    /// The output of the hash function can be read from state elements 4, 5, 6, and 7.
227    pub const DIGEST_RANGE: Range<usize> = DIGEST_RANGE;
228
229    /// MDS matrix used for computing the linear layer in the (FB) and (E) rounds.
230    pub const MDS: [[Felt; STATE_WIDTH]; STATE_WIDTH] = MDS;
231
232    /// Round constants added to the hasher state in the first half of the round.
233    pub const ARK1: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK1;
234
235    /// Round constants added to the hasher state in the second half of the round.
236    pub const ARK2: [[Felt; STATE_WIDTH]; NUM_ROUNDS] = ARK2;
237
238    // TRAIT PASS-THROUGH FUNCTIONS
239    // --------------------------------------------------------------------------------------------
240
241    /// Returns a hash of the provided sequence of bytes.
242    #[inline(always)]
243    pub fn hash(bytes: &[u8]) -> RpxDigest {
244        <Self as Hasher>::hash(bytes)
245    }
246
247    /// Returns a hash of two digests. This method is intended for use in construction of
248    /// Merkle trees and verification of Merkle paths.
249    #[inline(always)]
250    pub fn merge(values: &[RpxDigest; 2]) -> RpxDigest {
251        <Self as Hasher>::merge(values)
252    }
253
254    /// Returns a hash of the provided field elements.
255    #[inline(always)]
256    pub fn hash_elements<E: FieldElement<BaseField = Felt>>(elements: &[E]) -> RpxDigest {
257        <Self as ElementHasher>::hash_elements(elements)
258    }
259
260    // DOMAIN IDENTIFIER
261    // --------------------------------------------------------------------------------------------
262
263    /// Returns a hash of two digests and a domain identifier.
264    pub fn merge_in_domain(values: &[RpxDigest; 2], domain: Felt) -> RpxDigest {
265        // initialize the state by copying the digest elements into the rate portion of the state
266        // (8 total elements), and set the capacity elements to 0.
267        let mut state = [ZERO; STATE_WIDTH];
268        let it = RpxDigest::digests_as_elements(values.iter());
269        for (i, v) in it.enumerate() {
270            state[RATE_RANGE.start + i] = *v;
271        }
272
273        // set the second capacity element to the domain value. The first capacity element is used
274        // for padding purposes.
275        state[CAPACITY_RANGE.start + 1] = domain;
276
277        // apply the RPX permutation and return the first four elements of the state
278        Self::apply_permutation(&mut state);
279        RpxDigest::new(state[DIGEST_RANGE].try_into().unwrap())
280    }
281
282    // RPX PERMUTATION
283    // --------------------------------------------------------------------------------------------
284
285    /// Applies RPX permutation to the provided state.
286    #[inline(always)]
287    pub fn apply_permutation(state: &mut [Felt; STATE_WIDTH]) {
288        Self::apply_fb_round(state, 0);
289        Self::apply_ext_round(state, 1);
290        Self::apply_fb_round(state, 2);
291        Self::apply_ext_round(state, 3);
292        Self::apply_fb_round(state, 4);
293        Self::apply_ext_round(state, 5);
294        Self::apply_final_round(state, 6);
295    }
296
297    // RPX PERMUTATION ROUND FUNCTIONS
298    // --------------------------------------------------------------------------------------------
299
300    /// (FB) round function.
301    #[inline(always)]
302    pub fn apply_fb_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
303        apply_mds(state);
304        if !add_constants_and_apply_sbox(state, &ARK1[round]) {
305            add_constants(state, &ARK1[round]);
306            apply_sbox(state);
307        }
308
309        apply_mds(state);
310        if !add_constants_and_apply_inv_sbox(state, &ARK2[round]) {
311            add_constants(state, &ARK2[round]);
312            apply_inv_sbox(state);
313        }
314    }
315
316    /// (E) round function.
317    #[inline(always)]
318    pub fn apply_ext_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
319        // add constants
320        add_constants(state, &ARK1[round]);
321
322        // decompose the state into 4 elements in the cubic extension field and apply the power 7
323        // map to each of the elements
324        let [s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11] = *state;
325        let ext0 = Self::exp7(CubicExtElement::new(s0, s1, s2));
326        let ext1 = Self::exp7(CubicExtElement::new(s3, s4, s5));
327        let ext2 = Self::exp7(CubicExtElement::new(s6, s7, s8));
328        let ext3 = Self::exp7(CubicExtElement::new(s9, s10, s11));
329
330        // decompose the state back into 12 base field elements
331        let arr_ext = [ext0, ext1, ext2, ext3];
332        *state = CubicExtElement::slice_as_base_elements(&arr_ext)
333            .try_into()
334            .expect("shouldn't fail");
335    }
336
337    /// (M) round function.
338    #[inline(always)]
339    pub fn apply_final_round(state: &mut [Felt; STATE_WIDTH], round: usize) {
340        apply_mds(state);
341        add_constants(state, &ARK1[round]);
342    }
343
344    /// Computes an exponentiation to the power 7 in cubic extension field.
345    #[inline(always)]
346    pub fn exp7(x: CubeExtension<Felt>) -> CubeExtension<Felt> {
347        let x2 = x.square();
348        let x4 = x2.square();
349
350        let x3 = x2 * x;
351        x3 * x4
352    }
353}