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