p3-miden-dev-utils 0.5.0

Shared development utilities (benchmarks, test fixtures) for p3-miden crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Field/hash configuration modules and trait definitions.
//!
//! This module contains:
//! - `BenchScenario` and `PcsScenario` traits for generic benchmarking
//! - Macros for generating config-specific modules
//! - Config implementations (baby_bear_poseidon2, goldilocks_poseidon2, etc.)
//!
//! # Usage
//!
//! ## For tests (import specific config module)
//! ```ignore
//! use p3_miden_dev_utils::configs::baby_bear_poseidon2::*;
//!
//! #[test]
//! fn test_example() {
//!     let challenger = test_challenger();
//! }
//! ```
//!
//! ## For benchmarks (use trait-based dispatch)
//! ```ignore
//! use p3_miden_dev_utils::{BenchScenario, BabyBearPoseidon2};
//!
//! fn bench<S: BenchScenario>() {
//!     let mmcs = S::packed_mmcs();
//! }
//! ```

use p3_challenger::{CanObserve, FieldChallenger, GrindingChallenger};
use p3_commit::Mmcs;
use p3_field::{ExtensionField, Field, TwoAdicField};

// =============================================================================
// Traits
// =============================================================================

/// Trait for benchmark scenarios defining field + hash configuration.
///
/// Each implementor represents a specific combination from the matrix:
/// - Fields: BabyBear, Goldilocks
/// - Hashes: Poseidon2, Keccak
///
/// # Example
///
/// ```ignore
/// fn bench_generic<S: BenchScenario>(c: &mut Criterion) {
///     for &log_height in LOG_HEIGHTS {
///         let group_name = format!("MyBench/{}/{}", S::FIELD_NAME, S::HASH_NAME);
///         let mmcs = S::packed_mmcs();
///         // ...
///     }
/// }
/// ```
pub trait BenchScenario {
    /// Base field type (e.g., BabyBear, Goldilocks)
    type F: Field + TwoAdicField + Ord;

    /// Extension field type
    type EF: ExtensionField<Self::F> + TwoAdicField;

    /// MMCS type for benchmarks
    type Mmcs: Mmcs<Self::F>;

    /// Field name for benchmark grouping
    const FIELD_NAME: &'static str;

    /// Hash name for benchmark grouping
    const HASH_NAME: &'static str;

    /// Create MMCS instance
    fn mmcs() -> Self::Mmcs;
}

/// Extended trait for PCS benchmarks requiring Fiat-Shamir challenger.
///
/// Only implemented for Poseidon2 scenarios because Keccak produces
/// `Hash<F, u64, N>` commitments which are incompatible with DuplexChallenger.
pub trait PcsScenario: BenchScenario {
    /// Challenger type for Fiat-Shamir
    type Challenger: Clone
        + FieldChallenger<Self::F>
        + GrindingChallenger
        + CanObserve<<Self::Mmcs as Mmcs<Self::F>>::Commitment>;

    /// Rate constant for sponge (used for LMCS alignment defaults)
    const RATE: usize;

    /// Create a new challenger instance
    fn challenger() -> Self::Challenger;
}

// =============================================================================
// Helper trait for permutation construction
// =============================================================================

/// Helper trait for creating permutations from RNG.
///
/// This is needed because BabyBear and Goldilocks permutations have
/// the same method but it's not defined in a common trait.
pub trait PermFromRng: Sized {
    fn new_from_rng_128(rng: &mut SmallRng) -> Self;
}

use rand::rngs::SmallRng;

// BabyBear Poseidon2 implementations (only 16 and 24 are supported)
impl PermFromRng for p3_baby_bear::Poseidon2BabyBear<16> {
    fn new_from_rng_128(rng: &mut SmallRng) -> Self {
        p3_baby_bear::Poseidon2BabyBear::new_from_rng_128(rng)
    }
}

impl PermFromRng for p3_baby_bear::Poseidon2BabyBear<24> {
    fn new_from_rng_128(rng: &mut SmallRng) -> Self {
        p3_baby_bear::Poseidon2BabyBear::new_from_rng_128(rng)
    }
}

// Goldilocks Poseidon2 implementations (8 and 12 are common)
impl PermFromRng for p3_goldilocks::Poseidon2Goldilocks<8> {
    fn new_from_rng_128(rng: &mut SmallRng) -> Self {
        p3_goldilocks::Poseidon2Goldilocks::new_from_rng_128(rng)
    }
}

