miden_crypto/
lib.rs

1#![no_std]
2
3#[macro_use]
4extern crate alloc;
5#[cfg(feature = "std")]
6extern crate std;
7
8use field::PrimeCharacteristicRing;
9
10pub mod aead;
11pub mod dsa;
12pub mod ecdh;
13pub mod hash;
14pub mod ies;
15pub mod merkle;
16pub mod rand;
17pub mod utils;
18pub mod word;
19
20// RE-EXPORTS
21// ================================================================================================
22pub use p3_goldilocks::Goldilocks as Felt;
23pub use word::{Word, WordError};
24
25pub mod field {
26    //! Traits and utilities for working with the Goldilocks finite field (i.e.,
27    //! [Felt](super::Felt)).
28
29    pub use p3_field::{
30        BasedVectorSpace, ExtensionField, Field, PrimeCharacteristicRing, PrimeField64,
31        TwoAdicField, batch_multiplicative_inverse, extension::BinomialExtensionField,
32        integers::QuotientMap,
33    };
34}
35
36pub mod parallel {
37    //! Conditional parallel iteration primitives.
38    //!
39    //! When the `concurrent` feature is enabled, this module re-exports parallel iterator
40    //! traits from `p3-maybe-rayon` backed by rayon. Without `concurrent`, these traits
41    //! fall back to sequential iteration.
42    pub use p3_maybe_rayon::prelude::*;
43}
44
45pub mod stark {
46    //! Foundational components for the STARK proving system based on Plonky3.
47    //!
48    //! This module contains components needed to build a STARK prover/verifier and define
49    //! Algebraic Intermediate Representation (AIR) for the Miden VM and other components.
50    //! It primarily consists of re-exports from the Plonky3 project with some Miden-specific
51    //! adaptations.
52    pub use p3_miden_prover::{
53        Commitments, Domain, Entry, OpenedValues, PackedChallenge, PackedVal, PcsError, Proof,
54        ProverConstraintFolder, StarkConfig, StarkGenericConfig, SymbolicAirBuilder,
55        SymbolicExpression, SymbolicVariable, Val, VerificationError, VerifierConstraintFolder,
56        generate_logup_trace, get_log_quotient_degree, get_max_constraint_degree,
57        get_symbolic_constraints, prove, quotient_values, recompose_quotient_from_chunks, verify,
58        verify_constraints,
59    };
60
61    pub mod challenger {
62        pub use p3_challenger::{HashChallenger, SerializingChallenger64};
63    }
64
65    pub mod symmetric {
66        pub use p3_symmetric::{
67            CompressionFunctionFromHasher, PaddingFreeSponge, SerializingHasher,
68        };
69    }
70
71    pub mod air {
72        pub use p3_air::{
73            Air, AirBuilder, AirBuilderWithPublicValues, BaseAir, BaseAirWithPublicValues,
74            ExtensionBuilder, FilteredAirBuilder, PairBuilder, PairCol, PermutationAirBuilder,
75            VirtualPairCol,
76        };
77        pub use p3_miden_air::{
78            BaseAirWithAuxTrace, FilteredMidenAirBuilder, MidenAir, MidenAirBuilder,
79        };
80    }
81}
82
83// TYPE ALIASES
84// ================================================================================================
85
86/// An alias for a key-value map.
87///
88/// By default, this is an alias for the [`alloc::collections::BTreeMap`], however, when the
89/// `hashmaps` feature is enabled, this is an alias for the `hashbrown`'s `HashMap`.
90#[cfg(feature = "hashmaps")]
91pub type Map<K, V> = hashbrown::HashMap<K, V>;
92
93#[cfg(feature = "hashmaps")]
94pub use hashbrown::hash_map::Entry as MapEntry;
95
96/// An alias for a key-value map.
97///
98/// By default, this is an alias for the [`alloc::collections::BTreeMap`], however, when the
99/// `hashmaps` feature is enabled, this is an alias for the `hashbrown`'s `HashMap`.
100#[cfg(not(feature = "hashmaps"))]
101pub type Map<K, V> = alloc::collections::BTreeMap<K, V>;
102
103#[cfg(not(feature = "hashmaps"))]
104pub use alloc::collections::btree_map::Entry as MapEntry;
105
106/// An alias for a simple set.
107///
108/// By default, this is an alias for the [`alloc::collections::BTreeSet`]. However, when the
109/// `hashmaps` feature is enabled, this becomes an alias for hashbrown's HashSet.
110#[cfg(feature = "hashmaps")]
111pub type Set<V> = hashbrown::HashSet<V>;
112
113/// An alias for a simple set.
114///
115/// By default, this is an alias for the [`alloc::collections::BTreeSet`]. However, when the
116/// `hashmaps` feature is enabled, this becomes an alias for hashbrown's HashSet.
117#[cfg(not(feature = "hashmaps"))]
118pub type Set<V> = alloc::collections::BTreeSet<V>;
119
120// CONSTANTS
121// ================================================================================================
122
123/// Number of field elements in a word.
124pub const WORD_SIZE: usize = 4;
125
126/// Field element representing ZERO in the Miden base filed.
127pub const ZERO: Felt = Felt::ZERO;
128
129/// Field element representing ONE in the Miden base filed.
130pub const ONE: Felt = Felt::ONE;
131
132/// Array of field elements representing word of ZEROs in the Miden base field.
133pub const EMPTY_WORD: Word = Word::new([ZERO; WORD_SIZE]);
134
135// TRAITS
136// ================================================================================================
137
138/// Defines how to compute a commitment to an object represented as a sequence of field elements.
139pub trait SequentialCommit {
140    /// A type of the commitment which must be derivable from [Word].
141    type Commitment: From<Word>;
142
143    /// Computes the commitment to the object.
144    ///
145    /// The default implementation of this function uses RPO256 hash function to hash the sequence
146    /// of elements returned from [Self::to_elements()].
147    fn to_commitment(&self) -> Self::Commitment {
148        hash::rpo::Rpo256::hash_elements(&self.to_elements()).into()
149    }
150
151    /// Returns a representation of the object as a sequence of fields elements.
152    fn to_elements(&self) -> alloc::vec::Vec<Felt>;
153}
154
155// TESTS
156// ================================================================================================
157
158#[test]
159#[should_panic]
160fn debug_assert_is_checked() {
161    // enforce the release checks to always have `RUSTFLAGS="-C debug-assertions"`.
162    //
163    // some upstream tests are performed with `debug_assert`, and we want to assert its correctness
164    // downstream.
165    //
166    // for reference, check
167    // https://github.com/0xMiden/miden-vm/issues/433
168    debug_assert!(false);
169}
170
171#[test]
172#[should_panic]
173#[allow(arithmetic_overflow)]
174fn overflow_panics_for_test() {
175    // overflows might be disabled if tests are performed in release mode. these are critical,
176    // mandatory checks as overflows might be attack vectors.
177    //
178    // to enable overflow checks in release mode, ensure `RUSTFLAGS="-C overflow-checks"`
179    let a = 1_u64;
180    let b = 64;
181    assert_ne!(a << b, 0);
182}