Skip to main content

miden_crypto/
lib.rs

1#![no_std]
2#![allow(clippy::chunks_exact_to_as_chunks)]
3
4#[macro_use]
5extern crate alloc;
6#[cfg(feature = "std")]
7extern crate std;
8
9pub mod aead;
10pub mod dsa;
11pub mod ecdh;
12pub mod hash;
13pub mod ies;
14pub mod merkle;
15pub mod rand;
16pub mod utils;
17
18// RE-EXPORTS
19// ================================================================================================
20pub use miden_field::{Felt, Word, WordError, word};
21
22pub mod field {
23    //! Traits and utilities for working with the Goldilocks finite field (i.e.,
24    //! [Felt](super::Felt)).
25
26    pub use miden_field::{
27        Algebra, BasedVectorSpace, Binomial, BinomialExtensionField, BinomiallyExtendable,
28        BoundedPowers, ExtensionAlgebra, ExtensionField, Field, HasTwoAdicBinomialExtension,
29        InjectiveMonomial, Packable, PermutationMonomial, Powers, PrimeCharacteristicRing,
30        PrimeField, PrimeField64, QuotientMap, RawDataSerializable, TwoAdicField,
31        batch_multiplicative_inverse,
32    };
33
34    pub use super::batch_inversion::batch_inversion_allow_zeros;
35}
36
37pub mod parallel {
38    //! Conditional parallel iteration primitives.
39    //!
40    //! When the `concurrent` feature is enabled, this module re-exports parallel iterator
41    //! traits from `p3-maybe-rayon` backed by rayon. Without `concurrent`, these traits
42    //! fall back to sequential iteration.
43    pub use p3_maybe_rayon::prelude::*;
44}
45
46// TYPE ALIASES
47// ================================================================================================
48
49/// An alias for a key-value map.
50///
51/// When the `std` feature is enabled, this is an alias for [`std::collections::HashMap`].
52/// Otherwise, this is an alias for [`alloc::collections::BTreeMap`].
53#[cfg(feature = "std")]
54pub type Map<K, V> = std::collections::HashMap<K, V>;
55
56/// An alias for a key-value map.
57///
58/// When the `std` feature is enabled, this is an alias for [`std::collections::HashMap`].
59/// Otherwise, this is an alias for [`alloc::collections::BTreeMap`].
60#[cfg(not(feature = "std"))]
61pub type Map<K, V> = alloc::collections::BTreeMap<K, V>;
62
63#[cfg(not(feature = "std"))]
64pub use alloc::collections::btree_map::Entry as MapEntry;
65#[cfg(not(feature = "std"))]
66pub use alloc::collections::btree_map::IntoIter as MapIntoIter;
67#[cfg(feature = "std")]
68pub use std::collections::hash_map::Entry as MapEntry;
69#[cfg(feature = "std")]
70pub use std::collections::hash_map::IntoIter as MapIntoIter;
71
72/// An alias for a simple set.
73///
74/// When the `std` feature is enabled, this is an alias for [`std::collections::HashSet`].
75/// Otherwise, this is an alias for [`alloc::collections::BTreeSet`].
76#[cfg(feature = "std")]
77pub type Set<V> = std::collections::HashSet<V>;
78
79/// An alias for a simple set.
80///
81/// When the `std` feature is enabled, this is an alias for [`std::collections::HashSet`].
82/// Otherwise, this is an alias for [`alloc::collections::BTreeSet`].
83#[cfg(not(feature = "std"))]
84pub type Set<V> = alloc::collections::BTreeSet<V>;
85
86// CONSTANTS
87// ================================================================================================
88
89/// Field element representing ZERO in the Miden base field.
90pub const ZERO: Felt = Felt::ZERO;
91
92/// Field element representing ONE in the Miden base field.
93pub const ONE: Felt = Felt::ONE;
94
95/// Array of field elements representing word of ZEROs in the Miden base field.
96pub const EMPTY_WORD: Word = Word::new([ZERO; Word::NUM_ELEMENTS]);
97
98// TRAITS
99// ================================================================================================
100
101/// Defines how to compute a commitment to an object represented as a sequence of field elements.
102pub trait SequentialCommit {
103    /// A type of the commitment which must be derivable from [Word].
104    type Commitment: From<Word>;
105
106    /// Computes the commitment to the object.
107    ///
108    /// The default implementation hashes the sequence of elements returned from
109    /// [Self::to_elements()] with Eidos.
110    fn to_commitment(&self) -> Self::Commitment {
111        hash::eidos::Eidos::hash_elements(&self.to_elements()).into()
112    }
113
114    /// Returns a representation of the object as a sequence of fields elements.
115    fn to_elements(&self) -> alloc::vec::Vec<Felt>;
116}
117
118// BATCH INVERSION
119// ================================================================================================
120
121mod batch_inversion {
122    use p3_maybe_rayon::prelude::*;
123
124    use super::{Felt, ONE, ZERO, field::Field};
125
126    /// Parallel batch inversion using Montgomery's trick, with zeros left unchanged.
127    ///
128    /// Processes chunks in parallel using rayon, each chunk using Montgomery's trick.
129    pub fn batch_inversion_allow_zeros(values: &mut [Felt]) {
130        const CHUNK_SIZE: usize = 1024;
131
132        values.par_chunks_mut(CHUNK_SIZE).for_each(|output_chunk| {
133            let len = output_chunk.len();
134            let mut scratch = [ZERO; CHUNK_SIZE];
135            scratch[..len].copy_from_slice(output_chunk);
136            batch_inversion_helper(&scratch[..len], output_chunk);
137        });
138    }
139
140    /// Montgomery's trick for batch inversion, handling zeros.
141    fn batch_inversion_helper(values: &[Felt], result: &mut [Felt]) {
142        debug_assert_eq!(values.len(), result.len());
143
144        if values.is_empty() {
145            return;
146        }
147
148        // Forward pass: compute cumulative products, skipping zeros
149        let mut last = ONE;
150        for (result, &value) in result.iter_mut().zip(values.iter()) {
151            *result = last;
152            if value != ZERO {
153                last *= value;
154            }
155        }
156
157        // Invert the final cumulative product
158        last = last.inverse();
159
160        // Backward pass: compute individual inverses
161        for i in (0..values.len()).rev() {
162            if values[i] == ZERO {
163                result[i] = ZERO;
164            } else {
165                result[i] *= last;
166                last *= values[i];
167            }
168        }
169    }
170
171    #[cfg(test)]
172    mod tests {
173        use alloc::vec::Vec;
174
175        use super::*;
176
177        #[test]
178        fn test_batch_inversion_allow_zeros() {
179            let mut column = Vec::from([
180                Felt::new_unchecked(2),
181                ZERO,
182                Felt::new_unchecked(4),
183                Felt::new_unchecked(5),
184            ]);
185            batch_inversion_allow_zeros(&mut column);
186
187            assert_eq!(column[0], Felt::new_unchecked(2).inverse());
188            assert_eq!(column[1], ZERO);
189            assert_eq!(column[2], Felt::new_unchecked(4).inverse());
190            assert_eq!(column[3], Felt::new_unchecked(5).inverse());
191        }
192
193        #[test]
194        fn test_batch_inversion_allow_zeros_spans_fixed_chunks() {
195            let mut v: Vec<Felt> = (1_u64..=2050).map(Felt::new_unchecked).collect();
196            let expected: Vec<Felt> = v.iter().copied().map(|x| x.inverse()).collect();
197            batch_inversion_allow_zeros(&mut v);
198            assert_eq!(v, expected);
199        }
200
201        #[test]
202        fn test_batch_inversion_allow_zeros_zero_on_chunk_boundary() {
203            let mut v = vec![Felt::new_unchecked(7); 1025];
204            v[1023] = ZERO;
205            batch_inversion_allow_zeros(&mut v);
206            assert_eq!(v[1023], ZERO);
207            for i in (0..1023).chain(1024..1025) {
208                assert_eq!(v[i], Felt::new_unchecked(7).inverse());
209            }
210        }
211    }
212}
213
214// TESTS
215// ================================================================================================
216
217#[cfg(test)]
218mod tests {
219
220    #[test]
221    #[should_panic]
222    fn debug_assert_is_checked() {
223        // enforce the release checks to always have `RUSTFLAGS="-C debug-assertions"`.
224        //
225        // some upstream tests are performed with `debug_assert`, and we want to assert its
226        // correctness downstream.
227        //
228        // for reference, check
229        // https://github.com/0xMiden/miden-vm/issues/433
230        debug_assert!(false);
231    }
232
233    #[test]
234    #[should_panic]
235    #[allow(arithmetic_overflow)]
236    fn overflow_panics_for_test() {
237        // overflows might be disabled if tests are performed in release mode. these are critical,
238        // mandatory checks as overflows might be attack vectors.
239        //
240        // to enable overflow checks in release mode, ensure `RUSTFLAGS="-C overflow-checks"`
241        let a = 1_u64;
242        let b = 64;
243        assert_ne!(a << b, 0);
244    }
245}