impl PermFromRng for p3_goldilocks::Poseidon2Goldilocks<12> {
    fn new_from_rng_128(rng: &mut SmallRng) -> Self {
        p3_goldilocks::Poseidon2Goldilocks::new_from_rng_128(rng)
    }
}

// =============================================================================
// Macros for generating config modules
// =============================================================================

/// Macro to generate a Poseidon2-based config module.
///
/// Generates:
/// - Type aliases (F, P, EF, Perm, Sponge, Compress, BaseMmcs, Challenger)
/// - Constants (WIDTH, RATE, DIGEST)
/// - Constructor functions (test_components, test_challenger)
/// - BenchScenario + PcsScenario implementations
#[macro_export]
macro_rules! impl_poseidon2_config {
    (
        scenario: $scenario:ident,
        field: $field:ty,
        ext_degree: $ext_deg:literal,
        perm: $perm:ident,
        width: $width:literal,
        rate: $rate:literal,
        digest: $digest:literal,
        field_name: $field_name:literal
    ) => {
        use p3_challenger::DuplexChallenger;
        use p3_field::{Field, extension::BinomialExtensionField};
        use p3_merkle_tree::MerkleTreeMmcs;
        use p3_miden_stateful_hasher::StatefulSponge;
        use p3_symmetric::{PaddingFreeSponge, TruncatedPermutation};
        use rand::{SeedableRng, rngs::SmallRng};
        use $crate::{
            configs::{BenchScenario, PcsScenario},
            fixtures::TEST_SEED,
        };

        // =====================================================================
        // Constants
        // =====================================================================

        /// Poseidon2 permutation width.
        pub const WIDTH: usize = $width;

        /// Sponge rate (elements absorbed per permutation).
        pub const RATE: usize = $rate;

        /// Digest size in field elements.
        pub const DIGEST: usize = $digest;

        // =====================================================================
        // Type aliases
        // =====================================================================

        /// Base field.
        pub type F = $field;

        /// Packed base field for SIMD operations.
        pub type P = <F as Field>::Packing;

        /// Extension field.
        pub type EF = BinomialExtensionField<F, $ext_deg>;

        /// Poseidon2 permutation.
        pub type Perm = $perm<$width>;

        /// Stateful sponge for hashing (can be used for LMCS).
        pub type Sponge = StatefulSponge<Perm, WIDTH, RATE, DIGEST>;

        /// Padding-free sponge for MMCS hashing.
        pub type MmcsSponge = PaddingFreeSponge<Perm, WIDTH, RATE, DIGEST>;

        /// Truncated permutation for 2-to-1 compression.
        pub type Compress = TruncatedPermutation<Perm, 2, DIGEST, WIDTH>;

        /// Base Merkle tree MMCS over packed field.
        pub type BaseMmcs = MerkleTreeMmcs<P, P, MmcsSponge, Compress, 2, DIGEST>;

        /// Duplex challenger for Fiat-Shamir.
        pub type Challenger = DuplexChallenger<F, Perm, WIDTH, RATE>;

        // =====================================================================
        // Constructor functions
        // =====================================================================

        /// Create the permutation with standard seed.
        pub fn create_perm() -> Perm {
            let mut rng = SmallRng::seed_from_u64(TEST_SEED);
            <Perm as $crate::configs::PermFromRng>::new_from_rng_128(&mut rng)
        }

        /// Create standard test components with a consistent seed.
        ///
        /// Returns the permutation, sponge, and compressor for Merkle tree construction.
        pub fn test_components() -> (Perm, Sponge, Compress) {
            let perm = create_perm();
            let sponge = Sponge::new(perm.clone());
            let compress = Compress::new(perm.clone());
            (perm, sponge, compress)
        }

        /// Create a standard challenger for Fiat-Shamir.
        pub fn test_challenger() -> Challenger {
            Challenger::new(create_perm())
        }

        // =====================================================================
        // Scenario struct and trait implementations
        // =====================================================================

        #[doc = concat!(stringify!($field), " field with Poseidon2 hash.")]
        pub struct $scenario;

        impl BenchScenario for $scenario {
            type F = F;
            type EF = EF;
            type Mmcs = BaseMmcs;

            const FIELD_NAME: &'static str = $field_name;
            const HASH_NAME: &'static str = "poseidon2";

            fn mmcs() -> Self::Mmcs {
                let perm = create_perm();
                Self::Mmcs::new(MmcsSponge::new(perm.clone()), Compress::new(perm), 0)
            }
        }

        impl PcsScenario for $scenario {
            type Challenger = Challenger;

            const RATE: usize = RATE;

            fn challenger() -> Self::Challenger {
                test_challenger()
            }
        }
    };
}

/// Macro to generate a Keccak-based config module.
///
/// Keccak config is fixed (width=25, rate=17, digest=4), only field varies.
/// Keccak scenarios don't implement PcsScenario (incompatible commitment type).
#[macro_export]
macro_rules! impl_keccak_config {
    (
        scenario: $scenario:ident,
        field: $field:ty,
        ext_degree: $ext_deg:literal,
        field_name: $field_name:literal
    ) => {
        use p3_field::{Field, extension::BinomialExtensionField};
        use p3_keccak::KeccakF;
        use p3_merkle_tree::MerkleTreeMmcs;
        use p3_symmetric::{CompressionFunctionFromHasher, PaddingFreeSponge, SerializingHasher};
        use $crate::configs::BenchScenario;

        // =====================================================================
        // Constants (fixed for Keccak)
        // =====================================================================

        /// Keccak permutation width (fixed).
        pub const WIDTH: usize = 25;

        /// Sponge rate (fixed for Keccak).
        pub const RATE: usize = 17;

        /// Digest size in u64 elements (fixed for Keccak).
        pub const DIGEST: usize = 4;

        // =====================================================================
        // Type aliases
        // =====================================================================

        /// Base field.
        pub type F = $field;

        /// Packed base field for SIMD operations.
        pub type P = <F as Field>::Packing;

        /// Extension field.
        pub type EF = BinomialExtensionField<F, $ext_deg>;

        /// MMCS sponge for Keccak.
        pub type KeccakMmcsSponge = PaddingFreeSponge<KeccakF, WIDTH, RATE, DIGEST>;

        /// Compression function for Keccak.
        pub type KeccakCompress = CompressionFunctionFromHasher<KeccakMmcsSponge, 2, DIGEST>;

        /// Base Merkle tree MMCS for Keccak (with serialization).
        pub type BaseMmcs =
            MerkleTreeMmcs<F, u64, SerializingHasher<KeccakMmcsSponge>, KeccakCompress, 2, DIGEST>;

        // =====================================================================
        // Scenario struct and trait implementation
        // =====================================================================

        #[doc = concat!(stringify!($field), " field with Keccak hash.")]
        pub struct $scenario;

        impl BenchScenario for $scenario {
            type F = F;
            type EF = EF;
            type Mmcs = BaseMmcs;

            const FIELD_NAME: &'static str = $field_name;
            const HASH_NAME: &'static str = "keccak";

            fn mmcs() -> Self::Mmcs {
                let inner = KeccakMmcsSponge::new(KeccakF {});
                Self::Mmcs::new(
                    SerializingHasher::new(inner.clone()),
                    KeccakCompress::new(inner),
                    0,
                )
            }
        }
    };
}

// =============================================================================
// Config modules
// =============================================================================

/// BabyBear + Keccak configuration.
pub mod baby_bear_keccak {
    use p3_baby_bear::BabyBear;

    crate::impl_keccak_config!(
        scenario: BabyBearKeccak,
        field: BabyBear,
        ext_degree: 4,
        field_name: "babybear"
    );
}

/// BabyBear + Poseidon2 configuration.
pub mod baby_bear_poseidon2 {
    use p3_baby_bear::{BabyBear, Poseidon2BabyBear};

    crate::impl_poseidon2_config!(
        scenario: BabyBearPoseidon2,
        field: BabyBear,
        ext_degree: 4,
        perm: Poseidon2BabyBear,
        width: 16,
        rate: 8,
        digest: 8,
        field_name: "babybear"
    );
}

/// Goldilocks + Keccak configuration.
pub mod goldilocks_keccak {
    use p3_goldilocks::Goldilocks;

    crate::impl_keccak_config!(
        scenario: GoldilocksKeccak,
        field: Goldilocks,
        ext_degree: 2,
        field_name: "goldilocks"
    );
}

/// Goldilocks + Poseidon2 configuration.
pub mod goldilocks_poseidon2 {
    use p3_goldilocks::{Goldilocks, Poseidon2Goldilocks};

    crate::impl_poseidon2_config!(
        scenario: GoldilocksPoseidon2,
        field: Goldilocks,
        ext_degree: 2,
        perm: Poseidon2Goldilocks,
        width: 12,
        rate: 8,
        digest: 4,
        field_name: "goldilocks"
    );
}

// Re-export scenario structs at module level
pub use baby_bear_keccak::BabyBearKeccak;
pub use baby_bear_poseidon2::BabyBearPoseidon2;
pub use goldilocks_keccak::GoldilocksKeccak;
pub use goldilocks_poseidon2::GoldilocksPoseidon2;