repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/ies/crypto_box.rs
miden-crypto/src/ies/crypto_box.rs
//! Core cryptographic primitive for Integrated Encryption Scheme (IES). //! //! This module defines the generic `CryptoBox` abstraction that combines a key agreement scheme //! (e.g. K256 ECDH) with an AEAD scheme (e.g. XChaCha20-Poly1305) to provide authenticated //! encryption. use alloc::vec::Vec; use rand::{CryptoRng, RngCore}; use super::IesError; use crate::{Felt, aead::AeadScheme, ecdh::KeyAgreementScheme, utils::zeroize::Zeroizing}; // CRYPTO BOX // ================================================================================================ /// A generic CryptoBox primitive parameterized by key agreement and AEAD schemes. pub(super) struct CryptoBox<K: KeyAgreementScheme, A: AeadScheme> { _phantom: core::marker::PhantomData<(K, A)>, } impl<K: KeyAgreementScheme, A: AeadScheme> CryptoBox<K, A> { // BYTE-SPECIFIC METHODS // -------------------------------------------------------------------------------------------- pub fn seal_bytes_with_associated_data<R: CryptoRng + RngCore>( rng: &mut R, recipient_public_key: &K::PublicKey, plaintext: &[u8], associated_data: &[u8], ) -> Result<(Vec<u8>, K::EphemeralPublicKey), IesError> { let (ephemeral_private, ephemeral_public) = K::generate_ephemeral_keypair(rng); let shared_secret = Zeroizing::new( K::exchange_ephemeral_static(ephemeral_private, recipient_public_key) .map_err(|_| IesError::KeyAgreementFailed)?, ); let encryption_key_bytes = Zeroizing::new( K::extract_key_material(&shared_secret, <A as AeadScheme>::KEY_SIZE) .map_err(|_| IesError::FailedExtractKeyMaterial)?, ); let encryption_key = Zeroizing::new( A::key_from_bytes(&encryption_key_bytes) .map_err(|_| IesError::EncryptionKeyCreationFailed)?, ); let ciphertext = A::encrypt_bytes(&encryption_key, rng, plaintext, associated_data) .map_err(|_| IesError::EncryptionFailed)?; Ok((ciphertext, ephemeral_public)) } pub fn unseal_bytes_with_associated_data( recipient_private_key: &K::SecretKey, ephemeral_public_key: &K::EphemeralPublicKey, ciphertext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, IesError> { let shared_secret = Zeroizing::new( K::exchange_static_ephemeral(recipient_private_key, ephemeral_public_key) .map_err(|_| IesError::KeyAgreementFailed)?, ); let decryption_key_bytes = Zeroizing::new( K::extract_key_material(&shared_secret, <A as AeadScheme>::KEY_SIZE) .map_err(|_| IesError::FailedExtractKeyMaterial)?, ); let decryption_key = Zeroizing::new( A::key_from_bytes(&decryption_key_bytes) .map_err(|_| IesError::EncryptionKeyCreationFailed)?, ); A::decrypt_bytes_with_associated_data(&decryption_key, ciphertext, associated_data) .map_err(|_| IesError::DecryptionFailed) } // ELEMENT-SPECIFIC METHODS // -------------------------------------------------------------------------------------------- pub fn seal_elements_with_associated_data<R: CryptoRng + RngCore>( rng: &mut R, recipient_public_key: &K::PublicKey, plaintext: &[Felt], associated_data: &[Felt], ) -> Result<(Vec<u8>, K::EphemeralPublicKey), IesError> { let (ephemeral_private, ephemeral_public) = K::generate_ephemeral_keypair(rng); let shared_secret = Zeroizing::new( K::exchange_ephemeral_static(ephemeral_private, recipient_public_key) .map_err(|_| IesError::KeyAgreementFailed)?, ); let encryption_key_bytes = Zeroizing::new( K::extract_key_material(&shared_secret, <A as AeadScheme>::KEY_SIZE) .map_err(|_| IesError::FailedExtractKeyMaterial)?, ); let encryption_key = Zeroizing::new( A::key_from_bytes(&encryption_key_bytes) .map_err(|_| IesError::EncryptionKeyCreationFailed)?, ); let ciphertext = A::encrypt_elements(&encryption_key, rng, plaintext, associated_data) .map_err(|_| IesError::EncryptionFailed)?; Ok((ciphertext, ephemeral_public)) } pub fn unseal_elements_with_associated_data( recipient_private_key: &K::SecretKey, ephemeral_public_key: &K::EphemeralPublicKey, ciphertext: &[u8], associated_data: &[Felt], ) -> Result<Vec<Felt>, IesError> { let shared_secret = Zeroizing::new( K::exchange_static_ephemeral(recipient_private_key, ephemeral_public_key) .map_err(|_| IesError::KeyAgreementFailed)?, ); let decryption_key_bytes = Zeroizing::new( K::extract_key_material(&shared_secret, <A as AeadScheme>::KEY_SIZE) .map_err(|_| IesError::FailedExtractKeyMaterial)?, ); let decryption_key = Zeroizing::new( A::key_from_bytes(&decryption_key_bytes) .map_err(|_| IesError::EncryptionKeyCreationFailed)?, ); A::decrypt_elements_with_associated_data(&decryption_key, ciphertext, associated_data) .map_err(|_| IesError::DecryptionFailed) } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/ies/tests.rs
miden-crypto/src/ies/tests.rs
#![cfg(feature = "std")] use alloc::vec::Vec; use proptest::prelude::*; use rand::{RngCore, SeedableRng}; use rand_chacha::ChaCha20Rng; use crate::{ dsa::{ecdsa_k256_keccak::SecretKey, eddsa_25519_sha512::SecretKey as SecretKey25519}, ies::{keys::EphemeralPublicKey, *}, utils::{Deserializable, DeserializationError, Serializable, SliceReader}, }; // CORE TEST INFRASTRUCTURE // ================================================================================================ /// Generates arbitrary byte vectors for property testing fn arbitrary_bytes() -> impl Strategy<Value = Vec<u8>> { prop::collection::vec(any::<u8>(), 0..500) } /// Generates arbitrary field element vectors for property testing fn arbitrary_field_elements() -> impl Strategy<Value = Vec<crate::Felt>> { (1usize..100, any::<u64>()).prop_map(|(len, seed)| { let mut rng = ChaCha20Rng::seed_from_u64(seed); (0..len).map(|_| crate::Felt::new(rng.next_u64())).collect() }) } /// Helper macro for property-based roundtrip testing macro_rules! test_roundtrip { ( $sealing_key:expr, $unsealing_key:expr, $plaintext:expr, $seal_method:ident, $unseal_method:ident ) => { let mut rng = rand::rng(); let sealed = $sealing_key.$seal_method(&mut rng, $plaintext).unwrap(); let decrypted = $unsealing_key.$unseal_method(sealed).unwrap(); prop_assert_eq!($plaintext.clone(), decrypted); }; ( $sealing_key:expr, $unsealing_key:expr, $plaintext:expr, $associated_data:expr, $seal_method:ident, $unseal_method:ident ) => { let mut rng = rand::rng(); let sealed = $sealing_key.$seal_method(&mut rng, $plaintext, $associated_data).unwrap(); let decrypted = $unsealing_key.$unseal_method(sealed, $associated_data).unwrap(); prop_assert_eq!($plaintext.clone(), decrypted); }; } /// Helper macro for basic roundtrip testing macro_rules! test_basic_roundtrip { ( $sealing_key:expr, $unsealing_key:expr, $plaintext:expr, $seal_method:ident, $unseal_method:ident ) => { let mut rng = rand::rng(); let sealed = $sealing_key.$seal_method(&mut rng, $plaintext).unwrap(); let decrypted = $unsealing_key.$unseal_method(sealed).unwrap(); assert_eq!($plaintext, decrypted.as_slice()); }; ( $sealing_key:expr, $unsealing_key:expr, $plaintext:expr, $associated_data:expr, $seal_method:ident, $unseal_method:ident ) => { let mut rng = rand::rng(); let sealed = $sealing_key.$seal_method(&mut rng, $plaintext, $associated_data).unwrap(); let decrypted = $unsealing_key.$unseal_method(sealed, $associated_data).unwrap(); assert_eq!($plaintext, decrypted.as_slice()); }; } // IES SCHEME VARIANT REGISTRY // ================================================================================================ // Each IES variant gets its own dedicated test module with comprehensive coverage // To add a new variant, create a new module following the pattern below /// K256 + XChaCha20-Poly1305 test suite mod k256_xchacha_tests { use super::*; #[test] fn test_k256_xchacha_bytes_roundtrip() { let mut rng = rand::rng(); let plaintext = b"test bytes encryption"; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); test_basic_roundtrip!(sealing_key, unsealing_key, plaintext, seal_bytes, unseal_bytes); } #[test] fn test_k256_xchacha_bytes_with_associated_data() { let mut rng = rand::rng(); let plaintext = b"test bytes with associated data"; let associated_data = b"authentication context"; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, plaintext, associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data ); } #[test] fn test_k256_xchacha_elements_roundtrip() { let mut rng = rand::rng(); let plaintext = vec![crate::Felt::new(42), crate::Felt::new(1337), crate::Felt::new(9999)]; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, seal_elements, unseal_elements ); } #[test] fn test_k256_xchacha_elements_with_associated_data() { let mut rng = rand::rng(); let plaintext = vec![crate::Felt::new(100), crate::Felt::new(200), crate::Felt::new(300)]; let associated_data = vec![crate::Felt::new(999), crate::Felt::new(888)]; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data ); } #[test] fn test_k256_xchacha_invalid_associated_data() { let mut rng = rand::rng(); let plaintext = b"test invalid associated data"; let correct_ad = b"correct context"; let incorrect_ad = b"wrong context"; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let sealed = sealing_key .seal_bytes_with_associated_data(&mut rng, plaintext, correct_ad) .unwrap(); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); let result = unsealing_key.unseal_bytes_with_associated_data(sealed, incorrect_ad); assert!(result.is_err()); } proptest! { #[test] fn prop_k256_xchacha_bytes_comprehensive( plaintext in arbitrary_bytes(), associated_data in arbitrary_bytes() ) { let mut rng = rand::rng(); let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data); } #[test] fn prop_k256_xchacha_elements_comprehensive( plaintext in arbitrary_field_elements(), associated_data in arbitrary_field_elements() ) { let mut rng = rand::rng(); let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data); } #[test] fn prop_k256_xchacha_wrong_key_fails( plaintext in arbitrary_bytes() ) { prop_assume!(!plaintext.is_empty()); let mut rng = rand::rng(); let secret1 = SecretKey::with_rng(&mut rng); let public1 = secret1.public_key(); let secret2 = SecretKey::with_rng(&mut rng); let sealing_key = SealingKey::K256XChaCha20Poly1305(public1); let sealed = sealing_key.seal_bytes(&mut rng, &plaintext).unwrap(); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(secret2); let result = unsealing_key.unseal_bytes(sealed); prop_assert!(result.is_err()); } } } /// X25519 + XChaCha20-Poly1305 test suite mod x25519_xchacha_tests { use super::*; #[test] fn test_x25519_xchacha_bytes_roundtrip() { let mut rng = rand::rng(); let plaintext = b"test bytes encryption"; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); test_basic_roundtrip!(sealing_key, unsealing_key, plaintext, seal_bytes, unseal_bytes); } #[test] fn test_x25519_xchacha_bytes_with_associated_data() { let mut rng = rand::rng(); let plaintext = b"test bytes with associated data"; let associated_data = b"authentication context"; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, plaintext, associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data ); } #[test] fn test_x25519_xchacha_elements_roundtrip() { let mut rng = rand::rng(); let plaintext = vec![crate::Felt::new(42), crate::Felt::new(1337), crate::Felt::new(9999)]; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, seal_elements, unseal_elements ); } #[test] fn test_x25519_xchacha_elements_with_associated_data() { let mut rng = rand::rng(); let plaintext = vec![crate::Felt::new(100), crate::Felt::new(200), crate::Felt::new(300)]; let associated_data = vec![crate::Felt::new(999), crate::Felt::new(888)]; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data ); } #[test] fn test_x25519_xchacha_invalid_associated_data() { let mut rng = rand::rng(); let plaintext = b"test invalid associated data"; let correct_ad = b"correct context"; let incorrect_ad = b"wrong context"; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let sealed = sealing_key .seal_bytes_with_associated_data(&mut rng, plaintext, correct_ad) .unwrap(); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); let result = unsealing_key.unseal_bytes_with_associated_data(sealed, incorrect_ad); assert!(result.is_err()); } proptest! { #[test] fn prop_x25519_xchacha_bytes_comprehensive( plaintext in arbitrary_bytes(), associated_data in arbitrary_bytes() ) { let mut rng = rand::rng(); let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data); } #[test] fn prop_x25519_xchacha_elements_comprehensive( plaintext in arbitrary_field_elements(), associated_data in arbitrary_field_elements() ) { let mut rng = rand::rng(); let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data); } #[test] fn prop_x25519_xchacha_wrong_key_fails( plaintext in arbitrary_bytes() ) { prop_assume!(!plaintext.is_empty()); let mut rng = rand::rng(); let secret1 = SecretKey25519::with_rng(&mut rng); let public1 = secret1.public_key(); let secret2 = SecretKey25519::with_rng(&mut rng); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public1); let sealed = sealing_key.seal_bytes(&mut rng, &plaintext).unwrap(); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret2); let result = unsealing_key.unseal_bytes(sealed); prop_assert!(result.is_err()); } } } /// K256 + AeadRpo test suite mod k256_aead_rpo_tests { use super::*; // BYTES TESTS #[test] fn test_k256_aead_rpo_bytes_roundtrip() { let mut rng = rand::rng(); let plaintext = b"test bytes encryption"; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); test_basic_roundtrip!(sealing_key, unsealing_key, plaintext, seal_bytes, unseal_bytes); } #[test] fn test_k256_aead_rpo_bytes_with_associated_data() { let mut rng = rand::rng(); let plaintext = b"test bytes with associated data"; let associated_data = b"authentication context"; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, plaintext, associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data ); } #[test] fn test_k256_aead_rpo_invalid_associated_data() { let mut rng = rand::rng(); let plaintext = b"test invalid associated data"; let correct_ad = b"correct context"; let incorrect_ad = b"wrong context"; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let sealed = sealing_key .seal_bytes_with_associated_data(&mut rng, plaintext, correct_ad) .unwrap(); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); let result = unsealing_key.unseal_bytes_with_associated_data(sealed, incorrect_ad); assert!(result.is_err()); } // FIELD ELEMENTS TESTS #[test] fn test_k256_aead_rpo_field_elements_roundtrip() { use crate::Felt; let mut rng = rand::rng(); let plaintext = vec![Felt::new(1), Felt::new(2), Felt::new(3)]; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, seal_elements, unseal_elements ); } #[test] fn test_k256_aead_rpo_field_elements_with_associated_data() { use crate::Felt; let mut rng = rand::rng(); let plaintext = vec![Felt::new(10), Felt::new(20)]; let associated_data = vec![Felt::new(100), Felt::new(200)]; let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data ); } proptest! { #[test] fn prop_k256_aead_rpo_bytes_comprehensive( plaintext in arbitrary_bytes(), associated_data in arbitrary_bytes() ) { let mut rng = rand::rng(); let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data); } #[test] fn prop_k256_aead_rpo_field_elements_comprehensive( plaintext in arbitrary_field_elements(), associated_data in arbitrary_field_elements() ) { let mut rng = rand::rng(); let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256AeadRpo(public_key); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data); } #[test] fn prop_k256_aead_rpo_wrong_key_fails( plaintext in arbitrary_bytes() ) { prop_assume!(!plaintext.is_empty()); let mut rng = rand::rng(); let secret1 = SecretKey::with_rng(&mut rng); let public1 = secret1.public_key(); let secret2 = SecretKey::with_rng(&mut rng); let sealing_key = SealingKey::K256AeadRpo(public1); let sealed = sealing_key.seal_bytes(&mut rng, &plaintext).unwrap(); let unsealing_key = UnsealingKey::K256AeadRpo(secret2); let result = unsealing_key.unseal_bytes(sealed); prop_assert!(result.is_err()); } } } /// X25519 + AeadRpo test suite mod x25519_aead_rpo_tests { use super::*; // BYTES TESTS #[test] fn test_x25519_aead_rpo_bytes_roundtrip() { let mut rng = rand::rng(); let plaintext = b"test bytes encryption"; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); test_basic_roundtrip!(sealing_key, unsealing_key, plaintext, seal_bytes, unseal_bytes); } #[test] fn test_x25519_aead_rpo_bytes_with_associated_data() { let mut rng = rand::rng(); let plaintext = b"test bytes with associated data"; let associated_data = b"authentication context"; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, plaintext, associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data ); } #[test] fn test_x25519_aead_rpo_invalid_associated_data() { let mut rng = rand::rng(); let plaintext = b"test invalid associated data"; let correct_ad = b"correct context"; let incorrect_ad = b"wrong context"; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let sealed = sealing_key .seal_bytes_with_associated_data(&mut rng, plaintext, correct_ad) .unwrap(); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); let result = unsealing_key.unseal_bytes_with_associated_data(sealed, incorrect_ad); assert!(result.is_err()); } // FIELD ELEMENTS TESTS #[test] fn test_x25519_aead_rpo_field_elements_roundtrip() { use crate::Felt; let mut rng = rand::rng(); let plaintext = vec![Felt::new(1), Felt::new(2), Felt::new(3)]; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, seal_elements, unseal_elements ); } #[test] fn test_x25519_aead_rpo_field_elements_with_associated_data() { use crate::Felt; let mut rng = rand::rng(); let plaintext = vec![Felt::new(10), Felt::new(20)]; let associated_data = vec![Felt::new(100), Felt::new(200)]; let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); test_basic_roundtrip!( sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data ); } proptest! { #[test] fn prop_x25519_aead_rpo_bytes_comprehensive( plaintext in arbitrary_bytes(), associated_data in arbitrary_bytes() ) { let mut rng = rand::rng(); let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_bytes_with_associated_data, unseal_bytes_with_associated_data); } #[test] fn prop_x25519_aead_rpo_field_elements_comprehensive( plaintext in arbitrary_field_elements(), associated_data in arbitrary_field_elements() ) { let mut rng = rand::rng(); let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519AeadRpo(public_key); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key); test_roundtrip!(sealing_key, unsealing_key, &plaintext, &associated_data, seal_elements_with_associated_data, unseal_elements_with_associated_data); } #[test] fn prop_x25519_aead_rpo_wrong_key_fails( plaintext in arbitrary_bytes() ) { prop_assume!(!plaintext.is_empty()); let mut rng = rand::rng(); let secret1 = SecretKey25519::with_rng(&mut rng); let public1 = secret1.public_key(); let secret2 = SecretKey25519::with_rng(&mut rng); let sealing_key = SealingKey::X25519AeadRpo(public1); let sealed = sealing_key.seal_bytes(&mut rng, &plaintext).unwrap(); let unsealing_key = UnsealingKey::X25519AeadRpo(secret2); let result = unsealing_key.unseal_bytes(sealed); prop_assert!(result.is_err()); } } } // CROSS-SCHEME COMPATIBILITY TESTS // ================================================================================================ // These tests verify scheme mismatch detection and security properties /// Tests scheme mismatch detection between different IES variants mod scheme_compatibility_tests { use super::*; #[test] fn test_scheme_mismatch_k256_xchacha_vs_aead_rpo() { let mut rng = rand::rng(); let plaintext = b"test scheme mismatch"; // Seal with K256XChaCha20Poly1305 let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let sealed = sealing_key.seal_bytes(&mut rng, plaintext).unwrap(); // Try to unseal with K256AeadRpo (should fail) let secret_key2 = SecretKey::with_rng(&mut rng); let unsealing_key = UnsealingKey::K256AeadRpo(secret_key2); let result = unsealing_key.unseal_bytes(sealed); assert!(result.is_err()); } #[test] fn test_scheme_mismatch_x25519_xchacha_vs_aead_rpo() { let mut rng = rand::rng(); let plaintext = b"test scheme mismatch"; // Seal with X25519XChaCha20Poly1305 let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let sealed = sealing_key.seal_bytes(&mut rng, plaintext).unwrap(); // Try to unseal with X25519AeadRpo (should fail) let secret_key2 = SecretKey25519::with_rng(&mut rng); let unsealing_key = UnsealingKey::X25519AeadRpo(secret_key2); let result = unsealing_key.unseal_bytes(sealed); assert!(result.is_err()); } #[test] fn test_cross_curve_mismatch_k256_vs_x25519() { let mut rng = rand::rng(); let plaintext = b"test cross-curve mismatch"; // Seal with K256XChaCha20Poly1305 let secret_k256 = SecretKey::with_rng(&mut rng); let public_k256 = secret_k256.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_k256); let sealed = sealing_key.seal_bytes(&mut rng, plaintext).unwrap(); // Try to unseal with X25519XChaCha20Poly1305 (should fail) let secret_x25519 = SecretKey25519::with_rng(&mut rng); let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_x25519); let result = unsealing_key.unseal_bytes(sealed); assert!(result.is_err()); } proptest! { #[test] fn prop_general_scheme_mismatch_detection( plaintext in arbitrary_bytes() ) { let mut rng = rand::rng(); // Create keys for different schemes let secret_k256 = SecretKey::with_rng(&mut rng); let public_k256 = secret_k256.public_key(); let secret_x25519 = SecretKey25519::with_rng(&mut rng); // Seal with K256XChaCha20Poly1305 let sealing_key = SealingKey::K256XChaCha20Poly1305(public_k256); let sealed = sealing_key.seal_bytes(&mut rng, &plaintext).unwrap(); // Try to unseal with X25519XChaCha20Poly1305 - should fail let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_x25519); let result = unsealing_key.unseal_bytes(sealed); prop_assert!(result.is_err()); } } } // PROTOCOL-LEVEL TESTS // ================================================================================================ // These tests verify protocol-level functionality like serialization and message format /// Tests for IES protocol-level functionality mod protocol_tests { use super::*; #[test] fn test_ephemeral_key_serialization_k256() { let mut rng = rand::rng(); let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let sealed = sealing_key.seal_bytes(&mut rng, b"test").unwrap(); // Extract ephemeral key from sealed message let ephemeral_bytes = sealed.ephemeral_key.to_bytes(); let scheme = sealed.ephemeral_key.scheme(); // Deserialize and compare let reconstructed = EphemeralPublicKey::from_bytes(scheme, &ephemeral_bytes).unwrap(); assert_eq!(sealed.ephemeral_key, reconstructed); } #[test] fn test_ephemeral_key_serialization_x25519() { let mut rng = rand::rng(); let secret_key = SecretKey25519::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); let sealed = sealing_key.seal_bytes(&mut rng, b"test").unwrap(); // Extract ephemeral key from sealed message let ephemeral_bytes = sealed.ephemeral_key.to_bytes(); let scheme = sealed.ephemeral_key.scheme(); // Deserialize and compare let reconstructed = EphemeralPublicKey::from_bytes(scheme, &ephemeral_bytes).unwrap(); assert_eq!(sealed.ephemeral_key, reconstructed); } proptest! { #[test] fn prop_sealed_message_format_consistency( plaintext in arbitrary_bytes() ) { let mut rng = rand::rng(); let secret_key = SecretKey::with_rng(&mut rng); let public_key = secret_key.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(public_key); let sealed = sealing_key.seal_bytes(&mut rng, &plaintext).unwrap(); // Verify scheme consistency let scheme_from_key = sealed.ephemeral_key.scheme(); let scheme_from_message = sealed.scheme(); prop_assert_eq!(scheme_from_key, scheme_from_message); // Verify scheme name consistency prop_assert_eq!(scheme_from_key.name(), sealed.scheme_name()); } } // SEALED MESSAGE SERIALIZATION ROUND-TRIP TESTS (BYTES) // -------------------------------------------------------------------------------------------- #[test] fn test_sealed_message_serialization_roundtrip_k256_xchacha() { let mut rng = rand::rng(); let sk = crate::dsa::ecdsa_k256_keccak::SecretKey::with_rng(&mut rng); let pk = sk.public_key(); let sealing_key = SealingKey::K256XChaCha20Poly1305(pk); let unsealing_key = UnsealingKey::K256XChaCha20Poly1305(sk); let plaintext = b"serialization roundtrip"; let sealed = sealing_key.seal_bytes(&mut rng, plaintext).unwrap(); let before = sealed.scheme_name(); let bytes = sealed.to_bytes(); let sealed2 = <SealedMessage as crate::utils::Deserializable>::read_from_bytes(&bytes).unwrap(); let after = sealed2.scheme_name(); assert_eq!(before, after); let opened = unsealing_key.unseal_bytes(sealed2).unwrap(); assert_eq!(opened.as_slice(), plaintext); } #[test] fn test_sealed_message_serialization_roundtrip_x25519_xchacha() { let mut rng = rand::rng(); let sk = crate::dsa::eddsa_25519_sha512::SecretKey::with_rng(&mut rng); let pk = sk.public_key(); let sealing_key = SealingKey::X25519XChaCha20Poly1305(pk);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
true
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/ies/mod.rs
miden-crypto/src/ies/mod.rs
//! Integrated Encryption Scheme (IES) utilities. //! //! This module combines elliptic-curve Diffie–Hellman (ECDH) key agreement with authenticated //! encryption (AEAD) to provide sealed boxes that offer confidentiality and integrity for messages. //! It exposes a simple API via [`SealingKey`], [`UnsealingKey`], [`SealedMessage`], and //! [`IesError`]. //! //! # Examples //! //! ``` //! use miden_crypto::{ //! dsa::eddsa_25519_sha512::SecretKey, //! ies::{SealingKey, UnsealingKey}, //! }; //! use rand::rng; //! //! let mut rng = rng(); //! let secret_key = SecretKey::with_rng(&mut rng); //! let public_key = secret_key.public_key(); //! //! let sealing_key = SealingKey::X25519XChaCha20Poly1305(public_key); //! let unsealing_key = UnsealingKey::X25519XChaCha20Poly1305(secret_key); //! //! let sealed = sealing_key.seal_bytes(&mut rng, b"hello world").unwrap(); //! let opened = unsealing_key.unseal_bytes(sealed).unwrap(); //! //! assert_eq!(opened.as_slice(), b"hello world"); //! ``` mod crypto_box; mod keys; mod message; #[cfg(test)] mod tests; pub use keys::{SealingKey, UnsealingKey}; pub use message::SealedMessage; use thiserror::Error; // IES SCHEME // ================================================================================================ /// Supported schemes for IES #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum IesScheme { K256XChaCha20Poly1305 = 0, X25519XChaCha20Poly1305 = 1, K256AeadRpo = 2, X25519AeadRpo = 3, } impl TryFrom<u8> for IesScheme { type Error = IesError; fn try_from(value: u8) -> Result<Self, Self::Error> { match value { 0 => Ok(IesScheme::K256XChaCha20Poly1305), 1 => Ok(IesScheme::X25519XChaCha20Poly1305), 2 => Ok(IesScheme::K256AeadRpo), 3 => Ok(IesScheme::X25519AeadRpo), _ => Err(IesError::UnsupportedScheme), } } } impl From<IesScheme> for u8 { fn from(algo: IesScheme) -> Self { algo as u8 } } impl core::fmt::Display for IesScheme { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.name()) } } impl IesScheme { pub fn name(self) -> &'static str { match self { IesScheme::K256XChaCha20Poly1305 => "K256+XChaCha20-Poly1305", IesScheme::X25519XChaCha20Poly1305 => "X25519+XChaCha20-Poly1305", IesScheme::K256AeadRpo => "K256+AeadRpo", IesScheme::X25519AeadRpo => "X25519+AeadRpo", } } } // IES ERROR // ================================================================================================ /// Error type for the Integrated Encryption Scheme (IES) #[derive(Debug, Error)] pub enum IesError { #[error("key agreement failed")] KeyAgreementFailed, #[error("encryption failed")] EncryptionFailed, #[error("decryption failed")] DecryptionFailed, #[error("invalid key size")] InvalidKeySize, #[error("invalid nonce")] InvalidNonce, #[error("ephemeral public key deserialization failed")] EphemeralPublicKeyDeserializationFailed, #[error("scheme mismatch")] SchemeMismatch, #[error("unsupported scheme")] UnsupportedScheme, #[error("failed to extract key material for encryption/decryption")] FailedExtractKeyMaterial, #[error("failed to construct the encryption/decryption key from the provided bytes")] EncryptionKeyCreationFailed, }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/ies/message.rs
miden-crypto/src/ies/message.rs
use alloc::vec::Vec; use core::convert::TryFrom; use super::{IesScheme, keys::EphemeralPublicKey}; use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable}; // SEALED MESSAGE // ================================================================================================ /// A sealed message containing encrypted data #[derive(Debug, Clone, PartialEq, Eq)] pub struct SealedMessage { /// Ephemeral public key (determines scheme and provides key material) pub(super) ephemeral_key: EphemeralPublicKey, /// Encrypted ciphertext with authentication tag and nonce pub(super) ciphertext: Vec<u8>, } impl SealedMessage { /// Returns the scheme used to create this sealed message. pub(super) fn scheme(&self) -> IesScheme { self.ephemeral_key.scheme() } /// Returns the scheme name used to create this sealed message. pub fn scheme_name(&self) -> &'static str { self.scheme().name() } /// Returns the byte representation of this sealed message. pub fn to_bytes(&self) -> Vec<u8> { <Self as Serializable>::to_bytes(self) } } impl Serializable for SealedMessage { fn write_into<W: ByteWriter>(&self, target: &mut W) { let scheme = self.scheme(); target.write_u8(scheme as u8); self.ephemeral_key.to_bytes().write_into(target); self.ciphertext.write_into(target); } } impl Deserializable for SealedMessage { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let scheme = match IesScheme::try_from(source.read_u8()?) { Ok(a) => a, Err(_) => { return Err(DeserializationError::InvalidValue("Unsupported scheme".into())); }, }; let eph_key_bytes = Vec::<u8>::read_from(source)?; let ephemeral_key = EphemeralPublicKey::from_bytes(scheme, &eph_key_bytes).map_err(|e| { DeserializationError::InvalidValue(format!("Invalid ephemeral key: {e}")) })?; let ciphertext = Vec::<u8>::read_from(source)?; Ok(Self { ephemeral_key, ciphertext }) } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/ies/keys.rs
miden-crypto/src/ies/keys.rs
use alloc::vec::Vec; use core::fmt; use rand::{CryptoRng, RngCore}; use super::{IesError, IesScheme, crypto_box::CryptoBox, message::SealedMessage}; use crate::{ Felt, aead::{aead_rpo::AeadRpo, xchacha::XChaCha}, ecdh::{KeyAgreementScheme, k256::K256, x25519::X25519}, utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable}, }; // TYPE ALIASES // ================================================================================================ /// Instantiation of sealed box using K256 + XChaCha20Poly1305 type K256XChaCha20Poly1305 = CryptoBox<K256, XChaCha>; /// Instantiation of sealed box using X25519 + XChaCha20Poly1305 type X25519XChaCha20Poly1305 = CryptoBox<X25519, XChaCha>; /// Instantiation of sealed box using K256 + AeadRPO type K256AeadRpo = CryptoBox<K256, AeadRpo>; /// Instantiation of sealed box using X25519 + AeadRPO type X25519AeadRpo = CryptoBox<X25519, AeadRpo>; // HELPER MACROS // ================================================================================================ /// Generates seal_bytes_with_associated_data method implementation macro_rules! impl_seal_bytes_with_associated_data { ($($variant:path => $crypto_box:ty, $ephemeral_variant:path;)*) => { /// Seals the provided plaintext (represented as bytes) and associated data with this /// sealing key. /// /// The returned message can be unsealed with the [UnsealingKey] associated with this /// sealing key. pub fn seal_bytes_with_associated_data<R: CryptoRng + RngCore>( &self, rng: &mut R, plaintext: &[u8], associated_data: &[u8], ) -> Result<SealedMessage, IesError> { match self { $( $variant(key) => { let (ciphertext, ephemeral) = <$crypto_box>::seal_bytes_with_associated_data( rng, key, plaintext, associated_data, )?; Ok(SealedMessage { ephemeral_key: $ephemeral_variant(ephemeral), ciphertext, }) } )* } } }; } /// Generates seal_elements_with_associated_data method implementation macro_rules! impl_seal_elements_with_associated_data { ($($variant:path => $crypto_box:ty, $ephemeral_variant:path;)*) => { /// Seals the provided plaintext (represented as filed elements) and associated data with /// this sealing key. /// /// The returned message can be unsealed with the [UnsealingKey] associated with this /// sealing key. pub fn seal_elements_with_associated_data<R: CryptoRng + RngCore>( &self, rng: &mut R, plaintext: &[Felt], associated_data: &[Felt], ) -> Result<SealedMessage, IesError> { match self { $( $variant(key) => { let (ciphertext, ephemeral) = <$crypto_box>::seal_elements_with_associated_data( rng, key, plaintext, associated_data, )?; Ok(SealedMessage { ephemeral_key: $ephemeral_variant(ephemeral), ciphertext, }) } )* } } }; } /// Generates unseal_bytes_with_associated_data method implementation macro_rules! impl_unseal_bytes_with_associated_data { ($($variant:path => $crypto_box:ty, $ephemeral_variant:path;)*) => { /// Unseals the provided message using this unsealing key and returns the plaintext as bytes. /// /// # Errors /// Returns an error if: /// - The message was not sealed as bytes (i.e., if it was sealed using `seal_elements()` /// or `seal_elements_with_associated_data()`) /// - The scheme used to seal the message does not match this unsealing key's scheme /// - Decryption or authentication fails pub fn unseal_bytes_with_associated_data( &self, sealed_message: SealedMessage, associated_data: &[u8], ) -> Result<Vec<u8>, IesError> { // Check scheme compatibility using constant-time comparison let self_algo = self.scheme() as u8; let msg_algo = sealed_message.ephemeral_key.scheme() as u8; let compatible = self_algo == msg_algo; if !compatible { return Err(IesError::SchemeMismatch); } let SealedMessage { ephemeral_key, ciphertext } = sealed_message; match (self, ephemeral_key) { $( ($variant(key), $ephemeral_variant(ephemeral)) => { <$crypto_box>::unseal_bytes_with_associated_data(key, &ephemeral, &ciphertext, associated_data) } )* _ => Err(IesError::SchemeMismatch), } } }; } /// Generates unseal_elements_with_associated_data method implementation macro_rules! impl_unseal_elements_with_associated_data { ($($variant:path => $crypto_box:ty, $ephemeral_variant:path;)*) => { /// Unseals the provided message using this unsealing key and returns the plaintext as field elements. /// /// # Errors /// Returns an error if: /// - The message was not sealed as elements (i.e., if it was sealed using `seal_bytes()` /// or `seal_bytes_with_associated_data()`) /// - The scheme used to seal the message does not match this unsealing key's scheme /// - Decryption or authentication fails pub fn unseal_elements_with_associated_data( &self, sealed_message: SealedMessage, associated_data: &[Felt], ) -> Result<Vec<Felt>, IesError> { // Check scheme compatibility let self_algo = self.scheme() as u8; let msg_algo = sealed_message.ephemeral_key.scheme() as u8; let compatible = self_algo == msg_algo; if !compatible { return Err(IesError::SchemeMismatch); } let SealedMessage { ephemeral_key, ciphertext } = sealed_message; match (self, ephemeral_key) { $( ($variant(key), $ephemeral_variant(ephemeral)) => { <$crypto_box>::unseal_elements_with_associated_data(key, &ephemeral, &ciphertext, associated_data) } )* _ => Err(IesError::SchemeMismatch), } } }; } // SEALING KEY // ================================================================================================ /// Public key for sealing messages to a recipient. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SealingKey { K256XChaCha20Poly1305(crate::dsa::ecdsa_k256_keccak::PublicKey), X25519XChaCha20Poly1305(crate::dsa::eddsa_25519_sha512::PublicKey), K256AeadRpo(crate::dsa::ecdsa_k256_keccak::PublicKey), X25519AeadRpo(crate::dsa::eddsa_25519_sha512::PublicKey), } impl SealingKey { /// Returns scheme identifier for this sealing key. pub fn scheme(&self) -> IesScheme { match self { SealingKey::K256XChaCha20Poly1305(_) => IesScheme::K256XChaCha20Poly1305, SealingKey::X25519XChaCha20Poly1305(_) => IesScheme::X25519XChaCha20Poly1305, SealingKey::K256AeadRpo(_) => IesScheme::K256AeadRpo, SealingKey::X25519AeadRpo(_) => IesScheme::X25519AeadRpo, } } /// Seals the provided plaintext (represented as bytes) with this sealing key. /// /// The returned message can be unsealed with the [UnsealingKey] associated with this sealing /// key. pub fn seal_bytes<R: CryptoRng + RngCore>( &self, rng: &mut R, plaintext: &[u8], ) -> Result<SealedMessage, IesError> { self.seal_bytes_with_associated_data(rng, plaintext, &[]) } impl_seal_bytes_with_associated_data! { SealingKey::K256XChaCha20Poly1305 => K256XChaCha20Poly1305, EphemeralPublicKey::K256XChaCha20Poly1305; SealingKey::X25519XChaCha20Poly1305 => X25519XChaCha20Poly1305, EphemeralPublicKey::X25519XChaCha20Poly1305; SealingKey::K256AeadRpo => K256AeadRpo, EphemeralPublicKey::K256AeadRpo; SealingKey::X25519AeadRpo => X25519AeadRpo, EphemeralPublicKey::X25519AeadRpo; } /// Seals the provided plaintext (represented as filed elements) with this sealing key. /// /// The returned message can be unsealed with the [UnsealingKey] associated with this sealing /// key. pub fn seal_elements<R: CryptoRng + RngCore>( &self, rng: &mut R, plaintext: &[Felt], ) -> Result<SealedMessage, IesError> { self.seal_elements_with_associated_data(rng, plaintext, &[]) } impl_seal_elements_with_associated_data! { SealingKey::K256XChaCha20Poly1305 => K256XChaCha20Poly1305, EphemeralPublicKey::K256XChaCha20Poly1305; SealingKey::X25519XChaCha20Poly1305 => X25519XChaCha20Poly1305, EphemeralPublicKey::X25519XChaCha20Poly1305; SealingKey::K256AeadRpo => K256AeadRpo, EphemeralPublicKey::K256AeadRpo; SealingKey::X25519AeadRpo => X25519AeadRpo, EphemeralPublicKey::X25519AeadRpo; } } impl fmt::Display for SealingKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} sealing key", self.scheme()) } } impl Serializable for SealingKey { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u8(self.scheme().into()); match self { SealingKey::K256XChaCha20Poly1305(key) => key.write_into(target), SealingKey::X25519XChaCha20Poly1305(key) => key.write_into(target), SealingKey::K256AeadRpo(key) => key.write_into(target), SealingKey::X25519AeadRpo(key) => key.write_into(target), } } } impl Deserializable for SealingKey { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let scheme = IesScheme::try_from(source.read_u8()?) .map_err(|_| DeserializationError::InvalidValue("Unsupported IES scheme".into()))?; match scheme { IesScheme::K256XChaCha20Poly1305 => { let key = crate::dsa::ecdsa_k256_keccak::PublicKey::read_from(source)?; Ok(SealingKey::K256XChaCha20Poly1305(key)) }, IesScheme::X25519XChaCha20Poly1305 => { let key = crate::dsa::eddsa_25519_sha512::PublicKey::read_from(source)?; Ok(SealingKey::X25519XChaCha20Poly1305(key)) }, IesScheme::K256AeadRpo => { let key = crate::dsa::ecdsa_k256_keccak::PublicKey::read_from(source)?; Ok(SealingKey::K256AeadRpo(key)) }, IesScheme::X25519AeadRpo => { let key = crate::dsa::eddsa_25519_sha512::PublicKey::read_from(source)?; Ok(SealingKey::X25519AeadRpo(key)) }, } } } // UNSEALING KEY // ================================================================================================ /// Secret key for unsealing messages. pub enum UnsealingKey { K256XChaCha20Poly1305(crate::dsa::ecdsa_k256_keccak::SecretKey), X25519XChaCha20Poly1305(crate::dsa::eddsa_25519_sha512::SecretKey), K256AeadRpo(crate::dsa::ecdsa_k256_keccak::SecretKey), X25519AeadRpo(crate::dsa::eddsa_25519_sha512::SecretKey), } impl UnsealingKey { /// Returns scheme identifier for this unsealing key. pub fn scheme(&self) -> IesScheme { match self { UnsealingKey::K256XChaCha20Poly1305(_) => IesScheme::K256XChaCha20Poly1305, UnsealingKey::X25519XChaCha20Poly1305(_) => IesScheme::X25519XChaCha20Poly1305, UnsealingKey::K256AeadRpo(_) => IesScheme::K256AeadRpo, UnsealingKey::X25519AeadRpo(_) => IesScheme::X25519AeadRpo, } } /// Returns scheme name for this unsealing key. pub fn scheme_name(&self) -> &'static str { self.scheme().name() } /// Unseals the provided message using this unsealing key. /// /// The message must have been sealed as bytes (i.e., using `seal_bytes()` or /// `seal_bytes_with_associated_data()` method), otherwise an error will be returned. pub fn unseal_bytes(&self, sealed_message: SealedMessage) -> Result<Vec<u8>, IesError> { self.unseal_bytes_with_associated_data(sealed_message, &[]) } impl_unseal_bytes_with_associated_data! { UnsealingKey::K256XChaCha20Poly1305 => K256XChaCha20Poly1305, EphemeralPublicKey::K256XChaCha20Poly1305; UnsealingKey::X25519XChaCha20Poly1305 => X25519XChaCha20Poly1305, EphemeralPublicKey::X25519XChaCha20Poly1305; UnsealingKey::K256AeadRpo => K256AeadRpo, EphemeralPublicKey::K256AeadRpo; UnsealingKey::X25519AeadRpo => X25519AeadRpo, EphemeralPublicKey::X25519AeadRpo; } /// Unseals the provided message using this unsealing key. /// /// The message must have been sealed as elements (i.e., using `seal_elements()` or /// `seal_elements_with_associated_data()` method), otherwise an error will be returned. pub fn unseal_elements(&self, sealed_message: SealedMessage) -> Result<Vec<Felt>, IesError> { self.unseal_elements_with_associated_data(sealed_message, &[]) } impl_unseal_elements_with_associated_data! { UnsealingKey::K256XChaCha20Poly1305 => K256XChaCha20Poly1305, EphemeralPublicKey::K256XChaCha20Poly1305; UnsealingKey::X25519XChaCha20Poly1305 => X25519XChaCha20Poly1305, EphemeralPublicKey::X25519XChaCha20Poly1305; UnsealingKey::K256AeadRpo => K256AeadRpo, EphemeralPublicKey::K256AeadRpo; UnsealingKey::X25519AeadRpo => X25519AeadRpo, EphemeralPublicKey::X25519AeadRpo; } } impl fmt::Display for UnsealingKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} unsealing key", self.scheme()) } } impl Serializable for UnsealingKey { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u8(self.scheme().into()); match self { UnsealingKey::K256XChaCha20Poly1305(key) => key.write_into(target), UnsealingKey::X25519XChaCha20Poly1305(key) => key.write_into(target), UnsealingKey::K256AeadRpo(key) => key.write_into(target), UnsealingKey::X25519AeadRpo(key) => key.write_into(target), } } } impl Deserializable for UnsealingKey { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let scheme = IesScheme::try_from(source.read_u8()?) .map_err(|_| DeserializationError::InvalidValue("Unsupported IES scheme".into()))?; match scheme { IesScheme::K256XChaCha20Poly1305 => { let key = crate::dsa::ecdsa_k256_keccak::SecretKey::read_from(source)?; Ok(UnsealingKey::K256XChaCha20Poly1305(key)) }, IesScheme::X25519XChaCha20Poly1305 => { let key = crate::dsa::eddsa_25519_sha512::SecretKey::read_from(source)?; Ok(UnsealingKey::X25519XChaCha20Poly1305(key)) }, IesScheme::K256AeadRpo => { let key = crate::dsa::ecdsa_k256_keccak::SecretKey::read_from(source)?; Ok(UnsealingKey::K256AeadRpo(key)) }, IesScheme::X25519AeadRpo => { let key = crate::dsa::eddsa_25519_sha512::SecretKey::read_from(source)?; Ok(UnsealingKey::X25519AeadRpo(key)) }, } } } // EPHEMERAL PUBLIC KEY // ================================================================================================ /// Ephemeral public key, part of sealed messages #[derive(Debug, Clone, PartialEq, Eq)] pub(super) enum EphemeralPublicKey { K256XChaCha20Poly1305(crate::ecdh::k256::EphemeralPublicKey), X25519XChaCha20Poly1305(crate::ecdh::x25519::EphemeralPublicKey), K256AeadRpo(crate::ecdh::k256::EphemeralPublicKey), X25519AeadRpo(crate::ecdh::x25519::EphemeralPublicKey), } impl EphemeralPublicKey { /// Get scheme identifier for this ephemeral key pub fn scheme(&self) -> IesScheme { match self { EphemeralPublicKey::K256XChaCha20Poly1305(_) => IesScheme::K256XChaCha20Poly1305, EphemeralPublicKey::X25519XChaCha20Poly1305(_) => IesScheme::X25519XChaCha20Poly1305, EphemeralPublicKey::K256AeadRpo(_) => IesScheme::K256AeadRpo, EphemeralPublicKey::X25519AeadRpo(_) => IesScheme::X25519AeadRpo, } } /// Serialize to bytes pub fn to_bytes(&self) -> Vec<u8> { match self { EphemeralPublicKey::K256XChaCha20Poly1305(key) => key.to_bytes(), EphemeralPublicKey::X25519XChaCha20Poly1305(key) => key.to_bytes(), EphemeralPublicKey::K256AeadRpo(key) => key.to_bytes(), EphemeralPublicKey::X25519AeadRpo(key) => key.to_bytes(), } } /// Deserialize from bytes with explicit scheme pub fn from_bytes(scheme: IesScheme, bytes: &[u8]) -> Result<Self, IesError> { match scheme { IesScheme::K256XChaCha20Poly1305 => { let key = <K256 as KeyAgreementScheme>::EphemeralPublicKey::read_from_bytes(bytes) .map_err(|_| IesError::EphemeralPublicKeyDeserializationFailed)?; Ok(EphemeralPublicKey::K256XChaCha20Poly1305(key)) }, IesScheme::K256AeadRpo => { let key = <K256 as KeyAgreementScheme>::EphemeralPublicKey::read_from_bytes(bytes) .map_err(|_| IesError::EphemeralPublicKeyDeserializationFailed)?; Ok(EphemeralPublicKey::K256AeadRpo(key)) }, IesScheme::X25519XChaCha20Poly1305 => { let key = <X25519 as KeyAgreementScheme>::EphemeralPublicKey::read_from_bytes(bytes) .map_err(|_| IesError::EphemeralPublicKeyDeserializationFailed)?; Ok(EphemeralPublicKey::X25519XChaCha20Poly1305(key)) }, IesScheme::X25519AeadRpo => { let key = <X25519 as KeyAgreementScheme>::EphemeralPublicKey::read_from_bytes(bytes) .map_err(|_| IesError::EphemeralPublicKeyDeserializationFailed)?; Ok(EphemeralPublicKey::X25519AeadRpo(key)) }, } } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/rand/test_utils.rs
miden-crypto/src/rand/test_utils.rs
//! Test and benchmark utilities for generating random data. //! //! This module provides helper functions for tests and benchmarks that need //! random data generation. These functions replace the functionality previously //! provided by winter-rand-utils. use alloc::vec::Vec; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha20Rng; use crate::rand::Randomizable; /// Generates a random value of type T using the thread-local random number generator. /// /// # Examples /// ``` /// # use miden_crypto::rand::test_utils::rand_value; /// let x: u64 = rand_value(); /// let y: u128 = rand_value(); /// ``` #[cfg(feature = "std")] pub fn rand_value<T: Randomizable>() -> T { let mut rng = rand::rng(); let mut bytes = vec![0u8; T::VALUE_SIZE]; rng.fill(&mut bytes[..]); T::from_random_bytes(&bytes).expect("failed to generate random value") } /// Generates a random array of type T with N elements. /// /// # Examples /// ``` /// # use miden_crypto::rand::test_utils::rand_array; /// let arr: [u64; 4] = rand_array(); /// ``` #[cfg(feature = "std")] pub fn rand_array<T: Randomizable, const N: usize>() -> [T; N] { core::array::from_fn(|_| rand_value()) } /// Generates a random vector of type T with the specified length. /// /// # Examples /// ``` /// # use miden_crypto::rand::test_utils::rand_vector; /// let vec: Vec<u64> = rand_vector(100); /// ``` #[cfg(feature = "std")] pub fn rand_vector<T: Randomizable>(length: usize) -> Vec<T> { (0..length).map(|_| rand_value()).collect() } /// Generates a deterministic array using a PRNG seeded with the provided seed. /// /// This function uses ChaCha20 PRNG for deterministic random generation, which is /// useful for reproducible tests and benchmarks. /// /// # Examples /// ``` /// # use miden_crypto::rand::test_utils::prng_array; /// let seed = [0u8; 32]; /// let arr: [u64; 4] = prng_array(seed); /// ``` pub fn prng_array<T: Randomizable, const N: usize>(seed: [u8; 32]) -> [T; N] { let mut rng = ChaCha20Rng::from_seed(seed); core::array::from_fn(|_| { let mut bytes = vec![0u8; T::VALUE_SIZE]; rng.fill(&mut bytes[..]); T::from_random_bytes(&bytes).expect("failed to generate random value") }) } /// Generates a deterministic vector using a PRNG seeded with the provided seed. /// /// # Examples /// ``` /// # use miden_crypto::rand::test_utils::prng_vector; /// let seed = [0u8; 32]; /// let vec: Vec<u64> = prng_vector(seed, 100); /// ``` pub fn prng_vector<T: Randomizable>(seed: [u8; 32], length: usize) -> Vec<T> { let mut rng = ChaCha20Rng::from_seed(seed); (0..length) .map(|_| { let mut bytes = vec![0u8; T::VALUE_SIZE]; rng.fill(&mut bytes[..]); T::from_random_bytes(&bytes).expect("failed to generate random value") }) .collect() }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/rand/rpo.rs
miden-crypto/src/rand/rpo.rs
use alloc::{string::ToString, vec::Vec}; use p3_field::{ExtensionField, PrimeField64}; use rand_core::impls; use super::{Felt, FeltRng, RngCore}; use crate::{ Word, ZERO, hash::rpo::Rpo256, utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable}, }; // CONSTANTS // ================================================================================================ const STATE_WIDTH: usize = Rpo256::STATE_WIDTH; const RATE_START: usize = Rpo256::RATE_RANGE.start; const RATE_END: usize = Rpo256::RATE_RANGE.end; const HALF_RATE_WIDTH: usize = (Rpo256::RATE_RANGE.end - Rpo256::RATE_RANGE.start) / 2; // RPO RANDOM COIN // ================================================================================================ /// A simplified version of the `SPONGE_PRG` reseedable pseudo-random number generator algorithm /// described in <https://eprint.iacr.org/2011/499.pdf>. /// /// The simplification is related to the following facts: /// 1. A call to the reseed method implies one and only one call to the permutation function. This /// is possible because in our case we never reseed with more than 4 field elements. /// 2. As a result of the previous point, we don't make use of an input buffer to accumulate seed /// material. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RpoRandomCoin { state: [Felt; STATE_WIDTH], current: usize, } impl RpoRandomCoin { /// Returns a new [RpoRandomCoin] initialize with the specified seed. pub fn new(seed: Word) -> Self { let mut state = [ZERO; STATE_WIDTH]; for i in 0..HALF_RATE_WIDTH { state[RATE_START + i] += seed[i]; } // Absorb Rpo256::apply_permutation(&mut state); RpoRandomCoin { state, current: RATE_START } } /// Returns an [RpoRandomCoin] instantiated from the provided components. /// /// # Panics /// Panics if `current` is smaller than 4 or greater than or equal to 12. pub fn from_parts(state: [Felt; STATE_WIDTH], current: usize) -> Self { assert!( (RATE_START..RATE_END).contains(&current), "current value outside of valid range" ); Self { state, current } } /// Returns components of this random coin. pub fn into_parts(self) -> ([Felt; STATE_WIDTH], usize) { (self.state, self.current) } /// Fills `dest` with random data. pub fn fill_bytes(&mut self, dest: &mut [u8]) { <Self as RngCore>::fill_bytes(self, dest) } /// Draws a random base field element from the random coin. /// /// This method applies the Rpo256 permutation when the rate portion of the state is exhausted, /// then returns the next element from the rate portion. pub fn draw_basefield(&mut self) -> Felt { if self.current == RATE_END { Rpo256::apply_permutation(&mut self.state); self.current = RATE_START; } self.current += 1; self.state[self.current - 1] } /// Draws a random field element. /// /// This is an alias for [Self::draw_basefield]. pub fn draw(&mut self) -> Felt { self.draw_basefield() } /// Draws a random extension field element. /// /// The extension field element is constructed by drawing `E::DIMENSION` base field elements /// and interpreting them as basis coefficients. pub fn draw_ext_field<E: ExtensionField<Felt>>(&mut self) -> E { let ext_degree = E::DIMENSION; let mut result = vec![ZERO; ext_degree]; for r in result.iter_mut().take(ext_degree) { *r = self.draw_basefield(); } E::from_basis_coefficients_slice(&result).expect("failed to draw extension field element") } /// Reseeds the random coin with additional entropy. /// /// The provided `data` is added to the first half of the rate portion of the state, /// then the Rpo256 permutation is applied. The buffer pointer is reset to the start /// of the rate portion. pub fn reseed(&mut self, data: Word) { // Reset buffer self.current = RATE_START; // Add the new seed material to the first half of the rate portion of the RPO state self.state[RATE_START] += data[0]; self.state[RATE_START + 1] += data[1]; self.state[RATE_START + 2] += data[2]; self.state[RATE_START + 3] += data[3]; // Absorb Rpo256::apply_permutation(&mut self.state); } /// Checks how many leading zeros a value would produce when hashed with the current state. /// /// This method creates a temporary copy of the state, adds the provided `value` to the first /// rate element, applies the Rpo256 permutation, and returns the number of trailing zeros /// in the resulting first rate element. This is useful for proof-of-work style computations. pub fn check_leading_zeros(&self, value: u64) -> u32 { let value = Felt::new(value); let mut state_tmp = self.state; state_tmp[RATE_START] += value; Rpo256::apply_permutation(&mut state_tmp); let first_rate_element = state_tmp[RATE_START].as_canonical_u64(); first_rate_element.trailing_zeros() } /// Draws a specified number of unique random integers from a domain of a given size. /// /// # Arguments /// * `num_values` - The number of unique integers to draw (must be less than `domain_size`) /// * `domain_size` - The size of the domain (must be a power of two) /// * `nonce` - A nonce value that is absorbed into the state before drawing /// /// # Returns /// A vector of `num_values` unique integers in the range `[0, domain_size)` /// /// # Panics /// Panics if `domain_size` is not a power of two or if `num_values >= domain_size`. pub fn draw_integers( &mut self, num_values: usize, domain_size: usize, nonce: u64, ) -> Vec<usize> { assert!(domain_size.is_power_of_two(), "domain size must be a power of two"); assert!(num_values < domain_size, "number of values must be smaller than domain size"); // absorb the nonce let nonce = Felt::new(nonce); self.state[RATE_START] += nonce; Rpo256::apply_permutation(&mut self.state); // reset the buffer and move the next random element pointer to the second rate element. // this is done as the first rate element will be "biased" via the provided `nonce` to // contain some number of leading zeros. self.current = RATE_START + 1; // determine how many bits are needed to represent valid values in the domain let v_mask = (domain_size - 1) as u64; // draw values from PRNG until we get as many unique values as specified by num_queries let mut values = Vec::new(); for _ in 0..1000 { // get the next pseudo-random field element let value = self.draw_basefield().as_canonical_u64(); // use the mask to get a value within the range let value = (value & v_mask) as usize; values.push(value); if values.len() == num_values { break; } } assert_eq!( values.len(), num_values, "failed to draw {} integers after 1000 iterations (got {})", num_values, values.len() ); values } } // FELT RNG IMPLEMENTATION // ------------------------------------------------------------------------------------------------ impl FeltRng for RpoRandomCoin { fn draw_element(&mut self) -> Felt { self.draw_basefield() } fn draw_word(&mut self) -> Word { let mut output = [ZERO; 4]; for o in output.iter_mut() { *o = self.draw_basefield(); } Word::new(output) } } // RNGCORE IMPLEMENTATION // ------------------------------------------------------------------------------------------------ impl RngCore for RpoRandomCoin { fn next_u32(&mut self) -> u32 { self.draw_basefield().as_canonical_u64() as u32 } fn next_u64(&mut self) -> u64 { impls::next_u64_via_u32(self) } fn fill_bytes(&mut self, dest: &mut [u8]) { impls::fill_bytes_via_next(self, dest) } } // SERIALIZATION // ------------------------------------------------------------------------------------------------ impl Serializable for RpoRandomCoin { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.state.iter().for_each(|v| v.write_into(target)); // casting to u8 is OK because `current` is always between 4 and 12. target.write_u8(self.current as u8); } } impl Deserializable for RpoRandomCoin { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let state = [ Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, ]; let current = source.read_u8()? as usize; if !(RATE_START..RATE_END).contains(&current) { return Err(DeserializationError::InvalidValue( "current value outside of valid range".to_string(), )); } Ok(Self { state, current }) } } // TESTS // ================================================================================================ #[cfg(test)] mod tests { use super::{Deserializable, FeltRng, RpoRandomCoin, Serializable, ZERO}; use crate::{ONE, Word}; #[test] fn test_feltrng_felt() { let mut rpocoin = RpoRandomCoin::new([ZERO; 4].into()); let output = rpocoin.draw_element(); let mut rpocoin = RpoRandomCoin::new([ZERO; 4].into()); let expected = rpocoin.draw_basefield(); assert_eq!(output, expected); } #[test] fn test_feltrng_word() { let mut rpocoin = RpoRandomCoin::new([ZERO; 4].into()); let output = rpocoin.draw_word(); let mut rpocoin = RpoRandomCoin::new([ZERO; 4].into()); let mut expected = [ZERO; 4]; for o in expected.iter_mut() { *o = rpocoin.draw_basefield(); } let expected = Word::new(expected); assert_eq!(output, expected); } #[test] fn test_feltrng_serialization() { let coin1 = RpoRandomCoin::from_parts([ONE; 12], 5); let bytes = coin1.to_bytes(); let coin2 = RpoRandomCoin::read_from_bytes(&bytes).unwrap(); assert_eq!(coin1, coin2); } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/rand/rpx.rs
miden-crypto/src/rand/rpx.rs
use alloc::{string::ToString, vec::Vec}; use p3_field::{ExtensionField, PrimeField64}; use rand_core::impls; use super::{Felt, FeltRng, RngCore, Word}; use crate::{ ZERO, hash::rpx::Rpx256, utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable}, }; // CONSTANTS // ================================================================================================ const STATE_WIDTH: usize = Rpx256::STATE_WIDTH; const RATE_START: usize = Rpx256::RATE_RANGE.start; const RATE_END: usize = Rpx256::RATE_RANGE.end; const HALF_RATE_WIDTH: usize = (Rpx256::RATE_RANGE.end - Rpx256::RATE_RANGE.start) / 2; // RPX RANDOM COIN // ================================================================================================ /// A simplified version of the `SPONGE_PRG` reseedable pseudo-random number generator algorithm /// described in <https://eprint.iacr.org/2011/499.pdf>. /// /// The simplification is related to the following facts: /// 1. A call to the reseed method implies one and only one call to the permutation function. This /// is possible because in our case we never reseed with more than 4 field elements. /// 2. As a result of the previous point, we don't make use of an input buffer to accumulate seed /// material. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RpxRandomCoin { state: [Felt; STATE_WIDTH], current: usize, } impl RpxRandomCoin { /// Returns a new [RpxRandomCoin] initialize with the specified seed. pub fn new(seed: Word) -> Self { let mut state = [ZERO; STATE_WIDTH]; for i in 0..HALF_RATE_WIDTH { state[RATE_START + i] += seed[i]; } // Absorb Rpx256::apply_permutation(&mut state); RpxRandomCoin { state, current: RATE_START } } /// Returns an [RpxRandomCoin] instantiated from the provided components. /// /// # Panics /// Panics if `current` is smaller than 4 or greater than or equal to 12. pub fn from_parts(state: [Felt; STATE_WIDTH], current: usize) -> Self { assert!( (RATE_START..RATE_END).contains(&current), "current value outside of valid range" ); Self { state, current } } /// Returns components of this random coin. pub fn into_parts(self) -> ([Felt; STATE_WIDTH], usize) { (self.state, self.current) } /// Fills `dest` with random data. pub fn fill_bytes(&mut self, dest: &mut [u8]) { <Self as RngCore>::fill_bytes(self, dest) } pub fn draw_basefield(&mut self) -> Felt { if self.current == RATE_END { Rpx256::apply_permutation(&mut self.state); self.current = RATE_START; } self.current += 1; self.state[self.current - 1] } /// Draws a random field element. /// /// This is an alias for [Self::draw_basefield]. pub fn draw(&mut self) -> Felt { self.draw_basefield() } pub fn draw_ext_field<E: ExtensionField<Felt>>(&mut self) -> E { let ext_degree = E::DIMENSION; let mut result = vec![ZERO; ext_degree]; for r in result.iter_mut().take(ext_degree) { *r = self.draw_basefield(); } E::from_basis_coefficients_slice(&result).expect("failed to draw extension field element") } pub fn reseed(&mut self, data: Word) { // Reset buffer self.current = RATE_START; // Add the new seed material to the first half of the rate portion of the RPX state let data: Word = (*data).into(); self.state[RATE_START] += data[0]; self.state[RATE_START + 1] += data[1]; self.state[RATE_START + 2] += data[2]; self.state[RATE_START + 3] += data[3]; // Absorb Rpx256::apply_permutation(&mut self.state); } pub fn check_leading_zeros(&self, value: u64) -> u32 { let value = Felt::new(value); let mut state_tmp = self.state; state_tmp[RATE_START] += value; Rpx256::apply_permutation(&mut state_tmp); let first_rate_element = state_tmp[RATE_START].as_canonical_u64(); first_rate_element.trailing_zeros() } pub fn draw_integers( &mut self, num_values: usize, domain_size: usize, nonce: u64, ) -> Vec<usize> { assert!(domain_size.is_power_of_two(), "domain size must be a power of two"); assert!(num_values < domain_size, "number of values must be smaller than domain size"); // absorb the nonce let nonce = Felt::new(nonce); self.state[RATE_START] += nonce; Rpx256::apply_permutation(&mut self.state); // reset the buffer self.current = RATE_START; // determine how many bits are needed to represent valid values in the domain let v_mask = (domain_size - 1) as u64; // draw values from PRNG until we get as many unique values as specified by num_queries let mut values = Vec::new(); for _ in 0..1000 { // get the next pseudo-random field element let value = self.draw_basefield().as_canonical_u64(); // use the mask to get a value within the range let value = (value & v_mask) as usize; values.push(value); if values.len() == num_values { break; } } assert_eq!( values.len(), num_values, "failed to draw {} integers after 1000 iterations (got {})", num_values, values.len() ); values } } // FELT RNG IMPLEMENTATION // ------------------------------------------------------------------------------------------------ impl FeltRng for RpxRandomCoin { fn draw_element(&mut self) -> Felt { self.draw_basefield() } fn draw_word(&mut self) -> Word { let mut output = [ZERO; 4]; for o in output.iter_mut() { *o = self.draw_basefield(); } Word::new(output) } } // RNGCORE IMPLEMENTATION // ------------------------------------------------------------------------------------------------ impl RngCore for RpxRandomCoin { fn next_u32(&mut self) -> u32 { self.draw_basefield().as_canonical_u64() as u32 } fn next_u64(&mut self) -> u64 { impls::next_u64_via_u32(self) } fn fill_bytes(&mut self, dest: &mut [u8]) { impls::fill_bytes_via_next(self, dest) } } // SERIALIZATION // ------------------------------------------------------------------------------------------------ impl Serializable for RpxRandomCoin { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.state.iter().for_each(|v| v.write_into(target)); // casting to u8 is OK because `current` is always between 4 and 12. target.write_u8(self.current as u8); } } impl Deserializable for RpxRandomCoin { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let state = [ Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, Felt::read_from(source)?, ]; let current = source.read_u8()? as usize; if !(RATE_START..RATE_END).contains(&current) { return Err(DeserializationError::InvalidValue( "current value outside of valid range".to_string(), )); } Ok(Self { state, current }) } } // TESTS // ================================================================================================ #[cfg(test)] mod tests { use super::{Deserializable, FeltRng, RpxRandomCoin, Serializable, ZERO}; use crate::{ONE, Word}; #[test] fn test_feltrng_felt() { let mut rpxcoin = RpxRandomCoin::new([ZERO; 4].into()); let output = rpxcoin.draw_element(); let mut rpxcoin = RpxRandomCoin::new([ZERO; 4].into()); let expected = rpxcoin.draw_basefield(); assert_eq!(output, expected); } #[test] fn test_feltrng_word() { let mut rpxcoin = RpxRandomCoin::new([ZERO; 4].into()); let output = rpxcoin.draw_word(); let mut rpocoin = RpxRandomCoin::new([ZERO; 4].into()); let mut expected = [ZERO; 4]; for o in expected.iter_mut() { *o = rpocoin.draw_basefield(); } let expected = Word::new(expected); assert_eq!(output, expected); } #[test] fn test_feltrng_serialization() { let coin1 = RpxRandomCoin::from_parts([ONE; 12], 5); let bytes = coin1.to_bytes(); let coin2 = RpxRandomCoin::read_from_bytes(&bytes).unwrap(); assert_eq!(coin1, coin2); } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/rand/mod.rs
miden-crypto/src/rand/mod.rs
//! Pseudo-random element generation. use p3_field::PrimeField64; use rand::RngCore; use crate::{Felt, Word}; mod rpo; pub use rpo::RpoRandomCoin; mod rpx; pub use rpx::RpxRandomCoin; // Test utilities for generating random data (used in tests and benchmarks) #[cfg(any(test, feature = "std"))] pub mod test_utils; // RANDOMNESS (ported from Winterfell's winter-utils) // ================================================================================================ /// Defines how `Self` can be read from a sequence of random bytes. pub trait Randomizable: Sized { /// Size of `Self` in bytes. /// /// This is used to determine how many bytes should be passed to the /// [from_random_bytes()](Self::from_random_bytes) function. const VALUE_SIZE: usize; /// Returns `Self` if the set of bytes forms a valid value, otherwise returns None. fn from_random_bytes(source: &[u8]) -> Option<Self>; } impl Randomizable for u128 { const VALUE_SIZE: usize = 16; fn from_random_bytes(source: &[u8]) -> Option<Self> { if let Ok(bytes) = source[..Self::VALUE_SIZE].try_into() { Some(u128::from_le_bytes(bytes)) } else { None } } } impl Randomizable for u64 { const VALUE_SIZE: usize = 8; fn from_random_bytes(source: &[u8]) -> Option<Self> { if let Ok(bytes) = source[..Self::VALUE_SIZE].try_into() { Some(u64::from_le_bytes(bytes)) } else { None } } } impl Randomizable for u32 { const VALUE_SIZE: usize = 4; fn from_random_bytes(source: &[u8]) -> Option<Self> { if let Ok(bytes) = source[..Self::VALUE_SIZE].try_into() { Some(u32::from_le_bytes(bytes)) } else { None } } } impl Randomizable for u16 { const VALUE_SIZE: usize = 2; fn from_random_bytes(source: &[u8]) -> Option<Self> { if let Ok(bytes) = source[..Self::VALUE_SIZE].try_into() { Some(u16::from_le_bytes(bytes)) } else { None } } } impl Randomizable for u8 { const VALUE_SIZE: usize = 1; fn from_random_bytes(source: &[u8]) -> Option<Self> { Some(source[0]) } } impl Randomizable for Felt { const VALUE_SIZE: usize = 8; fn from_random_bytes(source: &[u8]) -> Option<Self> { if let Ok(bytes) = source[..Self::VALUE_SIZE].try_into() { let value = u64::from_le_bytes(bytes); // Ensure the value is within the field modulus if value < Felt::ORDER_U64 { Some(Felt::new(value)) } else { None } } else { None } } } /// Pseudo-random element generator. /// /// An instance can be used to draw, uniformly at random, base field elements as well as [Word]s. pub trait FeltRng: RngCore { /// Draw, uniformly at random, a base field element. fn draw_element(&mut self) -> Felt; /// Draw, uniformly at random, a [Word]. fn draw_word(&mut self) -> Word; } // RANDOM VALUE GENERATION FOR TESTING // ================================================================================================ /// Generates a random field element for testing purposes. /// /// This function is only available with the `std` feature. #[cfg(feature = "std")] pub fn random_felt() -> Felt { use rand::Rng; let mut rng = rand::rng(); // Goldilocks field order is 2^64 - 2^32 + 1 // Generate a random u64 and reduce modulo the field order Felt::new(rng.random::<u64>()) } /// Generates a random word (4 field elements) for testing purposes. /// /// This function is only available with the `std` feature. #[cfg(feature = "std")] pub fn random_word() -> Word { Word::new([random_felt(), random_felt(), random_felt(), random_felt()]) }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/aead/mod.rs
miden-crypto/src/aead/mod.rs
//! AEAD (authenticated encryption with associated data) schemes. use alloc::{ string::{String, ToString}, vec::Vec, }; use thiserror::Error; use crate::{ Felt, utils::{ Deserializable, zeroize::{Zeroize, ZeroizeOnDrop}, }, }; pub mod aead_rpo; pub mod xchacha; /// Indicates whether encrypted data originated from field elements or raw bytes. #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DataType { Elements = 0, Bytes = 1, } impl TryFrom<u8> for DataType { type Error = String; fn try_from(value: u8) -> Result<Self, Self::Error> { match value { 0 => Ok(DataType::Elements), 1 => Ok(DataType::Bytes), _ => Err("invalid data type value: expected 0 for Elements or 1 for Bytes".to_string()), } } } // AEAD TRAIT // ================================================================================================ /// Authenticated encryption with associated data (AEAD) scheme pub(crate) trait AeadScheme { const KEY_SIZE: usize; type Key: Deserializable + Zeroize + ZeroizeOnDrop; fn key_from_bytes(bytes: &[u8]) -> Result<Self::Key, EncryptionError>; // BYTE METHODS // ================================================================================================ fn encrypt_bytes<R: rand::CryptoRng + rand::RngCore>( key: &Self::Key, rng: &mut R, plaintext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError>; fn decrypt_bytes_with_associated_data( key: &Self::Key, ciphertext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError>; // FELT METHODS // ================================================================================================ /// Encrypts field elements with associated data. Default implementation converts to bytes. fn encrypt_elements<R: rand::CryptoRng + rand::RngCore>( key: &Self::Key, rng: &mut R, plaintext: &[Felt], associated_data: &[Felt], ) -> Result<Vec<u8>, EncryptionError> { let plaintext_bytes = crate::utils::elements_to_bytes(plaintext); let ad_bytes = crate::utils::elements_to_bytes(associated_data); Self::encrypt_bytes(key, rng, &plaintext_bytes, &ad_bytes) } /// Decrypts field elements with associated data. Default implementation uses byte decryption. fn decrypt_elements_with_associated_data( key: &Self::Key, ciphertext: &[u8], associated_data: &[Felt], ) -> Result<Vec<Felt>, EncryptionError> { let ad_bytes = crate::utils::elements_to_bytes(associated_data); let plaintext_bytes = Self::decrypt_bytes_with_associated_data(key, ciphertext, &ad_bytes)?; match crate::utils::bytes_to_elements_exact(&plaintext_bytes) { Some(elements) => Ok(elements), None => Err(EncryptionError::FailedBytesToElementsConversion), } } } // ERROR TYPES // ================================================================================================ /// Errors that can occur during encryption/decryption operations #[derive(Debug, Error)] pub enum EncryptionError { #[error("authentication tag verification failed")] InvalidAuthTag, #[error("peration failed")] FailedOperation, #[error("malformed padding")] MalformedPadding, #[error("ciphertext length, in field elements, is not a multiple of `RATE_WIDTH`")] CiphertextLenNotMultipleRate, #[error("invalid data type: expected {expected:?}, found {found:?}")] InvalidDataType { expected: DataType, found: DataType }, #[error( "failed to convert bytes, that are supposed to originate from field elements, back to field elements" )] FailedBytesToElementsConversion, }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/aead/xchacha/test.rs
miden-crypto/src/aead/xchacha/test.rs
use proptest::{ prelude::{any, prop}, prop_assert_eq, prop_assert_ne, proptest, }; use rand::{SeedableRng, TryRngCore}; use rand_chacha::ChaCha20Rng; use super::*; // PROPERTY-BASED TESTS // ================================================================================================ proptest! { #[test] fn test_encryption_decryption_roundtrip( data_len in 1usize..1000, ) { let mut rng = rand::rng(); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random field elements let data: Vec<Felt> = (0..data_len) .map(|_| Felt::new(rng.try_next_u64().unwrap())) .collect(); let encrypted = key.encrypt_elements_with_nonce(&data, &[], nonce).unwrap(); let decrypted = key.decrypt_elements(&encrypted).unwrap(); prop_assert_eq!(data, decrypted); } #[test] fn test_encryption_decryption_with_ad_roundtrip( associated_data_len in 1usize..1000, data_len in 1usize..1000, ) { let mut rng = rand::rng(); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random field elements let associated_data: Vec<Felt> = (0..associated_data_len) .map(|_| Felt::new(rng.try_next_u64().unwrap())) .collect(); let data: Vec<Felt> = (0..data_len) .map(|_| Felt::new(rng.try_next_u64().unwrap())) .collect(); let encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_elements_with_associated_data(&encrypted, &associated_data).unwrap(); prop_assert_eq!(data, decrypted); } #[test] fn test_bytes_encryption_decryption_roundtrip( data_len in 0usize..1000, ) { let mut rng = rand::rng(); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random bytes let mut data = vec![0_u8; data_len]; let _ = rng.try_fill_bytes(&mut data); let encrypted = key.encrypt_bytes_with_nonce(&data, &[], nonce).unwrap(); let decrypted = key.decrypt_bytes(&encrypted).unwrap(); prop_assert_eq!(data, decrypted); } #[test] fn test_bytes_encryption_decryption_with_ad_roundtrip( associated_data_len in 0usize..1000, data_len in 0usize..1000, ) { let mut rng = rand::rng(); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random bytes let mut associated_data = vec![0_u8; associated_data_len]; let _ = rng.try_fill_bytes(&mut associated_data); let mut data = vec![0_u8; data_len]; let _ = rng.try_fill_bytes(&mut data); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data).unwrap(); prop_assert_eq!(data, decrypted); } #[test] fn test_different_keys_different_outputs( associated_data in prop::collection::vec(any::<u8>(), 1..500), data in prop::collection::vec(any::<u8>(), 1..500), ) { let mut rng1 = rand::rng(); let mut rng2 = rand::rng(); let key1 = SecretKey::with_rng(&mut rng1); let key2 = SecretKey::with_rng(&mut rng2); let mut nonce_bytes = [0_u8; 24]; let _ = rng2.try_fill_bytes(&mut nonce_bytes); let nonce1 = Nonce::from_slice(&nonce_bytes); let nonce2 = Nonce::from_slice(&nonce_bytes); let encrypted1 = key1.encrypt_bytes_with_nonce(&data, &associated_data, nonce1).unwrap(); let encrypted2 = key2.encrypt_bytes_with_nonce(&data, &associated_data, nonce2).unwrap(); // Different keys should produce different ciphertexts prop_assert_ne!(encrypted1.ciphertext, encrypted2.ciphertext); } #[test] fn test_different_nonces_different_outputs( associated_data in prop::collection::vec(any::<u8>(), 1..500), data in prop::collection::vec(any::<u8>(), 1..500), ) { let mut rng = rand::rng(); let key = SecretKey::with_rng(&mut rng); let mut nonce_bytes = [0_u8; 24]; let _ = rng.try_fill_bytes(&mut nonce_bytes); let nonce1 = Nonce::from_slice(&nonce_bytes); let _ = rng.try_fill_bytes(&mut nonce_bytes); let nonce2 = Nonce::from_slice(&nonce_bytes); let encrypted1 = key.encrypt_bytes_with_nonce(&data,&associated_data, nonce1).unwrap(); let encrypted2 = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce2).unwrap(); // Different nonces should produce different ciphertexts (with very high probability) prop_assert_ne!(encrypted1.ciphertext, encrypted2.ciphertext); } } // UNIT TESTS // ================================================================================================ #[test] fn test_secret_key_creation() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key1 = SecretKey::with_rng(&mut rng); let key2 = SecretKey::with_rng(&mut rng); // Keys should be different assert_ne!(key1, key2); } #[test] fn test_secret_key_serialization() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let key_bytes = key.to_bytes(); let key_serialized = SecretKey::read_from_bytes(&key_bytes).unwrap(); assert_eq!(key, key_serialized); } #[test] fn test_nonce_creation() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let nonce1 = Nonce::with_rng(&mut rng); let nonce2 = Nonce::with_rng(&mut rng); // Nonces should be different assert_ne!(nonce1, nonce2); } #[test] fn test_empty_data_encryption() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data = vec![1; 8]; let empty_data = vec![]; let encrypted = key.encrypt_bytes_with_nonce(&empty_data, &associated_data, nonce).unwrap(); let decrypted = key .decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data) .unwrap(); assert_eq!(empty_data, decrypted); } #[test] fn test_single_element_encryption() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data = vec![1; 8]; let data = vec![42]; let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key .decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data) .unwrap(); assert_eq!(data, decrypted); } #[test] fn test_large_data_encryption() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data = vec![1; 8]; // Test with data larger than rate let data: Vec<_> = (0..100).collect(); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key .decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data) .unwrap(); assert_eq!(data, decrypted); } #[test] fn test_encryption_various_lengths() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let associated_data = vec![1; 8]; for len in [1, 7, 8, 9, 15, 16, 17, 31, 32, 35, 39, 54, 67, 100, 255] { let data: Vec<_> = (0..len).collect(); let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key .decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data) .unwrap(); assert_eq!(data, decrypted, "Failed for length {len}"); } } #[test] fn test_encrypted_data_serialization() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let associated_data = vec![1; 8]; for len in [1, 7, 8, 9, 15, 16, 17, 31, 32, 35, 39, 54, 67, 100, 255] { let data: Vec<_> = (0..len).collect(); let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let encrypted_data_bytes = encrypted.to_bytes(); let encrypted_data_serialized = EncryptedData::read_from_bytes(&encrypted_data_bytes).unwrap(); assert_eq!(encrypted, encrypted_data_serialized, "Failed for length {len}"); } } #[test] fn test_ciphertext_tampering_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data = vec![1; 8]; let data = vec![123, 45]; let mut encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); // Tamper with ciphertext encrypted.ciphertext[0] = encrypted.ciphertext[0].wrapping_add(1); let result = key.decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data); assert!(result.is_err()); } #[test] fn test_wrong_key_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key1 = SecretKey::with_rng(&mut rng); let key2 = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data = vec![1; 8]; let data = vec![123, 45]; let encrypted = key1.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); // Try to decrypt with wrong key let result = key2.decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data); assert!(result.is_err()); } #[test] fn test_wrong_nonce_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce1 = Nonce::with_rng(&mut rng); let nonce2 = Nonce::with_rng(&mut rng); let associated_data: Vec<u8> = vec![1; 8]; let data = vec![123, 55]; let mut encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce1).unwrap(); // Try to decrypt with wrong nonce encrypted.nonce = nonce2; let result = key.decrypt_bytes_with_associated_data_unchecked(&encrypted, &associated_data); assert!(result.is_err()); } // SECURITY TESTS // ================================================================================================ #[cfg(all(test, feature = "std"))] mod security_tests { use std::collections::HashSet; use super::*; #[test] fn test_key_uniqueness() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let mut keys = HashSet::new(); // Generate 1000 keys and ensure they're all unique for _ in 0..1000 { let key = SecretKey::with_rng(&mut rng); let key_bytes = format!("{:?}", key.0); assert!(keys.insert(key_bytes), "Duplicate key generated!"); } } #[test] fn test_nonce_uniqueness() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); // Generate 1000 nonces and ensure they're all unique let mut nonces = HashSet::new(); for _ in 0..1000 { let nonce = Nonce::with_rng(&mut rng); let nonce_bytes = format!("{:?}", nonce.inner); assert!(nonces.insert(nonce_bytes), "Duplicate nonce generated!"); } } #[test] fn test_ciphertext_appears_random() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); // Encrypt the same plaintext with different nonces let associated_data = vec![1; 8]; let plaintext = vec![3; 10]; let mut ciphertexts = Vec::new(); for _ in 0..100 { let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_bytes_with_nonce(&plaintext, &associated_data, nonce).unwrap(); ciphertexts.push(encrypted.ciphertext); } // Ensure all ciphertexts are different (randomness test) for i in 0..ciphertexts.len() { for j in i + 1..ciphertexts.len() { assert_ne!( ciphertexts[i], ciphertexts[j], "Ciphertexts {i} and {j} are identical!" ); } } } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/aead/xchacha/mod.rs
miden-crypto/src/aead/xchacha/mod.rs
//! Cryptographic utilities for encrypting and decrypting data using XChaCha20-Poly1305 AEAD. //! //! This module provides secure encryption and decryption functionality. It uses //! the XChaCha20-Poly1305 authenticated encryption with associated data (AEAD) algorithm, //! which provides both confidentiality and integrity. //! //! # Key Components //! //! - [`SecretKey`]: A 256-bit secret key for encryption and decryption operations //! - [`Nonce`]: A 192-bit nonce that should be sampled randomly per encryption operation //! - [`EncryptedData`]: Encrypted data use alloc::{string::ToString, vec::Vec}; use chacha20poly1305::{ XChaCha20Poly1305, aead::{Aead, AeadCore, KeyInit}, }; use rand::{CryptoRng, RngCore}; use crate::{ Felt, aead::{AeadScheme, DataType, EncryptionError}, utils::{ ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, bytes_to_elements_exact, elements_to_bytes, zeroize::{Zeroize, ZeroizeOnDrop}, }, }; #[cfg(all(test, feature = "std"))] mod test; // CONSTANTS // ================================================================================================ /// Size of nonce in bytes const NONCE_SIZE_BYTES: usize = 24; /// Size of secret key in bytes const SK_SIZE_BYTES: usize = 32; // STRUCTS AND IMPLEMENTATIONS // ================================================================================================ /// Encrypted data #[derive(Debug, PartialEq, Eq)] pub struct EncryptedData { /// Indicates the original format of the data before encryption data_type: DataType, /// The encrypted ciphertext, including the authentication tag ciphertext: Vec<u8>, /// The nonce used during encryption nonce: Nonce, } /// A 192-bit nonce /// /// Note: This should be drawn randomly from a CSPRNG. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Nonce { inner: chacha20poly1305::XNonce, } impl Nonce { /// Creates a new random nonce using the provided random number generator pub fn with_rng<R: RngCore + CryptoRng>(rng: &mut R) -> Self { // we use a seedable CSPRNG and seed it with `rng` // this is a work around the fact that the version of the `rand` dependency in our crate // is different than the one used in the `chacha20poly1305`. This solution will // no longer be needed once `chacha20poly1305` gets a new release with a version of // the `rand` dependency matching ours use chacha20poly1305::aead::rand_core::SeedableRng; let mut seed = [0_u8; 32]; rand::RngCore::fill_bytes(rng, &mut seed); let rng = rand_hc::Hc128Rng::from_seed(seed); Nonce { inner: XChaCha20Poly1305::generate_nonce(rng), } } /// Creates a new nonce from the provided array of bytes pub fn from_slice(bytes: &[u8; NONCE_SIZE_BYTES]) -> Self { Nonce { inner: (*bytes).into() } } } /// A 256-bit secret key #[derive(Debug, PartialEq, Eq)] pub struct SecretKey([u8; SK_SIZE_BYTES]); impl SecretKey { // CONSTRUCTORS // -------------------------------------------------------------------------------------------- /// Creates a new random secret key using the default random number generator #[cfg(feature = "std")] #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut rng = rand::rng(); Self::with_rng(&mut rng) } /// Creates a new random secret key using the provided random number generator pub fn with_rng<R: RngCore + CryptoRng>(rng: &mut R) -> Self { // we use a seedable CSPRNG and seed it with `rng` // this is a work around the fact that the version of the `rand` dependency in our crate // is different than the one used in the `chacha20poly1305`. This solution will // no longer be needed once `chacha20poly1305` gets a new release with a version of // the `rand` dependency matching ours use chacha20poly1305::aead::rand_core::SeedableRng; let mut seed = [0_u8; 32]; rand::RngCore::fill_bytes(rng, &mut seed); let rng = rand_hc::Hc128Rng::from_seed(seed); let key = XChaCha20Poly1305::generate_key(rng); Self(key.into()) } // BYTE ENCRYPTION // -------------------------------------------------------------------------------------------- /// Encrypts and authenticates the provided data using this secret key and a random /// nonce #[cfg(feature = "std")] pub fn encrypt_bytes(&self, data: &[u8]) -> Result<EncryptedData, EncryptionError> { self.encrypt_bytes_with_associated_data(data, &[]) } /// Encrypts the provided data and authenticates both the ciphertext as well as /// the provided associated data using this secret key and a random nonce #[cfg(feature = "std")] pub fn encrypt_bytes_with_associated_data( &self, data: &[u8], associated_data: &[u8], ) -> Result<EncryptedData, EncryptionError> { let mut rng = rand::rng(); let nonce = Nonce::with_rng(&mut rng); self.encrypt_bytes_with_nonce(data, associated_data, nonce) } /// Encrypts the provided data using this secret key and a specified nonce pub fn encrypt_bytes_with_nonce( &self, data: &[u8], associated_data: &[u8], nonce: Nonce, ) -> Result<EncryptedData, EncryptionError> { let payload = chacha20poly1305::aead::Payload { msg: data, aad: associated_data }; let cipher = XChaCha20Poly1305::new(&self.0.into()); let ciphertext = cipher .encrypt(&nonce.inner, payload) .map_err(|_| EncryptionError::FailedOperation)?; Ok(EncryptedData { data_type: DataType::Bytes, ciphertext, nonce, }) } // ELEMENT ENCRYPTION // -------------------------------------------------------------------------------------------- /// Encrypts and authenticates the provided sequence of field elements using this secret key /// and a random nonce. #[cfg(feature = "std")] pub fn encrypt_elements(&self, data: &[Felt]) -> Result<EncryptedData, EncryptionError> { self.encrypt_elements_with_associated_data(data, &[]) } /// Encrypts the provided sequence of field elements and authenticates both the ciphertext as /// well as the provided associated data using this secret key and a random nonce. #[cfg(feature = "std")] pub fn encrypt_elements_with_associated_data( &self, data: &[Felt], associated_data: &[Felt], ) -> Result<EncryptedData, EncryptionError> { let mut rng = rand::rng(); let nonce = Nonce::with_rng(&mut rng); self.encrypt_elements_with_nonce(data, associated_data, nonce) } /// Encrypts the provided sequence of field elements and authenticates both the ciphertext as /// well as the provided associated data using this secret key and the specified nonce. pub fn encrypt_elements_with_nonce( &self, data: &[Felt], associated_data: &[Felt], nonce: Nonce, ) -> Result<EncryptedData, EncryptionError> { let data_bytes = elements_to_bytes(data); let ad_bytes = elements_to_bytes(associated_data); let mut encrypted_data = self.encrypt_bytes_with_nonce(&data_bytes, &ad_bytes, nonce)?; encrypted_data.data_type = DataType::Elements; Ok(encrypted_data) } // BYTE DECRYPTION // -------------------------------------------------------------------------------------------- /// Decrypts the provided encrypted data using this secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as elements /// rather than as bytes. pub fn decrypt_bytes( &self, encrypted_data: &EncryptedData, ) -> Result<Vec<u8>, EncryptionError> { self.decrypt_bytes_with_associated_data(encrypted_data, &[]) } /// Decrypts the provided encrypted data given some associated data using this secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as elements /// rather than as bytes. pub fn decrypt_bytes_with_associated_data( &self, encrypted_data: &EncryptedData, associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { if encrypted_data.data_type != DataType::Bytes { return Err(EncryptionError::InvalidDataType { expected: DataType::Bytes, found: encrypted_data.data_type, }); } self.decrypt_bytes_with_associated_data_unchecked(encrypted_data, associated_data) } /// Decrypts the provided encrypted data given some associated data using this secret key. fn decrypt_bytes_with_associated_data_unchecked( &self, encrypted_data: &EncryptedData, associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { let EncryptedData { ciphertext, nonce, data_type: _ } = encrypted_data; let payload = chacha20poly1305::aead::Payload { msg: ciphertext, aad: associated_data }; let cipher = XChaCha20Poly1305::new(&self.0.into()); cipher .decrypt(&nonce.inner, payload) .map_err(|_| EncryptionError::FailedOperation) } // ELEMENT DECRYPTION // -------------------------------------------------------------------------------------------- /// Decrypts the provided encrypted data using this secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as bytes /// rather than as field elements. pub fn decrypt_elements( &self, encrypted_data: &EncryptedData, ) -> Result<Vec<Felt>, EncryptionError> { self.decrypt_elements_with_associated_data(encrypted_data, &[]) } /// Decrypts the provided encrypted data, given some associated data, using this secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as bytes /// rather than as field elements. pub fn decrypt_elements_with_associated_data( &self, encrypted_data: &EncryptedData, associated_data: &[Felt], ) -> Result<Vec<Felt>, EncryptionError> { if encrypted_data.data_type != DataType::Elements { return Err(EncryptionError::InvalidDataType { expected: DataType::Elements, found: encrypted_data.data_type, }); } let ad_bytes = elements_to_bytes(associated_data); let plaintext_bytes = self.decrypt_bytes_with_associated_data_unchecked(encrypted_data, &ad_bytes)?; match bytes_to_elements_exact(&plaintext_bytes) { Some(elements) => Ok(elements), None => Err(EncryptionError::FailedBytesToElementsConversion), } } } impl AsRef<[u8]> for SecretKey { fn as_ref(&self) -> &[u8] { &self.0 } } impl Drop for SecretKey { fn drop(&mut self) { self.zeroize(); } } impl Zeroize for SecretKey { fn zeroize(&mut self) { self.0.zeroize(); } } impl ZeroizeOnDrop for SecretKey {} // IES IMPLEMENTATION // ================================================================================================ pub struct XChaCha; impl AeadScheme for XChaCha { const KEY_SIZE: usize = SK_SIZE_BYTES; type Key = SecretKey; fn key_from_bytes(bytes: &[u8]) -> Result<Self::Key, EncryptionError> { SecretKey::read_from_bytes(bytes).map_err(|_| EncryptionError::FailedOperation) } fn encrypt_bytes<R: rand::CryptoRng + rand::RngCore>( key: &Self::Key, rng: &mut R, plaintext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { let nonce = Nonce::with_rng(rng); let encrypted_data = key .encrypt_bytes_with_nonce(plaintext, associated_data, nonce) .map_err(|_| EncryptionError::FailedOperation)?; Ok(encrypted_data.to_bytes()) } fn decrypt_bytes_with_associated_data( key: &Self::Key, ciphertext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { let encrypted_data = &EncryptedData::read_from_bytes(ciphertext).unwrap(); key.decrypt_bytes_with_associated_data(encrypted_data, associated_data) .map_err(|_| EncryptionError::FailedOperation) } } // SERIALIZATION / DESERIALIZATION // ================================================================================================ impl Serializable for SecretKey { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_bytes(&self.0); } } impl Deserializable for SecretKey { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let inner: [u8; SK_SIZE_BYTES] = source.read_array()?; Ok(SecretKey(inner)) } } impl Serializable for Nonce { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_bytes(&self.inner); } } impl Deserializable for Nonce { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let inner: [u8; NONCE_SIZE_BYTES] = source.read_array()?; Ok(Nonce { inner: inner.into() }) } } impl Serializable for EncryptedData { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u8(self.data_type as u8); target.write_usize(self.ciphertext.len()); target.write_bytes(&self.ciphertext); target.write_bytes(&self.nonce.inner); } } impl Deserializable for EncryptedData { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let data_type_value: u8 = source.read_u8()?; let data_type = data_type_value.try_into().map_err(|_| { DeserializationError::InvalidValue("invalid data type value".to_string()) })?; let ciphertext = Vec::<u8>::read_from(source)?; let inner: [u8; NONCE_SIZE_BYTES] = source.read_array()?; Ok(Self { ciphertext, nonce: Nonce { inner: inner.into() }, data_type, }) } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/aead/aead_rpo/test.rs
miden-crypto/src/aead/aead_rpo/test.rs
use proptest::{ prelude::{any, prop}, prop_assert_eq, prop_assert_ne, prop_assume, proptest, }; use rand::{RngCore, SeedableRng}; use rand_chacha::ChaCha20Rng; use super::*; // PROPERTY-BASED TESTS // ================================================================================================ proptest! { #[test] fn prop_bytes_felts_roundtrip(bytes in prop::collection::vec(any::<u8>(), 0..500)) { // bytes -> felts -> bytes let felts = super::bytes_to_elements_with_padding(&bytes); let back = super::padded_elements_to_bytes(&felts).unwrap(); prop_assert_eq!(bytes, back); // And the other direction on valid encodings: felts come from bytes_to_felts, // so they must satisfy the padding invariant expected by felts_to_bytes. let felts_roundtrip = super::bytes_to_elements_with_padding(&super::padded_elements_to_bytes(&felts).unwrap()); prop_assert_eq!(felts, felts_roundtrip); } #[test] fn test_encrypted_data_serialization_roundtrip( seed in any::<u64>(), associated_data_len in 1usize..100, data_len in 1usize..100, ) { let mut rng = ChaCha20Rng::seed_from_u64(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random field elements let associated_data: Vec<Felt> = (0..associated_data_len) .map(|_| Felt::new(rng.next_u64())) .collect(); let data: Vec<Felt> = (0..data_len) .map(|_| Felt::new(rng.next_u64())) .collect(); let encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); let encrypted_serialized = encrypted.to_bytes(); let encrypted_deserialized = EncryptedData::read_from_bytes(&encrypted_serialized).unwrap(); prop_assert_eq!(encrypted, encrypted_deserialized); } #[test] fn test_encryption_decryption_roundtrip( seed in any::<u64>(), associated_data_len in 1usize..100, data_len in 1usize..100, ) { let mut rng = ChaCha20Rng::seed_from_u64(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random field elements let associated_data: Vec<Felt> = (0..associated_data_len) .map(|_| Felt::new(rng.next_u64())) .collect(); let data: Vec<Felt> = (0..data_len) .map(|_| Felt::new(rng.next_u64())) .collect(); let encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_elements_with_associated_data(&encrypted, &associated_data).unwrap(); prop_assert_eq!(data, decrypted); } #[test] fn test_bytes_encryption_decryption_roundtrip( seed in any::<u64>(), associated_data_len in 0usize..1000, data_len in 0usize..1000, ) { let mut rng = ChaCha20Rng::seed_from_u64(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); // Generate random bytes let mut associated_data = vec![0_u8; associated_data_len]; rng.fill_bytes(&mut associated_data); let mut data = vec![0_u8; data_len]; rng.fill_bytes(&mut data); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_bytes_with_associated_data(&encrypted, &associated_data).unwrap(); prop_assert_eq!(data, decrypted); } #[test] fn test_different_keys_different_outputs( seed1 in any::<u64>(), seed2 in any::<u64>(), associated_data in prop::collection::vec(any::<u64>(), 1..500), data in prop::collection::vec(any::<u64>(), 1..500), ) { prop_assume!(seed1 != seed2); let mut rng1 = ChaCha20Rng::seed_from_u64(seed1); let mut rng2 = ChaCha20Rng::seed_from_u64(seed2); let key1 = SecretKey::with_rng(&mut rng1); let key2 = SecretKey::with_rng(&mut rng2); let nonce_word: Word = [ONE; 4].into(); let nonce1 = Nonce::from(nonce_word); let nonce2 = Nonce::from(nonce_word); let associated_data: Vec<Felt> = associated_data.into_iter() .map(Felt::new) .collect(); let data: Vec<Felt> = data.into_iter() .map(Felt::new) .collect(); let encrypted1 = key1.encrypt_elements_with_nonce(&data, &associated_data, nonce1).unwrap(); let encrypted2 = key2.encrypt_elements_with_nonce(&data, &associated_data, nonce2).unwrap(); // Different keys should produce different ciphertexts prop_assert_ne!(encrypted1.ciphertext, encrypted2.ciphertext); prop_assert_ne!(encrypted1.auth_tag, encrypted2.auth_tag); } #[test] fn test_different_nonces_different_outputs( seed in any::<u64>(), associated_data in prop::collection::vec(any::<u64>(), 1..50), data in prop::collection::vec(any::<u64>(), 1..50), ) { let mut rng = ChaCha20Rng::seed_from_u64(seed); let key = SecretKey::with_rng(&mut rng); let nonce1 = Nonce::from([ZERO; 4]); let nonce2 = Nonce::from([ONE; 4]); let associated_data: Vec<Felt> = associated_data.into_iter() .map(Felt::new) .collect(); let data: Vec<Felt> = data.into_iter() .map(Felt::new) .collect(); let encrypted1 = key.encrypt_elements_with_nonce(&data,&associated_data, nonce1).unwrap(); let encrypted2 = key.encrypt_elements_with_nonce(&data, &associated_data, nonce2).unwrap(); // Different nonces should produce different ciphertexts (with very high probability) prop_assert_ne!(encrypted1.ciphertext, encrypted2.ciphertext); prop_assert_ne!(encrypted1.auth_tag, encrypted2.auth_tag); } } // UNIT TESTS // ================================================================================================ #[test] fn test_secret_key_creation() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key1 = SecretKey::with_rng(&mut rng); let key2 = SecretKey::with_rng(&mut rng); // Keys should be different assert_ne!(key1, key2); } #[test] fn test_nonce_creation() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let nonce1 = Nonce::with_rng(&mut rng); let nonce2 = Nonce::with_rng(&mut rng); // Nonces should be different assert_ne!(nonce1, nonce2); } #[test] fn test_empty_data_encryption() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; let empty_data: Vec<Felt> = vec![]; let encrypted = key.encrypt_elements_with_nonce(&empty_data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_elements_with_associated_data(&encrypted, &associated_data).unwrap(); assert_eq!(empty_data, decrypted); assert!(!encrypted.ciphertext.is_empty()); } #[test] fn test_single_element_encryption() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ZERO; 8]; let data = vec![Felt::new(42)]; let encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_elements_with_associated_data(&encrypted, &associated_data).unwrap(); assert_eq!(data, decrypted); assert_eq!(encrypted.ciphertext.len(), 8); } #[test] fn test_large_data_encryption() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; // Test with data larger than rate let data: Vec<Felt> = (0..100).map(|i| Felt::new(i as u64)).collect(); let encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_elements_with_associated_data(&encrypted, &associated_data).unwrap(); assert_eq!(data, decrypted); } #[test] fn test_encryption_various_lengths() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; for len in [1, 7, 8, 9, 15, 16, 17, 31, 32, 35, 39, 54, 67, 100, 1000] { let data: Vec<Felt> = (0..len).map(|i| Felt::new(i as u64)).collect(); let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_elements_with_associated_data(&encrypted, &associated_data).unwrap(); assert_eq!(data, decrypted, "Failed for length {len}"); } } #[test] fn test_bytes_encryption_various_lengths() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let associated_data: Vec<u8> = vec![1; 8]; for len in [1, 7, 8, 9, 15, 16, 17, 31, 32, 35, 39, 54, 67, 100, 1000] { let mut data = vec![0_u8; len]; rng.fill_bytes(&mut data); let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce).unwrap(); let decrypted = key.decrypt_bytes_with_associated_data(&encrypted, &associated_data).unwrap(); assert_eq!(data, decrypted, "Failed for length {len}"); } } #[test] fn test_ciphertext_tampering_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; let data = vec![Felt::new(123), Felt::new(456)]; let mut encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); // Tamper with ciphertext encrypted.ciphertext[0] += ONE; let result = key.decrypt_elements_with_associated_data(&encrypted, &associated_data); assert!(matches!(result, Err(EncryptionError::InvalidAuthTag))); } #[test] fn test_auth_tag_tampering_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; let data = vec![Felt::new(123), Felt::new(456)]; let mut encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); // Tamper with auth tag let mut tampered_tag = encrypted.auth_tag.0; tampered_tag[0] += ONE; encrypted.auth_tag = AuthTag(tampered_tag); let result = key.decrypt_elements_with_associated_data(&encrypted, &associated_data); assert!(matches!(result, Err(EncryptionError::InvalidAuthTag))); } #[test] fn test_wrong_key_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key1 = SecretKey::with_rng(&mut rng); let key2 = SecretKey::with_rng(&mut rng); let nonce = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; let data = vec![Felt::new(123), Felt::new(456)]; let encrypted = key1.encrypt_elements_with_nonce(&data, &associated_data, nonce).unwrap(); // Try to decrypt with wrong key let result = key2.decrypt_elements_with_associated_data(&encrypted, &associated_data); assert!(matches!(result, Err(EncryptionError::InvalidAuthTag))); } #[test] fn test_wrong_nonce_detection() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let nonce1 = Nonce::with_rng(&mut rng); let nonce2 = Nonce::with_rng(&mut rng); let associated_data: Vec<Felt> = vec![ONE; 8]; let data = vec![Felt::new(123), Felt::new(456)]; let mut encrypted = key.encrypt_elements_with_nonce(&data, &associated_data, nonce1).unwrap(); // Try to decrypt with wrong nonce encrypted.nonce = nonce2; let result = key.decrypt_elements_with_associated_data(&encrypted, &associated_data); assert!(matches!(result, Err(EncryptionError::InvalidAuthTag))); } // SECURITY TESTS // ================================================================================================ #[cfg(all(test, feature = "std"))] mod security_tests { use std::collections::HashSet; use super::*; #[test] fn test_key_serialization() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); let key_serialized = key.to_bytes(); let key_deserialized = SecretKey::read_from_bytes(&key_serialized).unwrap(); assert_eq!(key, key_deserialized) } #[test] fn test_key_uniqueness() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let mut keys = HashSet::new(); // Generate 1000 keys and ensure they're all unique for _ in 0..1000 { let key = SecretKey::with_rng(&mut rng); let key_bytes = format!("{:?}", key.0); assert!(keys.insert(key_bytes), "Duplicate key generated!"); } } #[test] fn test_nonce_uniqueness() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let mut nonces = HashSet::new(); // Generate 1000 nonces and ensure they're all unique for _ in 0..1000 { let nonce = Nonce::with_rng(&mut rng); let nonce_bytes = format!("{:?}", nonce.0); assert!(nonces.insert(nonce_bytes), "Duplicate nonce generated!"); } } #[test] fn test_ciphertext_appears_random() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); // Encrypt the same plaintext with different nonces let associated_data: Vec<Felt> = vec![ONE; 8]; let plaintext = vec![ZERO; 10]; // All zeros let mut ciphertexts = Vec::new(); for _ in 0..100 { let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_elements_with_nonce(&plaintext, &associated_data, nonce).unwrap(); ciphertexts.push(encrypted.ciphertext); } // Ensure all ciphertexts are different (randomness test) for i in 0..ciphertexts.len() { for j in i + 1..ciphertexts.len() { assert_ne!( ciphertexts[i], ciphertexts[j], "Ciphertexts {i} and {j} are identical!", ); } } } #[test] fn test_secret_key_from_to_elements() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); // Generate a random key let key1 = SecretKey::with_rng(&mut rng); // Extract elements and reconstruct let elements = key1.to_elements(); let key2 = SecretKey::from_elements(elements); // Should be equal assert_eq!(key1, key2); // Should produce same ciphertext let plaintext = vec![Felt::new(42), Felt::new(100)]; let nonce = Nonce::with_rng(&mut rng); let encrypted1 = key1.encrypt_elements_with_nonce(&plaintext, &[], nonce.clone()).unwrap(); let encrypted2 = key2.encrypt_elements_with_nonce(&plaintext, &[], nonce).unwrap(); assert_eq!(encrypted1, encrypted2); } #[test] fn test_secret_key_debug_redaction() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key = SecretKey::with_rng(&mut rng); // Verify Debug impl produces expected redacted output let debug_output = format!("{key:?}"); assert_eq!(debug_output, "<elided secret for SecretKey>"); // Verify Display impl also elides let display_output = format!("{key}"); assert_eq!(display_output, "<elided secret for SecretKey>"); } #[test] fn test_secret_key_constant_time_equality() { let seed = [0_u8; 32]; let mut rng = ChaCha20Rng::from_seed(seed); let key1 = SecretKey::with_rng(&mut rng); let key2 = SecretKey::with_rng(&mut rng); let key1_clone = key1.clone(); // Same key should be equal assert_eq!(key1, key1_clone); // Different keys should not be equal assert_ne!(key1, key2); } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/src/aead/aead_rpo/mod.rs
miden-crypto/src/aead/aead_rpo/mod.rs
//! # Arithmetization Oriented AEAD //! //! This module implements an AEAD scheme optimized for speed within SNARKs/STARKs. //! The design is described in \[1\] and is based on the MonkeySpongeWrap construction and uses //! the RPO (Rescue Prime Optimized) permutation, creating an encryption scheme that is highly //! efficient when executed within zero-knowledge proof systems. //! //! \[1\] <https://eprint.iacr.org/2023/1668> use alloc::{string::ToString, vec::Vec}; use core::ops::Range; use miden_crypto_derive::{SilentDebug, SilentDisplay}; use num::Integer; use p3_field::{PrimeField64, RawDataSerializable, integers::QuotientMap}; use rand::{ Rng, distr::{Distribution, StandardUniform, Uniform}, }; use subtle::ConstantTimeEq; use crate::{ Felt, ONE, Word, ZERO, aead::{AeadScheme, DataType, EncryptionError}, hash::rpo::Rpo256, utils::{ ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, bytes_to_elements_exact, bytes_to_elements_with_padding, elements_to_bytes, padded_elements_to_bytes, zeroize::{Zeroize, ZeroizeOnDrop}, }, }; #[cfg(all(test, feature = "std"))] mod test; // CONSTANTS // ================================================================================================ /// Size of a secret key in field elements pub const SECRET_KEY_SIZE: usize = 4; /// Size of a secret key in bytes pub const SK_SIZE_BYTES: usize = SECRET_KEY_SIZE * Felt::NUM_BYTES; /// Size of a nonce in field elements pub const NONCE_SIZE: usize = 4; /// Size of a nonce in bytes pub const NONCE_SIZE_BYTES: usize = NONCE_SIZE * Felt::NUM_BYTES; /// Size of an authentication tag in field elements pub const AUTH_TAG_SIZE: usize = 4; /// Size of the sponge state field elements const STATE_WIDTH: usize = Rpo256::STATE_WIDTH; /// Capacity portion of the sponge state. const CAPACITY_RANGE: Range<usize> = Rpo256::CAPACITY_RANGE; /// Rate portion of the sponge state const RATE_RANGE: Range<usize> = Rpo256::RATE_RANGE; /// Size of the rate portion of the sponge state in field elements const RATE_WIDTH: usize = RATE_RANGE.end - RATE_RANGE.start; /// Size of either the 1st or 2nd half of the rate portion of the sponge state in field elements const HALF_RATE_WIDTH: usize = (Rpo256::RATE_RANGE.end - Rpo256::RATE_RANGE.start) / 2; /// First half of the rate portion of the sponge state const RATE_RANGE_FIRST_HALF: Range<usize> = Rpo256::RATE_RANGE.start..Rpo256::RATE_RANGE.start + HALF_RATE_WIDTH; /// Second half of the rate portion of the sponge state const RATE_RANGE_SECOND_HALF: Range<usize> = Rpo256::RATE_RANGE.start + HALF_RATE_WIDTH..Rpo256::RATE_RANGE.end; /// Index of the first element of the rate portion of the sponge state const RATE_START: usize = Rpo256::RATE_RANGE.start; /// Padding block used when the length of the data to encrypt is a multiple of `RATE_WIDTH` const PADDING_BLOCK: [Felt; RATE_WIDTH] = [ONE, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO]; // TYPES AND STRUCTURES // ================================================================================================ /// Encrypted data with its authentication tag #[derive(Debug, PartialEq, Eq)] pub struct EncryptedData { /// Indicates the original format of the data before encryption data_type: DataType, /// The encrypted ciphertext ciphertext: Vec<Felt>, /// The authentication tag attesting to the integrity of the ciphertext, and the associated /// data if it exists auth_tag: AuthTag, /// The nonce used during encryption nonce: Nonce, } impl EncryptedData { /// Constructs an EncryptedData from its component parts. pub fn from_parts( data_type: DataType, ciphertext: Vec<Felt>, auth_tag: AuthTag, nonce: Nonce, ) -> Self { Self { data_type, ciphertext, auth_tag, nonce } } /// Returns the data type of the encrypted data pub fn data_type(&self) -> DataType { self.data_type } /// Returns a reference to the ciphertext pub fn ciphertext(&self) -> &[Felt] { &self.ciphertext } /// Returns a reference to the authentication tag pub fn auth_tag(&self) -> &AuthTag { &self.auth_tag } /// Returns a reference to the nonce pub fn nonce(&self) -> &Nonce { &self.nonce } } /// An authentication tag represented as 4 field elements #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct AuthTag([Felt; AUTH_TAG_SIZE]); impl AuthTag { /// Constructs an AuthTag from an array of field elements. pub fn new(elements: [Felt; AUTH_TAG_SIZE]) -> Self { Self(elements) } /// Returns the authentication tag as an array of field elements pub fn to_elements(&self) -> [Felt; AUTH_TAG_SIZE] { self.0 } } /// A 256-bit secret key represented as 4 field elements #[derive(Clone, SilentDebug, SilentDisplay)] pub struct SecretKey([Felt; SECRET_KEY_SIZE]); impl SecretKey { // CONSTRUCTORS // -------------------------------------------------------------------------------------------- /// Creates a new random secret key using the default random number generator. #[cfg(feature = "std")] #[allow(clippy::new_without_default)] pub fn new() -> Self { let mut rng = rand::rng(); Self::with_rng(&mut rng) } /// Creates a new random secret key using the provided random number generator. pub fn with_rng<R: Rng>(rng: &mut R) -> Self { rng.sample(StandardUniform) } /// Creates a secret key from the provided array of field elements. /// /// # Security Warning /// This method should be used with caution. Secret keys must be derived from a /// cryptographically secure source of entropy. Do not use predictable or low-entropy /// values as secret key material. Prefer using `new()` or `with_rng()` with a /// cryptographically secure random number generator. pub fn from_elements(elements: [Felt; SECRET_KEY_SIZE]) -> Self { Self(elements) } // ACCESSORS // -------------------------------------------------------------------------------------------- /// Returns the secret key as an array of field elements. /// /// # Security Warning /// This method exposes the raw secret key material. Use with caution and ensure /// proper zeroization of the returned array when no longer needed. pub fn to_elements(&self) -> [Felt; SECRET_KEY_SIZE] { self.0 } // ELEMENT ENCRYPTION // -------------------------------------------------------------------------------------------- /// Encrypts and authenticates the provided sequence of field elements using this secret key /// and a random nonce. #[cfg(feature = "std")] pub fn encrypt_elements(&self, data: &[Felt]) -> Result<EncryptedData, EncryptionError> { self.encrypt_elements_with_associated_data(data, &[]) } /// Encrypts the provided sequence of field elements and authenticates both the ciphertext as /// well as the provided associated data using this secret key and a random nonce. #[cfg(feature = "std")] pub fn encrypt_elements_with_associated_data( &self, data: &[Felt], associated_data: &[Felt], ) -> Result<EncryptedData, EncryptionError> { let mut rng = rand::rng(); let nonce = Nonce::with_rng(&mut rng); self.encrypt_elements_with_nonce(data, associated_data, nonce) } /// Encrypts the provided sequence of field elements and authenticates both the ciphertext as /// well as the provided associated data using this secret key and the specified nonce. pub fn encrypt_elements_with_nonce( &self, data: &[Felt], associated_data: &[Felt], nonce: Nonce, ) -> Result<EncryptedData, EncryptionError> { // Initialize as sponge state with key and nonce let mut sponge = SpongeState::new(self, &nonce); // Process the associated data let padded_associated_data = pad(associated_data); padded_associated_data.chunks(RATE_WIDTH).for_each(|chunk| { sponge.duplex_overwrite(chunk); }); // Encrypt the data let mut ciphertext = Vec::with_capacity(data.len() + RATE_WIDTH); let data = pad(data); let mut data_block_iterator = data.chunks_exact(RATE_WIDTH); data_block_iterator.by_ref().for_each(|data_block| { let keystream = sponge.duplex_add(data_block); for (i, &plaintext_felt) in data_block.iter().enumerate() { ciphertext.push(plaintext_felt + keystream[i]); } }); // Generate authentication tag let auth_tag = sponge.squeeze_tag(); Ok(EncryptedData { data_type: DataType::Elements, ciphertext, auth_tag, nonce, }) } // BYTE ENCRYPTION // -------------------------------------------------------------------------------------------- /// Encrypts and authenticates the provided data using this secret key and a random nonce. /// /// Before encryption, the bytestring is converted to a sequence of field elements. #[cfg(feature = "std")] pub fn encrypt_bytes(&self, data: &[u8]) -> Result<EncryptedData, EncryptionError> { self.encrypt_bytes_with_associated_data(data, &[]) } /// Encrypts the provided data and authenticates both the ciphertext as well as the provided /// associated data using this secret key and a random nonce. /// /// Before encryption, both the data and the associated data are converted to sequences of /// field elements. #[cfg(feature = "std")] pub fn encrypt_bytes_with_associated_data( &self, data: &[u8], associated_data: &[u8], ) -> Result<EncryptedData, EncryptionError> { let mut rng = rand::rng(); let nonce = Nonce::with_rng(&mut rng); self.encrypt_bytes_with_nonce(data, associated_data, nonce) } /// Encrypts the provided data and authenticates both the ciphertext as well as the provided /// associated data using this secret key and the specified nonce. /// /// Before encryption, both the data and the associated data are converted to sequences of /// field elements. pub fn encrypt_bytes_with_nonce( &self, data: &[u8], associated_data: &[u8], nonce: Nonce, ) -> Result<EncryptedData, EncryptionError> { let data_felt = bytes_to_elements_with_padding(data); let ad_felt = bytes_to_elements_with_padding(associated_data); let mut encrypted_data = self.encrypt_elements_with_nonce(&data_felt, &ad_felt, nonce)?; encrypted_data.data_type = DataType::Bytes; Ok(encrypted_data) } // ELEMENT DECRYPTION // -------------------------------------------------------------------------------------------- /// Decrypts the provided encrypted data using this secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as bytes /// rather than as field elements. pub fn decrypt_elements( &self, encrypted_data: &EncryptedData, ) -> Result<Vec<Felt>, EncryptionError> { self.decrypt_elements_with_associated_data(encrypted_data, &[]) } /// Decrypts the provided encrypted data, given some associated data, using this secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as bytes /// rather than as field elements. pub fn decrypt_elements_with_associated_data( &self, encrypted_data: &EncryptedData, associated_data: &[Felt], ) -> Result<Vec<Felt>, EncryptionError> { if encrypted_data.data_type != DataType::Elements { return Err(EncryptionError::InvalidDataType { expected: DataType::Elements, found: encrypted_data.data_type, }); } self.decrypt_elements_with_associated_data_unchecked(encrypted_data, associated_data) } /// Decrypts the provided encrypted data, given some associated data, using this secret key. fn decrypt_elements_with_associated_data_unchecked( &self, encrypted_data: &EncryptedData, associated_data: &[Felt], ) -> Result<Vec<Felt>, EncryptionError> { if !encrypted_data.ciphertext.len().is_multiple_of(RATE_WIDTH) { return Err(EncryptionError::CiphertextLenNotMultipleRate); } // Initialize as sponge state with key and nonce let mut sponge = SpongeState::new(self, &encrypted_data.nonce); // Process the associated data let padded_associated_data = pad(associated_data); padded_associated_data.chunks(RATE_WIDTH).for_each(|chunk| { sponge.duplex_overwrite(chunk); }); // Decrypt the data let mut plaintext = Vec::with_capacity(encrypted_data.ciphertext.len()); let mut ciphertext_block_iterator = encrypted_data.ciphertext.chunks_exact(RATE_WIDTH); ciphertext_block_iterator.by_ref().for_each(|ciphertext_data_block| { let keystream = sponge.duplex_add(&[]); for (i, &ciphertext_felt) in ciphertext_data_block.iter().enumerate() { let plaintext_felt = ciphertext_felt - keystream[i]; plaintext.push(plaintext_felt); } sponge.state[RATE_RANGE].copy_from_slice(ciphertext_data_block); }); // Verify authentication tag let computed_tag = sponge.squeeze_tag(); if computed_tag != encrypted_data.auth_tag { return Err(EncryptionError::InvalidAuthTag); } // Remove padding and return unpad(plaintext) } // BYTE DECRYPTION // -------------------------------------------------------------------------------------------- /// Decrypts the provided encrypted data, as bytes, using this secret key. /// /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as elements /// rather than as bytes. pub fn decrypt_bytes( &self, encrypted_data: &EncryptedData, ) -> Result<Vec<u8>, EncryptionError> { self.decrypt_bytes_with_associated_data(encrypted_data, &[]) } /// Decrypts the provided encrypted data, as bytes, given some associated data using this /// secret key. /// /// # Errors /// Returns an error if decryption fails or if the underlying data was encrypted as elements /// rather than as bytes. pub fn decrypt_bytes_with_associated_data( &self, encrypted_data: &EncryptedData, associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { if encrypted_data.data_type != DataType::Bytes { return Err(EncryptionError::InvalidDataType { expected: DataType::Bytes, found: encrypted_data.data_type, }); } let ad_felt = bytes_to_elements_with_padding(associated_data); let data_felts = self.decrypt_elements_with_associated_data_unchecked(encrypted_data, &ad_felt)?; match padded_elements_to_bytes(&data_felts) { Some(bytes) => Ok(bytes), None => Err(EncryptionError::MalformedPadding), } } } impl Distribution<SecretKey> for StandardUniform { fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> SecretKey { let mut res = [ZERO; SECRET_KEY_SIZE]; let uni_dist = Uniform::new(0, Felt::ORDER_U64).expect("should not fail given the size of the field"); for r in res.iter_mut() { let sampled_integer = uni_dist.sample(rng); *r = Felt::new(sampled_integer); } SecretKey(res) } } impl PartialEq for SecretKey { fn eq(&self, other: &Self) -> bool { // Use constant-time comparison to prevent timing attacks let mut result = true; for (a, b) in self.0.iter().zip(other.0.iter()) { result &= bool::from(a.as_canonical_u64().ct_eq(&b.as_canonical_u64())); } result } } impl Eq for SecretKey {} impl Zeroize for SecretKey { /// Securely clears the shared secret from memory. /// /// # Security /// /// This implementation follows the same security methodology as the `zeroize` crate to ensure /// that sensitive cryptographic material is reliably cleared from memory: /// /// - **Volatile writes**: Uses `ptr::write_volatile` to prevent dead store elimination and /// other compiler optimizations that might remove the zeroing operation. /// - **Memory ordering**: Includes a sequentially consistent compiler fence (`SeqCst`) to /// prevent instruction reordering that could expose the secret data after this function /// returns. fn zeroize(&mut self) { for element in self.0.iter_mut() { unsafe { core::ptr::write_volatile(element, ZERO); } } core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } } // Manual Drop implementation to ensure zeroization on drop. impl Drop for SecretKey { fn drop(&mut self) { self.zeroize(); } } impl ZeroizeOnDrop for SecretKey {} // SPONGE STATE // ================================================================================================ /// Internal sponge state struct SpongeState { state: [Felt; STATE_WIDTH], } impl SpongeState { /// Creates a new sponge state fn new(sk: &SecretKey, nonce: &Nonce) -> Self { let mut state = [ZERO; STATE_WIDTH]; state[RATE_RANGE_FIRST_HALF].copy_from_slice(&sk.0); state[RATE_RANGE_SECOND_HALF].copy_from_slice(&nonce.0); Self { state } } /// Duplex interface as described in Algorithm 2 in [1] with `d = 0` /// /// /// [1]: https://eprint.iacr.org/2023/1668 fn duplex_overwrite(&mut self, data: &[Felt]) { self.permute(); // add 1 to the first capacity element self.state[CAPACITY_RANGE.start] += ONE; // overwrite the rate portion with `data` self.state[RATE_RANGE].copy_from_slice(data); } /// Duplex interface as described in Algorithm 2 in [1] with `d = 1` /// /// /// [1]: https://eprint.iacr.org/2023/1668 fn duplex_add(&mut self, data: &[Felt]) -> [Felt; RATE_WIDTH] { self.permute(); let squeezed_data = self.squeeze_rate(); for (idx, &element) in data.iter().enumerate() { self.state[RATE_START + idx] += element; } squeezed_data } /// Squeezes an authentication tag fn squeeze_tag(&mut self) -> AuthTag { self.permute(); AuthTag( self.state[RATE_RANGE_FIRST_HALF] .try_into() .expect("rate first half is exactly AUTH_TAG_SIZE elements"), ) } /// Applies the RPO permutation to the sponge state fn permute(&mut self) { Rpo256::apply_permutation(&mut self.state); } /// Squeeze the rate portion of the state fn squeeze_rate(&self) -> [Felt; RATE_WIDTH] { self.state[RATE_RANGE] .try_into() .expect("rate range is exactly RATE_WIDTH elements") } } // NONCE // ================================================================================================ /// A 256-bit nonce represented as 4 field elements #[derive(Clone, Debug, PartialEq, Eq)] pub struct Nonce([Felt; NONCE_SIZE]); impl Nonce { /// Creates a new random nonce using the provided random number generator pub fn with_rng<R: Rng>(rng: &mut R) -> Self { rng.sample(StandardUniform) } } impl From<Word> for Nonce { fn from(word: Word) -> Self { Nonce(word.into()) } } impl From<[Felt; NONCE_SIZE]> for Nonce { fn from(elements: [Felt; NONCE_SIZE]) -> Self { Nonce(elements) } } impl From<Nonce> for Word { fn from(nonce: Nonce) -> Self { nonce.0.into() } } impl From<Nonce> for [Felt; NONCE_SIZE] { fn from(nonce: Nonce) -> Self { nonce.0 } } impl Distribution<Nonce> for StandardUniform { fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Nonce { let mut res = [ZERO; NONCE_SIZE]; let uni_dist = Uniform::new(0, Felt::ORDER_U64).expect("should not fail given the size of the field"); for r in res.iter_mut() { let sampled_integer = uni_dist.sample(rng); *r = Felt::new(sampled_integer); } Nonce(res) } } // SERIALIZATION / DESERIALIZATION // ================================================================================================ impl Serializable for SecretKey { fn write_into<W: ByteWriter>(&self, target: &mut W) { let bytes = elements_to_bytes(&self.0); target.write_bytes(&bytes); } } impl Deserializable for SecretKey { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let bytes: [u8; SK_SIZE_BYTES] = source.read_array()?; match bytes_to_elements_exact(&bytes) { Some(inner) => { let inner: [Felt; 4] = inner.try_into().map_err(|_| { DeserializationError::InvalidValue("malformed secret key".to_string()) })?; Ok(Self(inner)) }, None => Err(DeserializationError::InvalidValue("malformed secret key".to_string())), } } } impl Serializable for Nonce { fn write_into<W: ByteWriter>(&self, target: &mut W) { let bytes = elements_to_bytes(&self.0); target.write_bytes(&bytes); } } impl Deserializable for Nonce { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let bytes: [u8; NONCE_SIZE_BYTES] = source.read_array()?; match bytes_to_elements_exact(&bytes) { Some(inner) => { let inner: [Felt; 4] = inner.try_into().map_err(|_| { DeserializationError::InvalidValue("malformed nonce".to_string()) })?; Ok(Self(inner)) }, None => Err(DeserializationError::InvalidValue("malformed nonce".to_string())), } } } impl Serializable for EncryptedData { fn write_into<W: ByteWriter>(&self, target: &mut W) { // we serialize field elements in their canonical form target.write_u8(self.data_type as u8); target.write_usize(self.ciphertext.len()); target.write_many(self.ciphertext.iter().map(Felt::as_canonical_u64)); target.write_many(self.nonce.0.iter().map(Felt::as_canonical_u64)); target.write_many(self.auth_tag.0.iter().map(Felt::as_canonical_u64)); } } impl Deserializable for EncryptedData { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let data_type_value: u8 = source.read_u8()?; let data_type = data_type_value.try_into().map_err(|_| { DeserializationError::InvalidValue("invalid data type value".to_string()) })?; let ciphertext_len = source.read_usize()?; let ciphertext_bytes = source.read_many(ciphertext_len)?; let ciphertext = felts_from_u64(ciphertext_bytes) .ok_or_else(|| DeserializationError::InvalidValue("invalid ciphertext".into()))?; let nonce = source.read_many(NONCE_SIZE)?; let nonce: [Felt; NONCE_SIZE] = felts_from_u64(nonce) .ok_or_else(|| DeserializationError::InvalidValue("invalid nonce".into()))? .try_into() .map_err(|_| { DeserializationError::InvalidValue("nonce conversion failed".to_string()) })?; let tag = source.read_many(AUTH_TAG_SIZE)?; let tag: [Felt; AUTH_TAG_SIZE] = felts_from_u64(tag) .ok_or_else(|| DeserializationError::InvalidValue("invalid tag".into()))? .try_into() .expect("deserialization reads exactly AUTH_TAG_SIZE elements"); Ok(Self { ciphertext, nonce: Nonce(nonce), auth_tag: AuthTag(tag), data_type, }) } } // HELPERS // ================================================================================================ /// Performs padding on either the plaintext or associated data. /// /// # Padding Scheme /// /// This AEAD implementation uses an injective padding scheme to ensure that different plaintexts /// always produce different ciphertexts, preventing ambiguity during decryption. /// /// ## Data Padding /// /// Plaintext data is padded using a 10* padding scheme: /// /// - A padding separator (field element `ONE`) is appended to the message. /// - The message is then zero-padded to reach the next rate boundary. /// - **Security guarantee**: `[ONE]` and `[ONE, ZERO]` will produce different ciphertexts because /// after padding they become `[ONE, ONE, 0, 0, ...]` and `[ONE, ZERO, ONE, 0, ...]` respectively, /// ensuring injectivity. /// /// ## Associated Data Padding /// /// Associated data follows the same injective padding scheme: /// /// - Padding separator (`ONE`) is appended. /// - Zero-padded to rate boundary. /// - **Security guarantee**: Different associated data inputs (like `[ONE]` vs `[ONE, ZERO]`) /// produce different authentication tags due to the injective padding. fn pad(data: &[Felt]) -> Vec<Felt> { // if data length is a multiple of 8, padding_elements will be 8 let num_elem_final_block = data.len() % RATE_WIDTH; let padding_elements = RATE_WIDTH - num_elem_final_block; let mut result = data.to_vec(); result.extend_from_slice(&PADDING_BLOCK[..padding_elements]); result } /// Removes the padding from the decoded ciphertext. fn unpad(mut plaintext: Vec<Felt>) -> Result<Vec<Felt>, EncryptionError> { let (num_blocks, remainder) = plaintext.len().div_rem(&RATE_WIDTH); assert_eq!(remainder, 0); let final_block: &[Felt; RATE_WIDTH] = plaintext.last_chunk().ok_or(EncryptionError::MalformedPadding)?; let pos = match final_block.iter().rposition(|entry| *entry == ONE) { Some(pos) => pos, None => return Err(EncryptionError::MalformedPadding), }; plaintext.truncate((num_blocks - 1) * RATE_WIDTH + pos); Ok(plaintext) } /// Converts a vector of u64 values into a vector of field elements, returning `None` if any of /// the u64 values is not a valid field element. fn felts_from_u64(input: Vec<u64>) -> Option<Vec<Felt>> { input.into_iter().map(Felt::from_canonical_checked).collect() } // AEAD SCHEME IMPLEMENTATION // ================================================================================================ /// RPO256-based AEAD scheme implementation pub struct AeadRpo; impl AeadScheme for AeadRpo { const KEY_SIZE: usize = SK_SIZE_BYTES; type Key = SecretKey; fn key_from_bytes(bytes: &[u8]) -> Result<Self::Key, EncryptionError> { SecretKey::read_from_bytes(bytes).map_err(|_| EncryptionError::FailedOperation) } fn encrypt_bytes<R: rand::CryptoRng + rand::RngCore>( key: &Self::Key, rng: &mut R, plaintext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { let nonce = Nonce::with_rng(rng); let encrypted_data = key .encrypt_bytes_with_nonce(plaintext, associated_data, nonce) .map_err(|_| EncryptionError::FailedOperation)?; Ok(encrypted_data.to_bytes()) } fn decrypt_bytes_with_associated_data( key: &Self::Key, ciphertext: &[u8], associated_data: &[u8], ) -> Result<Vec<u8>, EncryptionError> { let encrypted_data = EncryptedData::read_from_bytes(ciphertext) .map_err(|_| EncryptionError::FailedOperation)?; key.decrypt_bytes_with_associated_data(&encrypted_data, associated_data) } // OPTIMIZED FELT METHODS // -------------------------------------------------------------------------------------------- fn encrypt_elements<R: rand::CryptoRng + rand::RngCore>( key: &Self::Key, rng: &mut R, plaintext: &[Felt], associated_data: &[Felt], ) -> Result<Vec<u8>, EncryptionError> { let nonce = Nonce::with_rng(rng); let encrypted_data = key .encrypt_elements_with_nonce(plaintext, associated_data, nonce) .map_err(|_| EncryptionError::FailedOperation)?; Ok(encrypted_data.to_bytes()) } fn decrypt_elements_with_associated_data( key: &Self::Key, ciphertext: &[u8], associated_data: &[Felt], ) -> Result<Vec<Felt>, EncryptionError> { let encrypted_data = EncryptedData::read_from_bytes(ciphertext) .map_err(|_| EncryptionError::FailedOperation)?; key.decrypt_elements_with_associated_data(&encrypted_data, associated_data) } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/tests/rocksdb_large_smt.rs
miden-crypto/tests/rocksdb_large_smt.rs
use miden_crypto::{ EMPTY_WORD, Felt, ONE, WORD_SIZE, Word, ZERO, merkle::{ InnerNodeInfo, smt::{LargeSmt, LargeSmtError, RocksDbConfig, RocksDbStorage}, }, }; use tempfile::TempDir; fn setup_storage() -> (RocksDbStorage, TempDir) { let temp_dir = tempfile::Builder::new() .prefix("test_smt_rocksdb_") .tempdir() .expect("Failed to create temporary directory for RocksDB test"); let db_path = temp_dir.path().to_path_buf(); let storage = RocksDbStorage::open(RocksDbConfig::new(db_path)) .expect("Failed to open RocksDbStorage in temporary directory"); (storage, temp_dir) } fn generate_entries(pair_count: usize) -> Vec<(Word, Word)> { (0..pair_count) .map(|i| { let key = Word::new([ONE, ONE, Felt::new(i as u64), Felt::new(i as u64 % 1000)]); let value = Word::new([ONE, ONE, ONE, Felt::new(i as u64)]); (key, value) }) .collect() } #[test] fn rocksdb_sanity_insert_and_get() { let (storage, _tmp) = setup_storage(); let mut smt = LargeSmt::<RocksDbStorage>::new(storage).unwrap(); let key = Word::new([ONE, ONE, ONE, ONE]); let val = Word::new([ONE; WORD_SIZE]); let prev = smt.insert(key, val).unwrap(); assert_eq!(prev, EMPTY_WORD); assert_eq!(smt.get_value(&key), val); } #[test] fn rocksdb_persistence_reopen() { let entries = generate_entries(1000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); let root = smt.root(); let mut inner_nodes: Vec<InnerNodeInfo> = smt.inner_nodes().unwrap().collect(); inner_nodes.sort_by_key(|info| info.value); drop(smt); let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let smt = LargeSmt::<RocksDbStorage>::load(reopened_storage).unwrap(); let mut inner_nodes_2: Vec<InnerNodeInfo> = smt.inner_nodes().unwrap().collect(); inner_nodes_2.sort_by_key(|info| info.value); assert_eq!(inner_nodes.len(), inner_nodes_2.len()); assert_eq!(inner_nodes, inner_nodes_2); assert_eq!(smt.root(), root); } #[test] fn rocksdb_persistence_after_insertion() { let entries = generate_entries(1000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let mut smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); let key = Word::new([ONE, ONE, ONE, ONE]); let new_value = Word::new([Felt::new(2), Felt::new(2), Felt::new(2), Felt::new(2)]); smt.insert(key, new_value).unwrap(); let root = smt.root(); let mut inner_nodes: Vec<InnerNodeInfo> = smt.inner_nodes().unwrap().collect(); inner_nodes.sort_by_key(|info| info.value); drop(smt); let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let smt = LargeSmt::<RocksDbStorage>::load(reopened_storage).unwrap(); let mut inner_nodes_2: Vec<InnerNodeInfo> = smt.inner_nodes().unwrap().collect(); inner_nodes_2.sort_by_key(|info| info.value); assert_eq!(inner_nodes.len(), inner_nodes_2.len()); assert_eq!(inner_nodes, inner_nodes_2); assert_eq!(smt.root(), root); } #[test] fn rocksdb_persistence_after_insert_batch_with_deletions() { // Create a tree with initial entries let entries = generate_entries(10_000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let mut smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); // Create a batch that includes both insertions and deletions let mut batch_entries: Vec<(Word, Word)> = Vec::new(); // Add new entries for i in 20_000..25_000 { let key = Word::new([ONE, ONE, Felt::new(i as u64), Felt::new(i as u64 % 1000)]); let value = Word::new([ONE, ONE, ONE, Felt::new(i as u64)]); batch_entries.push((key, value)); } // Delete some existing entries for i in 0..1000 { let key = Word::new([ONE, ONE, Felt::new(i as u64), Felt::new(i as u64 % 1000)]); batch_entries.push((key, EMPTY_WORD)); } smt.insert_batch(batch_entries).unwrap(); let root = smt.root(); let mut inner_nodes: Vec<InnerNodeInfo> = smt.inner_nodes().unwrap().collect(); inner_nodes.sort_by_key(|info| info.value); let num_leaves = smt.num_leaves(); let num_entries = smt.num_entries(); drop(smt); let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let smt = LargeSmt::<RocksDbStorage>::load(reopened_storage).unwrap(); let mut inner_nodes_2: Vec<InnerNodeInfo> = smt.inner_nodes().unwrap().collect(); inner_nodes_2.sort_by_key(|info| info.value); let num_leaves_2 = smt.num_leaves(); let num_entries_2 = smt.num_entries(); assert_eq!(inner_nodes.len(), inner_nodes_2.len()); assert_eq!(inner_nodes, inner_nodes_2); assert_eq!(num_leaves, num_leaves_2); assert_eq!(num_entries, num_entries_2); assert_eq!(smt.root(), root, "Tree reconstruction failed - root mismatch after deletions"); } #[test] fn rocksdb_load_with_root_validates_correctly() { let entries = generate_entries(1000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); let expected_root = smt.root(); drop(smt); // Reopen with the correct expected root let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let smt = LargeSmt::load_with_root(reopened_storage, expected_root) .expect("Should successfully open with correct root"); assert_eq!(smt.root(), expected_root); } #[test] fn rocksdb_load_with_root_mismatch_returns_error() { let entries = generate_entries(1000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); let actual_root = smt.root(); drop(smt); // Try to reopen with a wrong root let wrong_root = Word::new([ONE; 4]); assert_ne!(wrong_root, actual_root, "Test requires different roots"); let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let result = LargeSmt::load_with_root(reopened_storage, wrong_root); assert!(result.is_err(), "Should fail with wrong root"); match result.unwrap_err() { LargeSmtError::RootMismatch { expected, actual } => { assert_eq!(expected, wrong_root); assert_eq!(actual, actual_root); }, other => panic!("Expected RootMismatch error, got {:?}", other), } } #[test] fn rocksdb_load_skips_validation() { let entries = generate_entries(1000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); let expected_root = smt.root(); drop(smt); // load should succeed let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let smt = LargeSmt::load(reopened_storage).expect("Should successfully open without validation"); assert_eq!(smt.root(), expected_root); } #[test] fn rocksdb_new_fails_on_non_empty_storage() { let entries = generate_entries(1000); let (initial_storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); // Create a tree with data let smt = LargeSmt::<RocksDbStorage>::with_entries(initial_storage, entries).unwrap(); drop(smt); // Reopen storage and try to use new() - should fail let reopened_storage = RocksDbStorage::open(RocksDbConfig::new(db_path)).unwrap(); let result = LargeSmt::new(reopened_storage); assert!(result.is_err(), "new() should fail on non-empty storage"); match result.unwrap_err() { LargeSmtError::StorageNotEmpty => {}, other => panic!("Expected StorageNotEmpty error, got {:?}", other), } } // Tests entry/leaf counts through the full lifecycle of a leaf: // Empty -> Single -> Multiple -> Single -> Empty #[test] fn rocksdb_entry_count_through_leaf_lifecycle() { let (storage, temp_dir_guard) = setup_storage(); let db_path = temp_dir_guard.path().to_path_buf(); let mut smt = LargeSmt::new(storage).unwrap(); // Two keys that map to the same leaf let key1 = Word::new([ZERO, ZERO, ZERO, ZERO]); let key2 = Word::new([ONE, ZERO, ZERO, ZERO]); let value = Word::new([ONE, ONE, ONE, ONE]); // Initial state: empty assert_eq!(smt.num_entries(), 0); assert_eq!(smt.num_leaves(), 0); // Add first key: Empty -> Single let mutations = smt.compute_mutations([(key1, value)]).unwrap(); smt.apply_mutations(mutations).unwrap(); assert_eq!(smt.num_entries(), 1, "should have 1 entry after first insert"); assert_eq!(smt.num_leaves(), 1, "should have 1 leaf after first insert"); // Add second key to same leaf: Single -> Multiple let mutations = smt.compute_mutations([(key2, value)]).unwrap(); smt.apply_mutations(mutations).unwrap(); assert_eq!(smt.num_entries(), 2, "should have 2 entries after second insert"); assert_eq!(smt.num_leaves(), 1, "should still have 1 leaf (now Multiple)"); // Remove first key: Multiple -> Single let mutations = smt.compute_mutations([(key1, EMPTY_WORD)]).unwrap(); smt.apply_mutations(mutations).unwrap(); assert_eq!(smt.num_entries(), 1, "should have 1 entry after removal from Multiple"); assert_eq!(smt.num_leaves(), 1, "should still have 1 leaf (now Single)"); // Remove second key: Single -> Empty let mutations = smt.compute_mutations([(key2, EMPTY_WORD)]).unwrap(); smt.apply_mutations(mutations).unwrap(); assert_eq!(smt.num_entries(), 0, "should have 0 entries after removing all"); assert_eq!(smt.num_leaves(), 0, "should have 0 leaves after removing all"); // Verify persistence through the lifecycle drop(smt); let storage = RocksDbStorage::open(RocksDbConfig::new(&db_path)).unwrap(); let smt = LargeSmt::load(storage).unwrap(); assert_eq!(smt.num_entries(), 0, "persisted entry count should be 0"); assert_eq!(smt.num_leaves(), 0, "persisted leaf count should be 0"); }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/store.rs
miden-crypto/benches/store.rs
use std::hint::black_box; use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main}; use miden_crypto::{ Felt, Word, merkle::{ MerkleTree, NodeIndex, smt::{LeafIndex, SMT_MAX_DEPTH, SimpleSmt}, store::MerkleStore, }, rand::test_utils::{rand_array, rand_value}, }; /// Since MerkleTree can only be created when a power-of-two number of elements is used, the sample /// sizes are limited to that. static BATCH_SIZES: [usize; 3] = [2usize.pow(4), 2usize.pow(7), 2usize.pow(10)]; /// Generates a random `Word`. fn random_word() -> Word { rand_array::<Felt, 4>().into() } /// Generates an index at the specified depth in `0..range`. fn random_index(range: u64, depth: u8) -> NodeIndex { let value = rand_value::<u64>() % range; NodeIndex::new(depth, value).unwrap() } /// Benchmarks getting an empty leaf from the SMT and MerkleStore backends. fn get_empty_leaf_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_empty_leaf_simplesmt"); const DEPTH: u8 = SMT_MAX_DEPTH; let size = u64::MAX; // both SMT and the store are pre-populated with empty hashes, accessing these values is what is // being benchmarked here, so no values are inserted into the backends let smt = SimpleSmt::<DEPTH>::new().unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); group.bench_function(BenchmarkId::new("SimpleSmt", DEPTH), |b| { b.iter_batched( || random_index(size, DEPTH), |index| black_box(smt.get_node(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", DEPTH), |b| { b.iter_batched( || random_index(size, DEPTH), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) }); } /// Benchmarks getting a leaf on Merkle trees and Merkle stores of varying power-of-two sizes. fn get_leaf_merkletree(c: &mut Criterion) { let mut group = c.benchmark_group("get_leaf_merkletree"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let mtree = MerkleTree::new(leaves).unwrap(); let store = MerkleStore::from(&mtree); let depth = mtree.depth(); let root = mtree.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("MerkleTree", size), |b| { b.iter_batched( || random_index(size_u64, depth), |index| black_box(mtree.get_node(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || random_index(size_u64, depth), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) }); } } /// Benchmarks getting a leaf on SMT and Merkle stores of varying power-of-two sizes. fn get_leaf_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_leaf_simplesmt"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let smt_leaves = leaves .iter() .enumerate() .map(|(c, &v)| (c.try_into().unwrap(), v)) .collect::<Vec<(u64, Word)>>(); let smt = SimpleSmt::<SMT_MAX_DEPTH>::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { b.iter_batched( || random_index(size_u64, SMT_MAX_DEPTH), |index| black_box(smt.get_node(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || random_index(size_u64, SMT_MAX_DEPTH), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) }); } } /// Benchmarks getting a node at half of the depth of an empty SMT and an empty Merkle store. fn get_node_of_empty_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_node_of_empty_simplesmt"); const DEPTH: u8 = SMT_MAX_DEPTH; // both SMT and the store are pre-populated with the empty hashes, accessing the internal nodes // of these values is what is being benchmarked here, so no values are inserted into the // backends. let smt = SimpleSmt::<DEPTH>::new().unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); let half_depth = DEPTH / 2; let half_size = 2_u64.pow(half_depth as u32); group.bench_function(BenchmarkId::new("SimpleSmt", DEPTH), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(smt.get_node(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", DEPTH), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) }); } /// Benchmarks getting a node at half of the depth of a Merkle tree and Merkle store of varying /// power-of-two sizes. fn get_node_merkletree(c: &mut Criterion) { let mut group = c.benchmark_group("get_node_merkletree"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let mtree = MerkleTree::new(leaves).unwrap(); let store = MerkleStore::from(&mtree); let root = mtree.root(); let half_depth = mtree.depth() / 2; let half_size = 2_u64.pow(half_depth as u32); group.bench_function(BenchmarkId::new("MerkleTree", size), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(mtree.get_node(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) }); } } /// Benchmarks getting a node at half the depth on SMT and Merkle stores of varying power-of-two /// sizes. fn get_node_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_node_simplesmt"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let smt_leaves = leaves .iter() .enumerate() .map(|(c, &v)| (c.try_into().unwrap(), v)) .collect::<Vec<(u64, Word)>>(); let smt = SimpleSmt::<SMT_MAX_DEPTH>::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); let half_depth = SMT_MAX_DEPTH / 2; let half_size = 2_u64.pow(half_depth as u32); group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(smt.get_node(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || random_index(half_size, half_depth), |index| black_box(store.get_node(root, index)), BatchSize::SmallInput, ) }); } } /// Benchmarks getting a path of a leaf on the Merkle tree and Merkle store backends. fn get_leaf_path_merkletree(c: &mut Criterion) { let mut group = c.benchmark_group("get_leaf_path_merkletree"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let mtree = MerkleTree::new(leaves).unwrap(); let store = MerkleStore::from(&mtree); let depth = mtree.depth(); let root = mtree.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("MerkleTree", size), |b| { b.iter_batched( || random_index(size_u64, depth), |index| black_box(mtree.get_path(index)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || random_index(size_u64, depth), |index| black_box(store.get_path(root, index)), BatchSize::SmallInput, ) }); } } /// Benchmarks getting a path of a leaf on the SMT and Merkle store backends. fn get_leaf_path_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("get_leaf_path_simplesmt"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let smt_leaves = leaves .iter() .enumerate() .map(|(c, &v)| (c.try_into().unwrap(), v)) .collect::<Vec<(u64, Word)>>(); let smt = SimpleSmt::<SMT_MAX_DEPTH>::with_leaves(smt_leaves.clone()).unwrap(); let store = MerkleStore::from(&smt); let root = smt.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("SimpleSmt", size), |b| { b.iter_batched( || random_index(size_u64, SMT_MAX_DEPTH), |index| { black_box(smt.open(&LeafIndex::<SMT_MAX_DEPTH>::new(index.value()).unwrap())) }, BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || random_index(size_u64, SMT_MAX_DEPTH), |index| black_box(store.get_path(root, index)), BatchSize::SmallInput, ) }); } } /// Benchmarks creation of the different storage backends fn new(c: &mut Criterion) { let mut group = c.benchmark_group("new"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; // MerkleTree constructor is optimized to work with vectors. Create a new copy of the data // and pass it to the benchmark function group.bench_function(BenchmarkId::new("MerkleTree::new", size), |b| { b.iter_batched(|| leaves, |l| black_box(MerkleTree::new(l)), BatchSize::SmallInput) }); // This could be done with `bench_with_input`, however to remove variables while comparing // with MerkleTree it is using `iter_batched` group.bench_function(BenchmarkId::new("MerkleStore::extend::MerkleTree", size), |b| { b.iter_batched( || leaves, |l| { let mtree = MerkleTree::new(l).unwrap(); black_box(MerkleStore::from(&mtree)); }, BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("SimpleSmt::new", size), |b| { b.iter_batched( || { leaves .iter() .enumerate() .map(|(c, &v)| (c.try_into().unwrap(), v)) .collect::<Vec<(u64, Word)>>() }, |l| black_box(SimpleSmt::<SMT_MAX_DEPTH>::with_leaves(l)), BatchSize::SmallInput, ) }); group.bench_function(BenchmarkId::new("MerkleStore::extend::SimpleSmt", size), |b| { b.iter_batched( || { leaves .iter() .enumerate() .map(|(c, &v)| (c.try_into().unwrap(), v)) .collect::<Vec<(u64, Word)>>() }, |l| { let smt = SimpleSmt::<SMT_MAX_DEPTH>::with_leaves(l).unwrap(); black_box(MerkleStore::from(&smt)); }, BatchSize::SmallInput, ) }); } } /// Benchmarks updating a leaf on MerkleTree and MerkleStore backends. fn update_leaf_merkletree(c: &mut Criterion) { let mut group = c.benchmark_group("update_leaf_merkletree"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let mut mtree = MerkleTree::new(leaves).unwrap(); let mut store = MerkleStore::from(&mtree); let depth = mtree.depth(); let root = mtree.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("MerkleTree", size), |b| { b.iter_batched( || (rand_value::<u64>() % size_u64, random_word()), |(index, value)| black_box(mtree.update_leaf(index, value)), BatchSize::SmallInput, ) }); let mut store_root = root; group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || (random_index(size_u64, depth), random_word()), |(index, value)| { // The MerkleTree automatically updates its internal root, the Store maintains // the old root and adds the new one. Here we update the root to have a fair // comparison store_root = store.set_node(root, index, value).unwrap().root; black_box(store_root) }, BatchSize::SmallInput, ) }); } } /// Benchmarks updating a leaf on SMT and MerkleStore backends. fn update_leaf_simplesmt(c: &mut Criterion) { let mut group = c.benchmark_group("update_leaf_simplesmt"); let random_data_size = BATCH_SIZES.into_iter().max().unwrap(); let random_data: Vec<Word> = (0..random_data_size).map(|_| random_word()).collect(); for size in BATCH_SIZES { let leaves = &random_data[..size]; let smt_leaves = leaves .iter() .enumerate() .map(|(c, &v)| (c.try_into().unwrap(), v)) .collect::<Vec<(u64, Word)>>(); let mut smt = SimpleSmt::<SMT_MAX_DEPTH>::with_leaves(smt_leaves.clone()).unwrap(); let mut store = MerkleStore::from(&smt); let root = smt.root(); let size_u64 = size as u64; group.bench_function(BenchmarkId::new("SimpleSMT", size), |b| { b.iter_batched( || (rand_value::<u64>() % size_u64, random_word()), |(index, value)| { black_box(smt.insert(LeafIndex::<SMT_MAX_DEPTH>::new(index).unwrap(), value)) }, BatchSize::SmallInput, ) }); let mut store_root = root; group.bench_function(BenchmarkId::new("MerkleStore", size), |b| { b.iter_batched( || (random_index(size_u64, SMT_MAX_DEPTH), random_word()), |(index, value)| { // The MerkleTree automatically updates its internal root, the Store maintains // the old root and adds the new one. Here we update the root to have a fair // comparison store_root = store.set_node(root, index, value).unwrap().root; black_box(store_root) }, BatchSize::SmallInput, ) }); } } criterion_group!( store_group, get_empty_leaf_simplesmt, get_leaf_merkletree, get_leaf_path_merkletree, get_leaf_path_simplesmt, get_leaf_simplesmt, get_node_merkletree, get_node_of_empty_simplesmt, get_node_simplesmt, new, update_leaf_merkletree, update_leaf_simplesmt, ); criterion_main!(store_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/encryption.rs
miden-crypto/benches/encryption.rs
use std::hint::black_box; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; use miden_crypto::Felt; mod common; use common::{ config::{DATA_SIZES, FELT_SIZES}, data::{ generate_byte_array_random, generate_byte_array_sequential, generate_felt_array_random, generate_felt_array_sequential, }, }; benchmark_aead_bytes!(aead_rpo, "AEAD RPO", bench_aead_rpo_bytes, aead_rpo_bytes_group); benchmark_aead_field!(aead_rpo, "AEAD RPO", bench_aead_rpo_felts, aead_rpo_felts_group); benchmark_aead_bytes!( xchacha, "AEAD XChaCha20-Poly1305", bench_aead_xchacha_bytes, aead_xchacha_bytes_group ); benchmark_aead_field!( xchacha, "AEAD XChaCha20-Poly1305", bench_aead_xchacha_felts, aead_xchacha_felts_group ); // Running the benchmarks: criterion_main!( aead_rpo_bytes_group, aead_rpo_felts_group, aead_xchacha_bytes_group, aead_xchacha_felts_group );
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/dsa.rs
miden-crypto/benches/dsa.rs
//! Comprehensive Digital Signature Algorithm (DSA) benchmarks //! //! This module benchmarks all DSA operations implemented in the library: //! - RPO-Falcon512 (Falcon using RPO for hashing) //! - ECDSA over secp256k1 (using Keccak for hashing) //! - EdDSA (Ed25519 using SHA-512) //! //! # Organization //! //! The benchmarks are organized by: //! 1. Key generation operations //! 2. Signing operations (with and without RNG) //! 3. Verification operations //! //! # Adding New DSA Benchmarks //! //! To add benchmarks for new DSA algorithms: //! 1. Add the algorithm to the imports //! 2. Add parameterized benchmark functions following the naming convention //! 3. Add to the appropriate benchmark group //! 4. Update input size arrays in config.rs if needed use std::hint::black_box; use criterion::{Criterion, criterion_group, criterion_main}; // Import DSA modules use miden_crypto::{ Felt, Word, dsa::{ ecdsa_k256_keccak, eddsa_25519_sha512, falcon512_rpo::{self, PublicKey as RpoPublicKey, SecretKey as RpoSecretKey}, }, }; use rand::rng; // Import common utilities mod common; use common::*; // Import configuration constants use crate::config::{DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE}; /// Configuration for key generation benchmarks const KEYGEN_ITERATIONS: usize = 10; // ================================================================================================ // RPO-FALCON512 BENCHMARKS // ================================================================================================ // === Key Generation Benchmarks === // Secret key generation without RNG benchmark_with_setup! { falcon512_rpo_keygen_secret_default, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "falcon512_rpo_keygen_secret", || {}, |b: &mut criterion::Bencher| { b.iter(|| { let _secret_key = RpoSecretKey::new(); }) }, } // Secret key generation with custom RNG benchmark_with_setup_data! { falcon512_rpo_keygen_secret_with_rng, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "falcon512_rpo_keygen_secret_with_rng", || { rng() }, |b: &mut criterion::Bencher, rng: &rand::rngs::ThreadRng| { b.iter(|| { let mut rng_clone = rng.clone(); let _secret_key = RpoSecretKey::with_rng(&mut rng_clone); }) }, } // Public key generation from secret key benchmark_with_setup_data! { falcon512_rpo_keygen_public, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "falcon512_rpo_keygen_public", || { let secret_keys: Vec<RpoSecretKey> = (0..KEYGEN_ITERATIONS).map(|_| RpoSecretKey::new()).collect(); secret_keys }, |b: &mut criterion::Bencher, secret_keys: &Vec<RpoSecretKey>| { b.iter(|| { for secret_key in secret_keys { let _public_key = secret_key.public_key(); } }) }, } // === Signing Benchmarks === // Message signing without RNG benchmark_with_setup_data! { falcon512_rpo_sign_default, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "falcon512_rpo_sign", || { let secret_keys: Vec<RpoSecretKey> = (0..KEYGEN_ITERATIONS).map(|_| RpoSecretKey::new()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); (secret_keys, messages) }, |b: &mut criterion::Bencher, (secret_keys, messages): &(Vec<RpoSecretKey>, Vec<Word>)| { b.iter(|| { for (secret_key, message) in secret_keys.iter().zip(messages.iter()) { let _signature = secret_key.sign(black_box(*message)); } }) }, } // Message signing with custom RNG benchmark_with_setup_data! { falcon512_rpo_sign_with_rng, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "falcon512_rpo_sign_with_rng", || { let secret_keys: Vec<RpoSecretKey> = (0..KEYGEN_ITERATIONS).map(|_| RpoSecretKey::new()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); let rngs: Vec<_> = (0..KEYGEN_ITERATIONS).map(|_| rng()).collect(); (secret_keys, messages, rngs) }, |b: &mut criterion::Bencher, (secret_keys, messages, rngs): &(Vec<RpoSecretKey>, Vec<Word>, Vec<_>)| { b.iter(|| { let mut rngs_local = rngs.clone(); for ((secret_key, message), rng) in secret_keys.iter().zip(messages.iter()).zip(rngs_local.iter_mut()) { let _signature = secret_key.sign_with_rng(black_box(*message), rng); } }) }, } // === Verification Benchmarks === // Signature verification benchmark_with_setup_data! { falcon512_rpo_verify, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "falcon512_rpo_verify", || { let mut rng = rand::rngs::ThreadRng::default(); let secret_keys: Vec<RpoSecretKey> = (0..KEYGEN_ITERATIONS).map(|_| RpoSecretKey::with_rng(&mut rng)).collect(); let public_keys: Vec<RpoPublicKey> = secret_keys.iter().map(|sk| sk.public_key()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); let signatures: Vec<falcon512_rpo::Signature> = secret_keys .iter() .zip(messages.iter()) .map(|(sk, msg)| sk.sign_with_rng(black_box(*msg), &mut rng)) .collect(); (public_keys, messages, signatures) }, |b: &mut criterion::Bencher, (public_keys, messages, signatures): &(Vec<RpoPublicKey>, Vec<Word>, Vec<falcon512_rpo::Signature>)| { b.iter(|| { for ((public_key, message), signature) in public_keys.iter().zip(messages.iter()).zip(signatures.iter()) { let _result = public_key.verify(black_box(*message), signature); } }) }, } // ================================================================================================ // ECDSA K256 BENCHMARKS (using Keccak) // ================================================================================================ // === Key Generation Benchmarks === benchmark_with_setup! { ecdsa_k256_keygen_secret_default, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "ecdsa_k256_keygen_secret", || {}, |b: &mut criterion::Bencher| { b.iter(|| { let _secret_key = ecdsa_k256_keccak::SecretKey::new(); }) }, } benchmark_with_setup_data! { ecdsa_k256_keygen_secret_with_rng, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "ecdsa_k256_keygen_secret_with_rng", || { rng() }, |b: &mut criterion::Bencher, rng: &rand::rngs::ThreadRng| { b.iter(|| { let mut rng_clone = rng.clone(); let _secret_key = ecdsa_k256_keccak::SecretKey::with_rng(&mut rng_clone); }) }, } benchmark_with_setup_data! { ecdsa_k256_keygen_public, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "ecdsa_k256_keygen_public", || { let secret_keys: Vec<ecdsa_k256_keccak::SecretKey> = (0..KEYGEN_ITERATIONS).map(|_| ecdsa_k256_keccak::SecretKey::new()).collect(); secret_keys }, |b: &mut criterion::Bencher, secret_keys: &Vec<ecdsa_k256_keccak::SecretKey>| { b.iter(|| { for secret_key in secret_keys { let _public_key = secret_key.public_key(); } }) }, } // === Signing Benchmarks === benchmark_with_setup_data! { ecdsa_k256_sign, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "ecdsa_k256_sign", || { let secret_keys: Vec<ecdsa_k256_keccak::SecretKey> = (0..KEYGEN_ITERATIONS).map(|_| ecdsa_k256_keccak::SecretKey::new()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); (secret_keys, messages) }, |b: &mut criterion::Bencher, (secret_keys, messages): &(Vec<ecdsa_k256_keccak::SecretKey>, Vec<Word>)| { b.iter(|| { // Clone secret keys since sign() needs &mut self let mut secret_keys_local = secret_keys.clone(); for (secret_key, message) in secret_keys_local.iter_mut().zip(messages.iter()) { let _signature = secret_key.sign(black_box(*message)); } }) }, } // === Verification Benchmarks === benchmark_with_setup_data! { ecdsa_k256_verify, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "ecdsa_k256_verify", || { let mut rng = rand::rngs::ThreadRng::default(); let mut secret_keys: Vec<ecdsa_k256_keccak::SecretKey> = (0..KEYGEN_ITERATIONS).map(|_| ecdsa_k256_keccak::SecretKey::with_rng(&mut rng)).collect(); let public_keys: Vec<ecdsa_k256_keccak::PublicKey> = secret_keys.iter().map(|sk| sk.public_key()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); let signatures: Vec<ecdsa_k256_keccak::Signature> = secret_keys .iter_mut() .zip(messages.iter()) .map(|(sk, msg)| sk.sign(black_box(*msg))) .collect(); (public_keys, messages, signatures) }, |b: &mut criterion::Bencher, (public_keys, messages, signatures): &(Vec<ecdsa_k256_keccak::PublicKey>, Vec<Word>, Vec<ecdsa_k256_keccak::Signature>)| { b.iter(|| { for ((public_key, message), signature) in public_keys.iter().zip(messages.iter()).zip(signatures.iter()) { let _result = public_key.verify(black_box(*message), signature); } }) }, } // ================================================================================================ // EDDSA 25519 BENCHMARKS // ================================================================================================ // === Key Generation Benchmarks === benchmark_with_setup! { eddsa_25519_sha512_keygen_secret_default, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "eddsa_25519_sha512_keygen_secret", || {}, |b: &mut criterion::Bencher| { b.iter(|| { let _secret_key = eddsa_25519_sha512::SecretKey::new(); }) }, } benchmark_with_setup_data! { eddsa_25519_sha512_keygen_secret_with_rng, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "eddsa_25519_sha512_keygen_secret_with_rng", || { rng() }, |b: &mut criterion::Bencher, rng: &rand::rngs::ThreadRng| { b.iter(|| { let mut rng_clone = rng.clone(); let _secret_key = eddsa_25519_sha512::SecretKey::with_rng(&mut rng_clone); }) }, } benchmark_with_setup_data! { eddsa_25519_sha512_keygen_public, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "eddsa_25519_sha512_keygen_public", || { let secret_keys: Vec<eddsa_25519_sha512::SecretKey> = (0..KEYGEN_ITERATIONS).map(|_| eddsa_25519_sha512::SecretKey::new()).collect(); secret_keys }, |b: &mut criterion::Bencher, secret_keys: &Vec<eddsa_25519_sha512::SecretKey>| { b.iter(|| { for secret_key in secret_keys { let _public_key = secret_key.public_key(); } }) }, } // === Signing Benchmarks === benchmark_with_setup_data! { eddsa_25519_sha512_sign, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "eddsa_25519_sha512_sign", || { let secret_keys: Vec<eddsa_25519_sha512::SecretKey> = (0..KEYGEN_ITERATIONS).map(|_| eddsa_25519_sha512::SecretKey::new()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); (secret_keys, messages) }, |b: &mut criterion::Bencher, (secret_keys, messages): &(Vec<eddsa_25519_sha512::SecretKey>, Vec<Word>)| { b.iter(|| { for (secret_key, message) in secret_keys.iter().zip(messages.iter()) { let _signature = secret_key.sign(black_box(*message)); } }) }, } // === Verification Benchmarks === benchmark_with_setup_data! { eddsa_25519_sha512_verify, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "eddsa_25519_sha512_verify", || { let mut rng = rand::rngs::ThreadRng::default(); let secret_keys: Vec<eddsa_25519_sha512::SecretKey> = (0..KEYGEN_ITERATIONS).map(|_| eddsa_25519_sha512::SecretKey::with_rng(&mut rng)).collect(); let public_keys: Vec<eddsa_25519_sha512::PublicKey> = secret_keys.iter().map(|sk| sk.public_key()).collect(); let messages: Vec<Word> = (0..KEYGEN_ITERATIONS).map(|i| Word::new([Felt::new(i as u64); 4])).collect(); let signatures: Vec<eddsa_25519_sha512::Signature> = secret_keys .iter() .zip(messages.iter()) .map(|(sk, msg)| sk.sign(black_box(*msg))) .collect(); (public_keys, messages, signatures) }, |b: &mut criterion::Bencher, (public_keys, messages, signatures): &(Vec<eddsa_25519_sha512::PublicKey>, Vec<Word>, Vec<eddsa_25519_sha512::Signature>)| { b.iter(|| { for ((public_key, message), signature) in public_keys.iter().zip(messages.iter()).zip(signatures.iter()) { let _result = public_key.verify(black_box(*message), signature); } }) }, } // ================================================================================================ // BENCHMARK GROUP CONFIGURATION // ================================================================================================ criterion_group!( dsa_benchmark_group, // ECDSA k256 benchmarks ecdsa_k256_keygen_secret_default, ecdsa_k256_keygen_secret_with_rng, ecdsa_k256_keygen_public, ecdsa_k256_sign, ecdsa_k256_verify, // EdDSA 25519 benchmarks eddsa_25519_sha512_keygen_secret_default, eddsa_25519_sha512_keygen_secret_with_rng, eddsa_25519_sha512_keygen_public, eddsa_25519_sha512_sign, eddsa_25519_sha512_verify, // RPO-Falcon512 benchmarks falcon512_rpo_keygen_secret_default, falcon512_rpo_keygen_secret_with_rng, falcon512_rpo_keygen_public, falcon512_rpo_sign_default, falcon512_rpo_sign_with_rng, falcon512_rpo_verify, ); criterion_main!(dsa_benchmark_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/smt.rs
miden-crypto/benches/smt.rs
//! Comprehensive Sparse Merkle Tree (SMT) operation benchmarks //! //! This module benchmarks all public APIs of the SMT implementations //! with a focus on tree creation, updates, proofs, and mutations. //! //! # Organization //! //! The benchmarks are organized by: //! 1. Full SMT benchmarks (Smt struct) //! 2. Simple SMT benchmarks (SimpleSmt const-generic) //! 3. SMT subtree construction benchmarks //! 4. Proof verification benchmarks //! 5. Mutation computation and application //! 6. Batch operations //! //! # Benchmarking Strategy //! //! - Tree creation benchmarks use `benchmark_with_setup_data!` for efficient setup //! - Multi-size benchmarks use `benchmark_multi!` for scalability testing //! - Batch operations use `benchmark_batch!` for performance analysis //! //! # Adding New SMT Benchmarks //! //! To add benchmarks for new SMT operations: //! 1. Add the operation to the appropriate benchmark group //! 2. Follow naming conventions: `smt_<struct>_<operation>_<parameter>` //! 3. Use the appropriate macro for benchmark type //! 4. Update input size arrays if needed use std::hint; use criterion::{Criterion, criterion_group, criterion_main}; use miden_crypto::{ Felt, ONE, Word, merkle::smt::{LeafIndex, SimpleSmt, Smt, SmtLeaf, SubtreeLeaf, build_subtree_for_bench}, }; mod common; use common::*; // === Test Data Generation === use crate::{ config::{DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE}, data::{ WordPattern, generate_simple_smt_entries_sequential as generate_simple_smt_entries, generate_smt_entries_mixed, generate_smt_entries_sequential as generate_smt_entries, generate_test_keys_sequential as generate_test_keys, generate_value, generate_word, generate_word_pattern, }, }; // === Full Smt Benchmarks === // Smt::new() tree creation benchmark_with_setup! { smt_new, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "new", || {}, |b: &mut criterion::Bencher| { b.iter(|| { // Prevent dead code elimination of tree creation hint::black_box(Smt::new()); }) }, } // Smt::with_entries() tree creation with initial data benchmark_with_setup_data! { smt_with_entries, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "with_entries", || { generate_smt_entries(256) }, |b: &mut criterion::Bencher, entries: &Vec<(Word, Word)>| { b.iter(|| { // Prevent dead code elimination of tree creation with entries hint::black_box(Smt::with_entries(entries.clone()).unwrap()); }) }, } // Smt root computation benchmark_with_setup_data! { smt_root, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "root", || { let entries: Vec<(Word, Word)> = generate_smt_entries(256); Smt::with_entries(entries).unwrap() }, |b: &mut criterion::Bencher, smt: &Smt| { b.iter(|| { hint::black_box(smt.root()); }) }, } // Smt get_value operations benchmark_with_setup_data! { smt_get_value, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "get_value", || { let entries = generate_smt_entries(256); let keys: Vec<Word> = generate_test_keys(100); let smt = Smt::with_entries(entries).unwrap(); (smt, keys) }, |b: &mut criterion::Bencher, (smt, keys): &(Smt, Vec<Word>)| { b.iter(|| { for key in keys { hint::black_box(smt.get_value(key)); } }) }, } // Smt insert operations with multiple input sizes benchmark_batch! { smt_insert, &[1, 16, 32, 64, 128], |b: &mut criterion::Bencher, insert_count: usize| { let entries = generate_smt_entries(256); let mut smt = Smt::with_entries(entries).unwrap(); let new_key = Word::new([Felt::new(999), Felt::new(1000), Felt::new(1001), Felt::new(1002)]); let new_value = Word::new([Felt::new(1003), Felt::new(1004), Felt::new(1005), Felt::new(1006)]); b.iter(|| { for _ in 0..insert_count { smt.insert(new_key, new_value).unwrap(); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) } // Smt open operations (proof generation) benchmark_with_setup_data! { smt_open, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "open", || { let entries = generate_smt_entries(256); let keys = generate_test_keys(10); let smt = Smt::with_entries(entries).unwrap(); (smt, keys) }, |b: &mut criterion::Bencher, (smt, keys): &(Smt, Vec<Word>)| { b.iter(|| { for key in keys { hint::black_box(smt.open(key)); } }) }, } // Smt num_leaves and num_entries accessors benchmark_with_setup_data! { smt_counters, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "counters", || { let entries = generate_smt_entries(512); Smt::with_entries(entries).unwrap() }, |b: &mut criterion::Bencher, smt: &Smt| { b.iter(|| { hint::black_box(smt.num_leaves()); hint::black_box(smt.num_entries()); }) }, } // Multi-size Smt tree creation benchmark_multi! { smt_creation_sizes, "creation-sizes", &[16, 64, 256, 1024, 4096, 65536, 1_048_576], |b: &mut criterion::Bencher, num_entries: &usize| { b.iter_batched( || { if *num_entries <= 4096 { generate_smt_entries(*num_entries) } else { // Use mixed pattern for larger datasets to be more realistic generate_smt_entries_mixed(*num_entries) } }, |entries| { Smt::with_entries(hint::black_box(entries)).unwrap() }, criterion::BatchSize::SmallInput, ) } } // === SimpleSmt Benchmarks === // SimpleSmt::new() tree creation benchmark_with_setup! { simple_smt_new, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "new", || {}, |b: &mut criterion::Bencher| { b.iter(|| { // Prevent dead code elimination of tree creation hint::black_box(SimpleSmt::<32>::new().unwrap()); }) }, } // SimpleSmt::with_leaves() tree creation with initial data benchmark_with_setup_data! { simple_smt_with_leaves, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "with_leaves", || { generate_simple_smt_entries(256) }, |b: &mut criterion::Bencher, entries: &Vec<(u64, Word)>| { b.iter(|| { // Prevent dead code elimination of tree creation with leaves hint::black_box(SimpleSmt::<32>::with_leaves(entries.clone()).unwrap()); }) }, } // SimpleSmt root computation benchmark_with_setup_data! { simple_smt_root, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "root", || { let entries = generate_simple_smt_entries(256); SimpleSmt::<32>::with_leaves(entries).unwrap() }, |b: &mut criterion::Bencher, smt: &SimpleSmt<32>| { b.iter(|| { hint::black_box(smt.root()); }) }, } // SimpleSmt get_leaf operations benchmark_with_setup_data! { simple_smt_get_leaf, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "get_leaf", || { let entries = generate_simple_smt_entries(256); let indices: Vec<LeafIndex<32>> = (0..100) .map(|i| LeafIndex::<32>::new(i).unwrap()) .collect(); let smt = SimpleSmt::<32>::with_leaves(entries).unwrap(); (smt, indices) }, |b: &mut criterion::Bencher, (smt, indices): &(SimpleSmt<32>, Vec<LeafIndex<32>>)| { b.iter(|| { for index in indices { hint::black_box(smt.get_leaf(index)); } }) }, } // SimpleSmt insert operations with multiple input sizes benchmark_batch! { simple_smt_insert, &[1, 16, 32, 64, 128], |b: &mut criterion::Bencher, insert_count: usize| { let entries = generate_simple_smt_entries(256); let mut smt = SimpleSmt::<32>::with_leaves(entries).unwrap(); let new_index = LeafIndex::<32>::new(999).unwrap(); let new_value = Word::new([Felt::new(1000), Felt::new(1001), Felt::new(1002), Felt::new(1003)]); b.iter(|| { for _ in 0..insert_count { smt.insert(new_index, new_value); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) } // SimpleSmt open operations benchmark_with_setup_data! { simple_smt_open, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "open", || { let entries = generate_simple_smt_entries(256); let indices: Vec<LeafIndex<32>> = (0..10) .map(|i| LeafIndex::<32>::new(i).unwrap()) .collect(); let smt = SimpleSmt::<32>::with_leaves(entries).unwrap(); (smt, indices) }, |b: &mut criterion::Bencher, (smt, indices): &(SimpleSmt<32>, Vec<LeafIndex<32>>)| { b.iter(|| { for index in indices { hint::black_box(smt.open(index)); } }) }, } // SimpleSmt leaves iteration benchmark_with_setup_data! { simple_smt_leaves, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "leaves", || { let entries = generate_simple_smt_entries(256); SimpleSmt::<32>::with_leaves(entries).unwrap() }, |b: &mut criterion::Bencher, smt: &SimpleSmt<32>| { b.iter(|| { // Prevent dead code elimination of leaves counting hint::black_box(smt.leaves().count()); }) }, } // === Mutation Benchmarks === // Smt compute_mutations benchmark_with_setup_data! { smt_compute_mutations, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "compute_mutations", || { let entries = generate_smt_entries(256); let smt = Smt::with_entries(entries).unwrap(); let new_entries = generate_smt_entries(32); (smt, new_entries) }, |b: &mut criterion::Bencher, (smt, new_entries): &(Smt, Vec<(Word, Word)>)| { b.iter(|| { hint::black_box(smt.compute_mutations(new_entries.clone()).unwrap()); }) }, } // Smt apply_mutations with multiple input sizes benchmark_batch! { smt_apply_mutations, &[1, 16, 32, 64, 128], |b: &mut criterion::Bencher, mutation_count: usize| { let base_entries = generate_smt_entries(256); let mut smt = Smt::with_entries(base_entries).unwrap(); b.iter(|| { for _ in 0..mutation_count { let new_entries = generate_smt_entries(32); let mutations = smt.compute_mutations(new_entries).unwrap(); smt.apply_mutations(mutations).unwrap(); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) } // === Batch Operations Benchmarks === // Batch Smt updates benchmark_batch! { smt_batch_updates, &[1, 16, 32, 64, 128], |b: &mut criterion::Bencher, update_count: usize| { let entries = generate_smt_entries(256); let mut smt = Smt::with_entries(entries).unwrap(); let update_pairs: Vec<(Word, Word)> = (0..update_count) .map(|i| { let key = generate_word_pattern((1000 + i) as u64, WordPattern::Sequential); let value = generate_word_pattern((1004 + i) as u64, WordPattern::Sequential); (key, value) }) .collect(); b.iter(|| { for (key, value) in &update_pairs { smt.insert(*key, *value).unwrap(); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) } // Batch SimpleSmt updates benchmark_batch! { simple_smt_batch_updates, &[1, 16, 32, 64, 128], |b: &mut criterion::Bencher, update_count: usize| { let entries = generate_simple_smt_entries(256); let mut smt = SimpleSmt::<32>::with_leaves(entries).unwrap(); let updates: Vec<(LeafIndex<32>, Word)> = (0..update_count) .map(|i| { let index = LeafIndex::<32>::new(1000u64 + i as u64).unwrap(); let value = Word::new([ Felt::new((1000 + i) as u64), Felt::new((1001 + i) as u64), Felt::new((1002 + i) as u64), Felt::new((1003 + i) as u64), ]); (index, value) }) .collect(); b.iter(|| { for (index, value) in &updates { smt.insert(*index, *value); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) } // === SMT Subtree Benchmarks === const PAIR_COUNTS: [u64; 5] = [1, 64, 128, 192, 256]; // SMT subtree construction with even distribution benchmark_multi! { smt_subtree_even, "subtree8-even", &PAIR_COUNTS, |b: &mut criterion::Bencher, &pair_count: &u64| { let mut seed = [0u8; 32]; b.iter_batched( || { let entries: Vec<(Word, Word)> = (0..pair_count) .map(|n| { // A single depth-8 subtree can have a maximum of 255 leaves. let leaf_index = ((n as f64 / pair_count as f64) * 255.0) as u64; let key = Word::new([ generate_value(&mut seed), ONE, Felt::new(n), Felt::new(leaf_index), ]); let value = generate_word(&mut seed); (key, value) }) .collect(); let mut leaves: Vec<_> = entries .iter() .map(|(key, value)| { let leaf = SmtLeaf::new_single(*key, *value); let col = leaf.index().value(); let hash = leaf.hash(); SubtreeLeaf { col, hash } }) .collect(); leaves.sort(); leaves.dedup_by_key(|leaf| leaf.col); leaves }, |leaves| { let (subtree, _) = build_subtree_for_bench( hint::black_box(leaves), hint::black_box(8), // SMT_DEPTH hint::black_box(8), // SMT_DEPTH ); assert!(!subtree.is_empty()); }, criterion::BatchSize::SmallInput, ); } } // SMT subtree construction with random distribution benchmark_multi! { smt_subtree_random, "subtree8-rand", &PAIR_COUNTS, |b: &mut criterion::Bencher, &pair_count: &u64| { let mut seed = [0u8; 32]; b.iter_batched( || { let entries: Vec<(Word, Word)> = (0..pair_count) .map(|i| { let leaf_index: u8 = generate_value(&mut seed); let key = Word::new([ONE, ONE, Felt::new(i), Felt::new(leaf_index as u64)]); let value = generate_word(&mut seed); (key, value) }) .collect(); let mut leaves: Vec<_> = entries .iter() .map(|(key, value)| { let leaf = SmtLeaf::new_single(*key, *value); let col = leaf.index().value(); let hash = leaf.hash(); SubtreeLeaf { col, hash } }) .collect(); leaves.sort(); leaves.dedup_by_key(|leaf| leaf.col); leaves }, |leaves| { let (subtree, _) = build_subtree_for_bench( hint::black_box(leaves), hint::black_box(8), // SMT_DEPTH hint::black_box(8), // SMT_DEPTH ); assert!(!subtree.is_empty()); }, criterion::BatchSize::SmallInput, ); } } // === Benchmark Group Configuration === criterion_group!( smt_benchmark_group, // Full Smt benchmarks smt_new, smt_with_entries, smt_root, smt_get_value, smt_insert, smt_open, smt_counters, smt_creation_sizes, // SimpleSmt benchmarks simple_smt_new, simple_smt_with_leaves, simple_smt_root, simple_smt_get_leaf, simple_smt_insert, simple_smt_open, simple_smt_leaves, // SMT subtree benchmarks smt_subtree_even, smt_subtree_random, // Mutation benchmarks smt_compute_mutations, smt_apply_mutations, // Batch operations smt_batch_updates, simple_smt_batch_updates, ); criterion_main!(smt_benchmark_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/partial_mt.rs
miden-crypto/benches/partial_mt.rs
//! PartialMerkleTree construction and operation benchmarks. use std::hint; use criterion::{BatchSize, Bencher, Criterion, criterion_group, criterion_main}; use miden_crypto::{ Word, merkle::{NodeIndex, PartialMerkleTree}, }; mod common; use common::data::{WordPattern, generate_word_pattern}; // === PartialMerkleTree Construction Benchmarks === benchmark_multi!( partial_merkle_tree_with_leaves, "partial_merkle_tree_with_leaves", &[64, 256, 1024, 4096, 8192], |b: &mut Bencher<'_>, &num_leaves: &usize| { b.iter_batched( || { // Generate entries at the same depth (no ancestor relationships) let depth = (num_leaves as f64).log2() as u8; let entries: Vec<(NodeIndex, Word)> = (0..num_leaves as u64) .map(|i| { let node = NodeIndex::new(depth, i).unwrap(); let word = generate_word_pattern(i, WordPattern::MerkleStandard); (node, word) }) .collect(); entries }, |entries| { let tree = PartialMerkleTree::with_leaves(hint::black_box(entries)).unwrap(); hint::black_box(tree); }, BatchSize::SmallInput, ); } ); // === Benchmark Group Definition === criterion_group!(partial_mt_benches, partial_merkle_tree_with_leaves,); criterion_main!(partial_mt_benches);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/merkle.rs
miden-crypto/benches/merkle.rs
//! MerkleTree construction and operation benchmarks. //! //! This module benchmarks the creation and operations of Merkle trees, //! including tree construction, path computation, updates, and verification. use std::hint; use criterion::{BatchSize, Bencher, Criterion, criterion_group, criterion_main}; use miden_crypto::{ Word, merkle::{MerklePath, MerkleTree, NodeIndex}, }; mod common; use common::{ config::{DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE}, data::{WordPattern, generate_words_merkle_std, generate_words_pattern}, }; // === MerkleTree Construction Benchmarks === benchmark_multi!( merkle_tree_construction, "merkle_tree_construction", &[4, 8, 16, 32, 64, 128, 256], |b: &mut Bencher<'_>, &num_leaves: &usize| { b.iter_batched( || generate_words_pattern(num_leaves, WordPattern::Random), |leaves| { let tree = MerkleTree::new(hint::black_box(leaves)).unwrap(); assert_eq!(tree.depth(), num_leaves.ilog2() as u8); }, BatchSize::SmallInput, ); } ); benchmark_multi!( balanced_merkle_even, "balanced-merkle-even", &[4, 8, 16, 32, 64, 128, 256], |b: &mut Bencher<'_>, num_leaves: &usize| { b.iter_batched( || { let entries = generate_words_merkle_std(*num_leaves); assert_eq!(entries.len(), *num_leaves); entries }, |leaves| { let tree = MerkleTree::new(hint::black_box(leaves)).unwrap(); assert_eq!(tree.depth(), num_leaves.ilog2() as u8); }, BatchSize::SmallInput, ); } ); // === MerkleTree Operation Benchmarks === benchmark_with_setup_data!( merkle_tree_root, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "merkle-tree-root", || { let entries = generate_words_merkle_std(256); MerkleTree::new(&entries).unwrap() }, |b: &mut criterion::Bencher<'_>, tree: &MerkleTree| { b.iter(|| { hint::black_box(tree.root()); }); } ); benchmark_with_setup_data!( merkle_tree_get_path, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "merkle-tree-get-path", || { // Setup let leaves = generate_words_merkle_std(256); let tree = MerkleTree::new(&leaves).unwrap(); let index = NodeIndex::new(8, 128).unwrap(); (tree, index) }, |b: &mut criterion::Bencher<'_>, (tree, index): &(MerkleTree, NodeIndex)| { b.iter(|| { let _path = hint::black_box(tree.get_path(*index)).unwrap(); }) }, ); benchmark_batch!( merkle_tree_batch_update, &[1, 16, 32, 64, 128], |b: &mut Bencher<'_>, update_count: usize| { let mut tree = MerkleTree::new(generate_words_merkle_std(256)).unwrap(); let new_leaves: Vec<Word> = generate_words_pattern(update_count, WordPattern::Random); b.iter(|| { for (i, new_leaf) in new_leaves.iter().enumerate() { hint::black_box(tree.update_leaf(i as u64, *new_leaf)).unwrap(); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) ); benchmark_with_setup_data!( merkle_tree_leaves, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "merkle-tree-leaves", || { let entries = generate_words_merkle_std(256); MerkleTree::new(&entries).unwrap() }, |b: &mut criterion::Bencher<'_>, tree: &MerkleTree| { b.iter(|| { hint::black_box(tree.leaves().collect::<Vec<_>>()); }); } ); benchmark_with_setup_data!( merkle_tree_inner_nodes, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "merkle-tree-inner-nodes", || { let entries = generate_words_merkle_std(256); MerkleTree::new(&entries).unwrap() }, |b: &mut criterion::Bencher<'_>, tree: &MerkleTree| { b.iter(|| { hint::black_box(tree.inner_nodes().collect::<Vec<_>>()); }); } ); // === MerklePath Verification Benchmark === benchmark_with_setup_data!( merkle_path_verify, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "merkle_path_verify", || { // Setup let leaves = generate_words_merkle_std(256); let tree = MerkleTree::new(&leaves).unwrap(); let leaf_index = 128; let node_index = NodeIndex::new(8, leaf_index).unwrap(); let path = tree.get_path(node_index).unwrap(); let leaf = leaves[leaf_index as usize]; let root = tree.root(); (path, leaf_index, leaf, root) }, |b: &mut criterion::Bencher<'_>, (path, index, leaf, root): &(MerklePath, u64, Word, Word)| { b.iter(|| { let _ = path.verify(*index, hint::black_box(*leaf), hint::black_box(root)); }) }, ); // === Benchmark Group Definition === criterion_group!( merkle_benches, merkle_tree_construction, balanced_merkle_even, merkle_tree_root, merkle_tree_get_path, merkle_tree_batch_update, merkle_tree_leaves, merkle_tree_inner_nodes, merkle_path_verify, ); criterion_main!(merkle_benches);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/rand.rs
miden-crypto/benches/rand.rs
//! Comprehensive random number generation benchmarks //! //! This module benchmarks all random number generation operations implemented in the library //! with a focus on RPO and RPX-based random coins. //! //! # Organization //! //! The benchmarks are organized by: //! 1. Random coin initialization using benchmark_rand_new! //! 2. Element drawing operations using benchmark_rand_draw! //! 3. Word drawing operations using benchmark_rand_draw! //! 4. Reseeding operations using benchmark_rand_reseed! //! 5. Integer drawing operations using benchmark_rand_draw_integers! //! 6. Leading zero checking using benchmark_rand_check_leading_zeros! //! 7. Byte filling operations using benchmark_rand_fill_bytes! //! //! # Adding New Random Benchmarks //! //! To add benchmarks for new random number generators: //! 1. Add the algorithm to the imports //! 2. Use benchmark_rand_comprehensive! for complete coverage //! 3. Add to the appropriate benchmark group //! 4. Update input size arrays in config.rs if needed use std::hint::black_box; use criterion::{Criterion, criterion_group, criterion_main}; // Import random generation modules use miden_crypto::{ Felt, Word, rand::{FeltRng, RpoRandomCoin, RpxRandomCoin}, }; // Import common utilities mod common; use common::*; // Import configuration constants use crate::config::PRNG_OUTPUT_SIZES; /// Configuration for random coin testing const TEST_SEED: Word = Word::new([Felt::new(1), Felt::new(2), Felt::new(3), Felt::new(4)]); // === RPO Random Coin Benchmarks === // Use individual macros for better control benchmark_rand_new!(rand_rpo_new, RpoRandomCoin, TEST_SEED); benchmark_rand_draw!( rand_rpo_draw_elements, RpoRandomCoin, TEST_SEED, "draw_element", PRNG_OUTPUT_SIZES, |coin: &mut RpoRandomCoin, count| { for _ in 0..count { let _element = coin.draw_element(); } } ); benchmark_rand_draw!( rand_rpo_draw_words, RpoRandomCoin, TEST_SEED, "draw_word", PRNG_OUTPUT_SIZES, |coin: &mut RpoRandomCoin, count| { for _ in 0..count { let _word = coin.draw_word(); } } ); benchmark_rand_reseed!(rand_rpo_reseed, RpoRandomCoin, TEST_SEED); benchmark_rand_draw_integers!(rand_rpo_draw_integers, RpoRandomCoin, TEST_SEED); benchmark_rand_check_leading_zeros!(rand_rpo_check_leading_zeros, RpoRandomCoin, TEST_SEED); benchmark_rand_fill_bytes!( rand_rpo_fill_bytes, RpoRandomCoin, TEST_SEED, &[1, 32, 64, 128, 256, 512, 1024] ); // === RPX Random Coin Benchmarks === // Use individual macros for better control benchmark_rand_new!(rand_rpx_new, RpxRandomCoin, TEST_SEED); benchmark_rand_draw!( rand_rpx_draw_elements, RpxRandomCoin, TEST_SEED, "draw_element", PRNG_OUTPUT_SIZES, |coin: &mut RpxRandomCoin, count| { for _ in 0..count { let _element = coin.draw_element(); } } ); benchmark_rand_draw!( rand_rpx_draw_words, RpxRandomCoin, TEST_SEED, "draw_word", PRNG_OUTPUT_SIZES, |coin: &mut RpxRandomCoin, count| { for _ in 0..count { let _word = coin.draw_word(); } } ); benchmark_rand_reseed!(rand_rpx_reseed, RpxRandomCoin, TEST_SEED); benchmark_rand_draw_integers!(rand_rpx_draw_integers, RpxRandomCoin, TEST_SEED); benchmark_rand_check_leading_zeros!(rand_rpx_check_leading_zeros, RpxRandomCoin, TEST_SEED); benchmark_rand_fill_bytes!( rand_rpx_fill_bytes, RpxRandomCoin, TEST_SEED, &[1, 32, 64, 128, 256, 512, 1024] ); // === Benchmark Group Configuration === criterion_group!( rand_benchmark_group, // RPO Random Coin benchmarks rand_rpo_new, rand_rpo_draw_elements, rand_rpo_draw_words, rand_rpo_reseed, rand_rpo_draw_integers, rand_rpo_check_leading_zeros, rand_rpo_fill_bytes, // RPX Random Coin benchmarks rand_rpx_new, rand_rpx_draw_elements, rand_rpx_draw_words, rand_rpx_reseed, rand_rpx_draw_integers, rand_rpx_check_leading_zeros, rand_rpx_fill_bytes, ); criterion_main!(rand_benchmark_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/hash.rs
miden-crypto/benches/hash.rs
//! Simplified hash function benchmarks //! //! This module focuses on the two key operations across all hash functions: //! 1. merge() - 2-to-1 hash merge (single permutation) //! 2. hash_elements() - Sequential hashing of field elements (especially 100 elements) //! //! # Organization //! //! The benchmarks are organized by hash algorithm: //! - RPO256 //! - RPX256 //! - Poseidon2 //! - Blake3 variants (256, 192, 160) //! - Keccak256 //! //! Each algorithm has two benchmarks: //! - `hash_<algo>_merge` - 2-to-1 merge operation //! - `hash_<algo>_sequential_felt` - Sequential hashing of field elements use std::hint::black_box; use criterion::{Criterion, criterion_group, criterion_main}; use miden_crypto::hash::{ HasherExt, blake::{Blake3_192, Blake3_256}, keccak::Keccak256, poseidon2::Poseidon2, rpo::Rpo256, rpx::Rpx256, }; // Import common utilities mod common; use common::data::{generate_byte_array_random, generate_felt_array_sequential}; // Import config constants use crate::common::config::HASH_ELEMENT_COUNTS; // === RPO256 Hash Benchmarks === // 2-to-1 hash merge benchmark_hash_merge!(hash_rpo256_merge, "rpo256", |b: &mut criterion::Bencher| { let input1 = Rpo256::hash(&generate_byte_array_random(32)); let input2 = Rpo256::hash(&generate_byte_array_random(32)); b.iter(|| Rpo256::merge(black_box(&[input1, input2]))) }); // Sequential hashing of Felt elements benchmark_hash_felt!( hash_rpo256_sequential_felt, "rpo256", HASH_ELEMENT_COUNTS, |b: &mut criterion::Bencher, count| { let elements = generate_felt_array_sequential(count); b.iter(|| Rpo256::hash_elements(black_box(&elements))) }, |count| Some(criterion::Throughput::Elements(count as u64)) ); // === RPX256 Hash Benchmarks === // 2-to-1 hash merge benchmark_hash_merge!(hash_rpx256_merge, "rpx256", |b: &mut criterion::Bencher| { let input1 = Rpx256::hash(&generate_byte_array_random(32)); let input2 = Rpx256::hash(&generate_byte_array_random(32)); b.iter(|| Rpx256::merge(black_box(&[input1, input2]))) }); // Sequential hashing of Felt elements benchmark_hash_felt!( hash_rpx256_sequential_felt, "rpx256", HASH_ELEMENT_COUNTS, |b: &mut criterion::Bencher, count| { let elements = generate_felt_array_sequential(count); b.iter(|| Rpx256::hash_elements(black_box(&elements))) }, |count| Some(criterion::Throughput::Elements(count as u64)) ); // === Poseidon2 Hash Benchmarks === // 2-to-1 hash merge benchmark_hash_merge!(hash_poseidon2_merge, "poseidon2", |b: &mut criterion::Bencher| { let input1 = Poseidon2::hash(&generate_byte_array_random(32)); let input2 = Poseidon2::hash(&generate_byte_array_random(32)); b.iter(|| Poseidon2::merge(black_box(&[input1, input2]))) }); // Sequential hashing of Felt elements benchmark_hash_felt!( hash_poseidon2_sequential_felt, "poseidon2", HASH_ELEMENT_COUNTS, |b: &mut criterion::Bencher, count| { let elements = generate_felt_array_sequential(count); b.iter(|| Poseidon2::hash_elements(black_box(&elements))) }, |count| Some(criterion::Throughput::Elements(count as u64)) ); // === Blake3 Hash Benchmarks === // 2-to-1 hash merge benchmark_hash_merge!(hash_blake3_merge, "blake3_256", |b: &mut criterion::Bencher| { let input1 = Blake3_256::hash(&generate_byte_array_random(32)); let input2 = Blake3_256::hash(&generate_byte_array_random(32)); let digest_inputs: [<Blake3_256 as HasherExt>::Digest; 2] = [input1, input2]; b.iter(|| Blake3_256::merge(black_box(&digest_inputs))) }); // Sequential hashing of Felt elements benchmark_hash_felt!( hash_blake3_sequential_felt, "blake3_256", HASH_ELEMENT_COUNTS, |b: &mut criterion::Bencher, count| { let elements = generate_felt_array_sequential(count); b.iter(|| Blake3_256::hash_elements(black_box(&elements))) }, |count| Some(criterion::Throughput::Elements(count as u64)) ); // === Blake3_192 Hash Benchmarks === // 2-to-1 hash merge benchmark_hash_merge!(hash_blake3_192_merge, "blake3_192", |b: &mut criterion::Bencher| { let input1 = Blake3_192::hash(&generate_byte_array_random(32)); let input2 = Blake3_192::hash(&generate_byte_array_random(32)); let digest_inputs: [<Blake3_192 as HasherExt>::Digest; 2] = [input1, input2]; b.iter(|| Blake3_192::merge(black_box(&digest_inputs))) }); // Sequential hashing of Felt elements benchmark_hash_felt!( hash_blake3_192_sequential_felt, "blake3_192", HASH_ELEMENT_COUNTS, |b: &mut criterion::Bencher, count| { let elements = generate_felt_array_sequential(count); b.iter(|| Blake3_192::hash_elements(black_box(&elements))) }, |count| Some(criterion::Throughput::Elements(count as u64)) ); // === Keccak256 benches === // 2-to-1 hash merge benchmark_hash_merge!(hash_keccak_256_merge, "keccak_256", |b: &mut criterion::Bencher| { let input1 = Keccak256::hash(&generate_byte_array_random(32)); let input2 = Keccak256::hash(&generate_byte_array_random(32)); let digest_inputs: [<Keccak256 as HasherExt>::Digest; 2] = [input1, input2]; b.iter(|| Keccak256::merge(black_box(&digest_inputs))) }); // Sequential hashing of Felt elements benchmark_hash_felt!( hash_keccak_256_sequential_felt, "keccak_256", HASH_ELEMENT_COUNTS, |b: &mut criterion::Bencher, count| { let elements = generate_felt_array_sequential(count); b.iter(|| Keccak256::hash_elements(black_box(&elements))) }, |count| Some(criterion::Throughput::Elements(count as u64)) ); criterion_group!( hash_benchmark_group, // RPO256 benchmarks hash_rpo256_merge, hash_rpo256_sequential_felt, // RPX256 benchmarks hash_rpx256_merge, hash_rpx256_sequential_felt, // Poseidon2 benchmarks hash_poseidon2_merge, hash_poseidon2_sequential_felt, // Blake3 benchmarks hash_blake3_merge, hash_blake3_sequential_felt, // Blake3_192 benchmarks hash_blake3_192_merge, hash_blake3_192_sequential_felt, // Keccak256 benchmarks hash_keccak_256_merge, hash_keccak_256_sequential_felt, ); criterion_main!(hash_benchmark_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/large-smt.rs
miden-crypto/benches/large-smt.rs
use std::hint; use criterion::{Criterion, criterion_group, criterion_main}; use miden_crypto::{ Word, merkle::smt::{LargeSmt, RocksDbConfig, RocksDbStorage}, }; mod common; use common::*; use crate::{ common::data::{generate_smt_entries_sequential, generate_test_keys_sequential}, config::{DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE}, }; benchmark_with_setup_data! { large_smt_open, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "open", || { let entries = generate_smt_entries_sequential(256); let keys = generate_test_keys_sequential(10); let temp_dir = tempfile::TempDir::new().unwrap(); let storage = RocksDbStorage::open(RocksDbConfig::new(temp_dir.path())).unwrap(); let smt = LargeSmt::with_entries(storage, entries).unwrap(); (smt, keys, temp_dir) }, |b: &mut criterion::Bencher, (smt, keys, _temp_dir): &(LargeSmt<RocksDbStorage>, Vec<Word>, tempfile::TempDir)| { b.iter(|| { for key in keys { hint::black_box(smt.open(key)); } }) }, } benchmark_with_setup_data! { large_smt_compute_mutations, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "compute_mutations", || { let entries = generate_smt_entries_sequential(256); let temp_dir = tempfile::TempDir::new().unwrap(); let storage = RocksDbStorage::open(RocksDbConfig::new(temp_dir.path())).unwrap(); let smt = LargeSmt::with_entries(storage, entries).unwrap(); let new_entries = generate_smt_entries_sequential(10_000); (smt, new_entries, temp_dir) }, |b: &mut criterion::Bencher, (smt, new_entries, _temp_dir): &(LargeSmt<RocksDbStorage>, Vec<(Word, Word)>, tempfile::TempDir)| { b.iter(|| { hint::black_box(smt.compute_mutations(new_entries.clone()).unwrap()); }) }, } // Benchmarks apply_mutations at different batch sizes. // Setup: Creates fresh tree and computes mutations // Measured: Only the apply_mutations call // Tests: Performance scaling with mutation size (100, 1k, 10k entries) on a tree with 256 entries benchmark_batch! { large_smt_apply_mutations, &[100, 1_000, 10_000], |b: &mut criterion::Bencher, entry_count: usize| { use criterion::BatchSize; let base_entries = generate_smt_entries_sequential(256); let bench_dir = std::env::temp_dir().join("bench_apply_mutations"); b.iter_batched( || { std::fs::create_dir_all(&bench_dir).unwrap(); let storage = RocksDbStorage::open(RocksDbConfig::new(&bench_dir)).unwrap(); let smt = LargeSmt::with_entries(storage, base_entries.clone()).unwrap(); let new_entries = generate_smt_entries_sequential(entry_count); let mutations = smt.compute_mutations(new_entries).unwrap(); (smt, mutations, bench_dir.clone()) }, |(mut smt, mutations, bench_dir)| { smt.apply_mutations(mutations).unwrap(); drop(smt); let _ = std::fs::remove_dir_all(&bench_dir); }, BatchSize::LargeInput, ) }, |size| Some(criterion::Throughput::Elements(size as u64)) } // Benchmarks apply_mutations_with_reversion at different batch sizes. // Setup: Creates fresh tree and computes mutations // Measured: Only the apply_mutations_with_reversion call // Tests: Performance scaling with mutation size (100, 1k, 10k entries) on a tree with 256 entries benchmark_batch! { large_smt_apply_mutations_with_reversion, &[100, 1_000, 10_000], |b: &mut criterion::Bencher, entry_count: usize| { use criterion::BatchSize; let base_entries = generate_smt_entries_sequential(256); let bench_dir = std::env::temp_dir().join("bench_apply_mutations_with_reversion"); b.iter_batched( || { std::fs::create_dir_all(&bench_dir).unwrap(); let storage = RocksDbStorage::open(RocksDbConfig::new(&bench_dir)).unwrap(); let smt = LargeSmt::with_entries(storage, base_entries.clone()).unwrap(); let new_entries = generate_smt_entries_sequential(entry_count); let mutations = smt.compute_mutations(new_entries).unwrap(); (smt, mutations, bench_dir.clone()) }, |(mut smt, mutations, bench_dir)| { let _ = smt.apply_mutations_with_reversion(mutations).unwrap(); drop(smt); let _ = std::fs::remove_dir_all(&bench_dir); }, BatchSize::LargeInput, ) }, |size| Some(criterion::Throughput::Elements(size as u64)) } benchmark_batch! { large_smt_insert_batch, &[1, 16, 32, 64, 128], |b: &mut criterion::Bencher, insert_count: usize| { let base_entries = generate_smt_entries_sequential(256); let temp_dir = tempfile::TempDir::new().unwrap(); let storage = RocksDbStorage::open(RocksDbConfig::new(temp_dir.path())).unwrap(); let mut smt = LargeSmt::with_entries(storage, base_entries).unwrap(); b.iter(|| { for _ in 0..insert_count { let new_entries = generate_smt_entries_sequential(10_000); smt.insert_batch(new_entries).unwrap(); } }) }, |size| Some(criterion::Throughput::Elements(size as u64)) } criterion_group!( large_smt_benchmark_group, large_smt_open, large_smt_compute_mutations, large_smt_apply_mutations, large_smt_apply_mutations_with_reversion, large_smt_insert_batch, ); criterion_main!(large_smt_benchmark_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/word.rs
miden-crypto/benches/word.rs
//! Comprehensive Word operation benchmarks //! //! This module benchmarks all Word operations implemented in the library //! with a focus on type conversions, serialization, and lexicographic ordering. //! //! # Organization //! //! The benchmarks are organized by: //! 1. Word creation and basic operations //! 2. Type conversions (bool, u8, u16, u32, u64) //! 3. Serialization and deserialization //! 4. Lexicographic ordering //! 5. Batch operations //! //! # Adding New Word Benchmarks //! //! To add benchmarks for new Word operations: //! 1. Add the operation to the imports //! 2. Add parameterized benchmark functions following the naming convention //! 3. Add to the appropriate benchmark group //! 4. Update input size arrays in config.rs if needed use criterion::{Criterion, criterion_group, criterion_main}; // Import Word modules use miden_crypto::{Felt, Word, word::LexicographicWord}; // Import common utilities mod common; use common::*; // Import configuration constants use crate::config::{DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, FIELD_BATCH_SIZES}; /// Configuration for Word testing const TEST_WORDS: [Word; 10] = [ Word::new([Felt::new(0), Felt::new(0), Felt::new(0), Felt::new(0)]), Word::new([Felt::new(1), Felt::new(0), Felt::new(0), Felt::new(0)]), Word::new([Felt::new(0), Felt::new(1), Felt::new(0), Felt::new(0)]), Word::new([Felt::new(0), Felt::new(0), Felt::new(1), Felt::new(0)]), Word::new([Felt::new(0), Felt::new(0), Felt::new(0), Felt::new(1)]), Word::new([Felt::new(1), Felt::new(1), Felt::new(1), Felt::new(1)]), Word::new([Felt::new(u64::MAX), Felt::new(0), Felt::new(0), Felt::new(0)]), Word::new([Felt::new(0), Felt::new(u64::MAX), Felt::new(0), Felt::new(0)]), Word::new([Felt::new(0), Felt::new(0), Felt::new(u64::MAX), Felt::new(0)]), Word::new([Felt::new(0), Felt::new(0), Felt::new(0), Felt::new(u64::MAX)]), ]; // === Word Creation and Basic Operations === // Word creation from field elements benchmark_with_setup_data! { word_new, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "new_from_elements", || { let test_elements: Vec<[Felt; 4]> = (0u64..100) .map(|i| { [ Felt::new(i), Felt::new(i + 1), Felt::new(i + 2), Felt::new(i + 3), ] }) .collect(); test_elements }, |b: &mut criterion::Bencher, test_elements: &Vec<[Felt; 4]>| { b.iter(|| { for elements in test_elements { let _word = Word::new(*elements); } }) }, } // Accessing word elements benchmark_with_setup! { word_access_elements, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "as_elements", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _elements = word.as_elements(); } }) }, } // Accessing word as bytes benchmark_with_setup! { word_access_bytes, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "as_bytes", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _bytes = word.as_bytes(); } }) }, } // === Type Conversion Benchmarks === // Basic type conversions (bool, u8, u16, u32, u64) benchmark_word_conversions!( word_convert_basic, &[0u8, 1u8, 2u8, 3u8, 4u8], // Type indices: 0=bool, 1=u8, 2=u16, 3=u32, 4=u64 &TEST_WORDS ); // Conversion to u64 array using Into trait benchmark_with_setup! { word_convert_u64, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "from_to_u64", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _result: [u64; 4] = (*word).into(); } }) }, } // Conversion to Felt array benchmark_with_setup! { word_convert_felt, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "from_to_felt", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _result: [Felt; 4] = (*word).into(); } }) }, } // Conversion to byte array benchmark_with_setup! { word_convert_bytes, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "from_to_bytes", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _result: [u8; 32] = (*word).into(); } }) }, } // === Serialization Benchmarks === // Hex serialization benchmark_with_setup! { word_to_hex, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "to_hex", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _hex = word.to_hex(); } }) }, } // Vector conversion benchmark_with_setup! { word_to_vec, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "to_vec", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _vec = word.to_vec(); } }) }, } // === Lexicographic Ordering Benchmarks === // Lexicographic word creation benchmark_with_setup! { word_lexicographic_new, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "new", || {}, |b: &mut criterion::Bencher| { b.iter(|| { for word in &TEST_WORDS { let _lex_word = LexicographicWord::new(*word); } }) }, } // Lexicographic word access benchmark_with_setup_data! { word_lexicographic_access, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "inner_access", || { let lex_words: Vec<LexicographicWord> = TEST_WORDS.iter().map(|w| LexicographicWord::new(*w)).collect(); lex_words }, |b: &mut criterion::Bencher, lex_words: &Vec<LexicographicWord>| { b.iter(|| { for lex_word in lex_words { let _inner = lex_word.inner(); } }) }, } // Lexicographic ordering comparisons benchmark_with_setup_data! { word_lexicographic_ordering, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "partial_cmp", || { let lex_words: Vec<LexicographicWord> = TEST_WORDS.iter().map(|w| LexicographicWord::new(*w)).collect(); lex_words }, |b: &mut criterion::Bencher, lex_words: &Vec<LexicographicWord>| { b.iter(|| { for i in 0..lex_words.len() { for j in i..lex_words.len() { let _result = lex_words[i].partial_cmp(&lex_words[j]); } } }) }, } // Lexicographic equality comparison benchmark_with_setup_data! { word_lexicographic_eq, DEFAULT_MEASUREMENT_TIME, DEFAULT_SAMPLE_SIZE, "eq", || { let lex_words: Vec<LexicographicWord> = TEST_WORDS.iter().map(|w| LexicographicWord::new(*w)).collect(); lex_words }, |b: &mut criterion::Bencher, lex_words: &Vec<LexicographicWord>| { b.iter(|| { for i in 0..lex_words.len() { for j in 0..lex_words.len() { let _result = lex_words[i] == lex_words[j]; } } }) }, } // === Batch Operations Benchmarks === // Batch processing of words as elements benchmark_batch! { word_batch_elements, FIELD_BATCH_SIZES, |b: &mut criterion::Bencher, count: usize| { let words: Vec<Word> = (0..count) .map(|i| { Word::new([ Felt::new(i as u64), Felt::new((i + 1) as u64), Felt::new((i + 2) as u64), Felt::new((i + 3) as u64), ]) }) .collect(); b.iter(|| { let _elements = Word::words_as_elements(&words); }) }, |count| Some(criterion::Throughput::Elements(count as u64)) } // === Benchmark Group Configuration === criterion_group!( word_benchmark_group, // Word creation and basic operations word_new, word_access_elements, word_access_bytes, // Type conversion benchmarks (consolidated) word_convert_basic, word_convert_u64, word_convert_felt, word_convert_bytes, // Serialization benchmarks word_to_hex, word_to_vec, // Lexicographic ordering benchmarks word_lexicographic_new, word_lexicographic_access, word_lexicographic_ordering, word_lexicographic_eq, // Batch operations benchmarks word_batch_elements, ); criterion_main!(word_benchmark_group);
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/common/config.rs
miden-crypto/benches/common/config.rs
//! Benchmark configuration constants and settings //! //! This module contains all configuration constants used across benchmark modules //! to ensure consistency and make it easy to adjust benchmark parameters. use std::time::Duration; // === Core Configuration === /// Default measurement time for most benchmarks pub const DEFAULT_MEASUREMENT_TIME: Duration = Duration::from_secs(20); /// Sample size for statistical significance pub const DEFAULT_SAMPLE_SIZE: usize = 100; // === Hash Function Configuration === /// Input sizes for hash function testing (in bytes) pub const HASH_INPUT_SIZES: &[usize] = &[ 1, // Single byte 2, // Very small input 4, // Tiny input 8, // Small input 16, // Small buffer 32, // Word size 64, // Double word 128, // 128 bytes 256, // 1KB / 32 Felt elements 512, // 512 bytes 1024, // 1KB 2048, // 2KB 4096, // 4KB 8192, // 8KB 16384, // 16KB ]; /// Element counts for sequential hashing tests /// Focused on the key benchmark size (100 elements) with a few representative sizes pub const HASH_ELEMENT_COUNTS: &[usize] = &[ 1, // Single element (minimal case) 100, // Primary benchmark target - typical use case 1000, // Larger scale test ]; /// Input sizes for merge operations (in bytes) pub const MERGE_INPUT_SIZES: &[usize] = &[ 1, // Single byte inputs 2, // Tiny inputs 4, // Small inputs 8, // Very small inputs 16, // Small inputs 32, // Word size 64, // Double word 128, // 128 bytes 256, // 1KB 512, // 512 bytes ]; /// Integer sizes for merge_with_int tests pub const MERGE_INT_SIZES: &[usize] = &[ 1, // Single byte integer 2, // 16-bit integer 4, // 32-bit integer 8, // 64-bit integer ]; // === Field Operations Configuration === /// Field element counts for batch operations pub const FIELD_BATCH_SIZES: &[usize] = &[ 1, // Single operation 10, // Small batch 100, // Medium batch 1000, // Large batch ]; // === Randomness Configuration === /// Output sizes for PRNG testing (in elements) pub const PRNG_OUTPUT_SIZES: &[usize] = &[ 1, // Single element 32, // Word size 100, // Small array 1000, // Medium array ]; // === Encryption Configuration === // Plaintext sizes in bytes pub const DATA_SIZES: &[usize] = &[16, 64, 256, 1024, 4096, 16384, 65536, 262144]; // Plaintext sizes in field elements pub const FELT_SIZES: &[usize] = &[ 4, // 32 bytes equivalent 16, // 128 bytes equivalent 64, // 512 bytes equivalent 256, // 2KB equivalent 1024, // 8KB equivalent 4096, // 32KB equivalent 16384, // 128KB equivalent ];
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/common/macros.rs
miden-crypto/benches/common/macros.rs
// Benchmark macros to reduce boilerplate code // // This module provides procedural macros to eliminate repetitive // patterns commonly found in benchmark code. // Creates a unified hash benchmark macro that eliminates duplication // // This is the core macro that all other hash macros build upon. // It supports custom throughput calculation and provides maximum flexibility. // // # Usage // ```no_run // benchmark_hash_core!( // hash_rpo256_elements, // "rpo256", // "elements", // HASH_ELEMENT_COUNTS, // |b, count| { // let elements = generate_felt_array_sequential(count); // b.iter(|| Rpo256::hash_elements(black_box(&elements))) // }, // |count| Some(criterion::Throughput::Elements(count as u64)) // ); // ``` #[macro_export] macro_rules! benchmark_hash_core { ( $func_name:ident, $hasher_name:literal, $operation:literal, $sizes:expr, $closure:expr, $throughput:expr ) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("hash-", $hasher_name, "-", $operation)); group.sample_size(10); for size_ref in $sizes { let size_val = *size_ref; group.bench_with_input( criterion::BenchmarkId::new($operation, size_val), &size_val, |b: &mut criterion::Bencher, &size_param: &usize| $closure(b, size_param), ); if size_val > 0 { let throughput_result = $throughput(size_val); if let Some(ref t) = throughput_result { group.throughput(t.clone()); } } } group.finish(); } }; } // Creates a benchmark for hash algorithms with common patterns (simplified interface) // // # Usage // ```no_run // benchmark_hash_simple!(hash_rpo256_single, "rpo256", "single", HASH_INPUT_SIZES, |b, size| { // let data = if size <= 64 { // generate_byte_array_sequential(size) // } else { // generate_byte_array_random(size) // }; // b.iter(|| Rpo256::hash(black_box(&data))) // }); // ``` #[macro_export] macro_rules! benchmark_hash_simple { ($func_name:ident, $hasher_name:literal, $operation:literal, $sizes:expr, $closure:expr) => { $crate::benchmark_hash_core! { $func_name, $hasher_name, $operation, $sizes, $closure, |size| Some(criterion::Throughput::Bytes(size as u64)) } }; } // Creates a benchmark for hash algorithms with backward compatibility // This macro maintains the original interface for existing code // // # Usage // ```no_run // benchmark_hash!(hash_rpo256_bytes, "rpo256", "bytes", HASH_INPUT_SIZES, |b, size| { // let data = generate_byte_array_sequential(size); // b.iter(|| Rpo256::hash(black_box(&data))) // }); // ``` #[macro_export] macro_rules! benchmark_hash { ( $func_name:ident, $hasher_name:literal, $operation:literal, $sizes:expr, $closure:expr, $size_var:ident, $throughput:expr ) => { $crate::benchmark_hash_core! { $func_name, $hasher_name, $operation, $sizes, $closure, $throughput } }; ($func_name:ident, $hasher_name:literal, $operation:literal, $sizes:expr, $closure:expr) => { $crate::benchmark_hash_core! { $func_name, $hasher_name, $operation, $sizes, $closure, |size| Some(criterion::Throughput::Bytes(size as u64)) } }; } // Creates a benchmark with automatic data generation for hash operations // // # Usage // ```rust // benchmark_hash_auto!(hash_rpo256_single, "rpo256", HASH_INPUT_SIZES, |b, data| { // b.iter(|| Rpo256::hash(black_box(data))) // }); // ``` #[macro_export] macro_rules! benchmark_hash_auto { ($func_name:ident, $hasher_name:literal, $sizes:expr, $closure:expr) => { $crate::benchmark_hash_simple!($func_name, $hasher_name, "single", $sizes, |b, size| { let data = if size <= 64 { $crate::common::data::generate_byte_array_sequential(size) } else { $crate::common::data::generate_byte_array_random(size) }; $closure(b, &data) }) }; } // Creates a benchmark for hash merge operations // // # Usage // ```no_run // benchmark_hash_merge!(hash_rpo_merge, "rpo256", &[1, 2, 4, 8, 16], |b, size| { // // merge logic here // }); // ``` #[macro_export] macro_rules! benchmark_hash_merge { // Simple variant without size parameterization - just benchmarks merge operation ($func_name:ident, $hasher_name:literal, $closure:expr) => { fn $func_name(c: &mut Criterion) { c.bench_function(concat!("hash-", $hasher_name, "-merge"), |b| $closure(b)); } }; // Parameterized variant with multiple sizes (legacy) ($func_name:ident, $hasher_name:literal, $sizes:expr, $closure:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("hash-", $hasher_name, "-merge")); group.sample_size(10); for size_ref in $sizes { let size = *size_ref; group.bench_with_input( criterion::BenchmarkId::new("merge", size), &size, |b: &mut criterion::Bencher, &size_param: &usize| $closure(b, size_param), ); } group.finish(); } }; } // Creates a benchmark for hash felt operations with automatic throughput // // # Usage // ```no_run // benchmark_hash_felt!( // hash_rpo_elements, // "rpo256", // &[1, 2, 4, 8, 16, 32, 64, 128], // |b, count| { // let elements = generate_felt_array_sequential(count); // b.iter(|| Rpo256::hash_elements(black_box(&elements))) // }, // |count| Some(criterion::Throughput::Elements(count as u64)) // ); // ``` #[macro_export] macro_rules! benchmark_hash_felt { ($func_name:ident, $hasher_name:literal, $counts:expr, $closure:expr, $throughput:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("hash-", $hasher_name, "-felt")); group.sample_size(10); for count_ref in $counts { let count = *count_ref; group.bench_with_input( criterion::BenchmarkId::new("hash_elements", count), &count, |b: &mut criterion::Bencher, &count_param: &usize| $closure(b, count_param), ); let throughput_result = $throughput(count); if let Some(ref t) = throughput_result { group.throughput(t.clone()); } } group.finish(); } }; ($func_name:ident, $hasher_name:literal, $counts:expr, $closure:expr) => { $crate::benchmark_hash_felt!($func_name, $hasher_name, $counts, $closure, |count| Some( criterion::Throughput::Elements(count as u64) )) }; } // Creates a benchmark for hash merge domain operations #[macro_export] macro_rules! benchmark_hash_merge_domain { ($func_name:ident, $hasher_name:literal, $sizes:expr, $domains:expr, $closure:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("hash-", $hasher_name, "-merge-domain")); group.sample_size(10); for size_ref in $sizes { let size = *size_ref; for domain_ref in $domains { let domain = *domain_ref; group.bench_with_input( criterion::BenchmarkId::new("merge_in_domain", format!("{size}_{domain}")), &(size, domain), |b: &mut criterion::Bencher, param_ref: &(usize, u64)| { let (size_param, domain_param) = *param_ref; $closure(b, (size_param, domain_param)) }, ); } } group.finish(); } }; } // Creates a benchmark for hash merge with int operations #[macro_export] macro_rules! benchmark_hash_merge_with_int { ($func_name:ident, $hasher_name:literal, $sizes:expr, $int_sizes:expr, $closure:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("hash-", $hasher_name, "-merge-int")); group.sample_size(10); for size_ref in $sizes { let size = *size_ref; for int_size_ref in $int_sizes { let int_size = *int_size_ref; group.bench_with_input( criterion::BenchmarkId::new("merge_with_int", format!("{size}_{int_size}")), &(size, int_size), |b: &mut criterion::Bencher, param_ref: &(usize, usize)| { let (size_param, int_size_param) = *param_ref; $closure(b, (size_param, int_size_param)) }, ); } } group.finish(); } }; } // Creates a benchmark for hash merge many operations #[macro_export] macro_rules! benchmark_hash_merge_many { ($func_name:ident, $hasher_name:literal, $digest_counts:expr, $closure:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("hash-", $hasher_name, "-merge-many")); group.sample_size(10); for digest_count_ref in $digest_counts { let digest_count = *digest_count_ref; group.bench_with_input( criterion::BenchmarkId::new("merge_many", digest_count), &digest_count, |b: &mut criterion::Bencher, &digest_count_param: &usize| { $closure(b, digest_count_param) }, ); } group.finish(); } }; } // Creates a benchmark for random coin operations // // # Usage // ```no_run // benchmark_rand_core!( // rpo_draw_elements, // RpoRandomCoin, // TEST_SEED, // "draw_element", // PRNG_OUTPUT_SIZES, // |b, coin, count| { // for _ in 0..count { // coin.draw_element(); // } // } // ); // ``` #[macro_export] macro_rules! benchmark_rand_core { ( $func_name:ident, $coin_type:ty, $seed:expr, $group_name:expr, $operation:literal, $sizes:expr, $closure:expr ) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group($group_name); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); let mut coin = <$coin_type>::new($seed); for count_ref in $sizes { let count = *count_ref; group.bench_with_input( criterion::BenchmarkId::new($operation, count), &count, |b: &mut criterion::Bencher, &count_param: &usize| { b.iter(|| $closure(&mut coin, count_param)) }, ); group.throughput(criterion::Throughput::Elements(count as u64)); } group.finish(); } }; } // Creates a benchmark for random coin operations (legacy interface) // // # Usage // ```no_run // benchmark_rand_coin!( // rpo_draw_elements, // RpoRandomCoin, // TEST_SEED, // "draw_element", // PRNG_OUTPUT_SIZES, // |b, coin, count| { // for _ in 0..count { // coin.draw_element(); // } // } // ); // ``` #[macro_export] macro_rules! benchmark_rand_coin { ( $func_name:ident, $coin_type:ty, $seed:expr, $operation:literal, $sizes:expr, $closure:expr ) => { $crate::benchmark_rand_core! { $func_name, $coin_type, $seed, "rand-".to_string() + stringify!($coin_type).to_lowercase().as_str() + "-" + $operation, $operation, $sizes, $closure } }; } // Creates a benchmark for word conversion operations // // # Usage // ```no_run // benchmark_word_convert!(convert_bool, bool, TEST_WORDS, |word| { word.try_into() }); // ``` #[macro_export] macro_rules! benchmark_word_convert { ($func_name:ident, $target_type:ty, $test_data:expr, $closure:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("word-convert-", stringify!($target_type))); group.bench_function(concat!("try_from_to_", stringify!($target_type)), |b| { b.iter(|| { for word in $test_data { let _result: Result<$target_type, _> = $closure(word); } }) }); group.finish(); } }; } // Creates a benchmark with multiple test cases // // # Usage // ```no_run // benchmark_multi!(my_bench, "operation", &[1, 2, 3], |b, &value| { // // benchmark logic with value // }); // ``` #[macro_export] macro_rules! benchmark_multi { ($func_name:ident, $operation:literal, $test_cases:expr, $closure:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("bench-", $operation)); for &test_case in $test_cases { group.bench_with_input( criterion::BenchmarkId::new($operation, test_case), &test_case, |b, test_case| $closure(b, test_case), ); } group.finish(); } }; } // Creates a benchmark with setup and teardown that uses setup data // // # Usage // ```no_run // benchmark_with_setup_data!(my_bench, measurement_time, sample_size, group_name, setup_closure, |b, data| { ... }); // ``` #[macro_export] macro_rules! benchmark_with_setup_data { ( $func_name:ident, $measurement_time:expr, $sample_size:expr, $group_name:literal, $setup:expr, $closure:expr ) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group($group_name); group.measurement_time($measurement_time); group.sample_size($sample_size as usize); let setup_data = $setup(); group.bench_function("benchmark", |b| $closure(b, &setup_data)); group.finish(); } }; ( $func_name:ident, $measurement_time:expr, $sample_size:expr, $group_name:literal, $setup:expr, $closure:expr, ) => { benchmark_with_setup_data!( $func_name, $measurement_time, $sample_size, $group_name, $setup, $closure ); }; } // Creates a benchmark with setup but ignores setup data // // # Usage // ```no_run // benchmark_with_setup!(my_bench, measurement_time, sample_size, group_name, setup_closure, |b| { ... }); // ``` #[macro_export] macro_rules! benchmark_with_setup { ( $func_name:ident, $measurement_time:expr, $sample_size:expr, $group_name:literal, $setup:expr, $closure:expr ) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group($group_name); group.measurement_time($measurement_time); group.sample_size($sample_size as usize); let _setup_data = $setup(); group.bench_function("benchmark", |b| $closure(b)); group.finish(); } }; ( $func_name:ident, $measurement_time:expr, $sample_size:expr, $group_name:literal, $setup:expr, $closure:expr, ) => { benchmark_with_setup!( $func_name, $measurement_time, $sample_size, $group_name, $setup, $closure ); }; } // Creates a benchmark that uses setup data but doesn't pass it to the closure // // # Usage // ```no_run // benchmark_with_setup_custom!(my_bench, measurement_time, sample_size, group_name, setup_closure, |b, setup_data| { ... }); // ``` #[macro_export] macro_rules! benchmark_with_setup_custom { ( $func_name:ident, $measurement_time:expr, $sample_size:expr, $group_name:literal, $setup:expr, $closure:expr ) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group($group_name); group.measurement_time($measurement_time); group.sample_size($sample_size as usize); let setup_data = $setup(); group.bench_function("benchmark", |b| $closure(b, &setup_data)); group.finish(); } }; ( $func_name:ident, $measurement_time:expr, $sample_size:expr, $group_name:literal, $setup:expr, $closure:expr, ) => { benchmark_with_setup_custom!( $func_name, $measurement_time, $sample_size, $group_name, $setup, $closure ); }; } // Creates a benchmark for batch operations // // # Usage // ```no_run // benchmark_batch!( // batch_operation, // SIZES, // |b, size| { // // batch logic with size // }, // |size| Some(criterion::Throughput::Elements(size as u64)) // ); // ``` #[macro_export] macro_rules! benchmark_batch { ($func_name:ident, $sizes:expr, $closure:expr, $throughput:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group(concat!("batch-", stringify!($func_name))); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); for size_ref in $sizes { let size = *size_ref; group.bench_with_input( criterion::BenchmarkId::new("batch", size), &size, |b, &size| $closure(b, size), ); let throughput = $throughput(size); if let Some(ref t) = throughput { group.throughput(t.clone()); } } group.finish(); } }; } // Creates a benchmark for random coin initialization // // # Usage // ```no_run // benchmark_rand_new!(rand_rpo_new, RpoRandomCoin, TEST_SEED); // ``` #[macro_export] macro_rules! benchmark_rand_new { ($func_name:ident, $coin_type:ty, $seed:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group("rand-new"); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); group.bench_function("new_from_word", |b| { b.iter(|| { let _coin = <$coin_type>::new(black_box($seed)); }); }); group.finish(); } }; } // Creates a benchmark for random coin drawing operations // // # Usage // ```no_run // benchmark_rand_draw!( // rand_rpo_draw_elements, // RpoRandomCoin, // TEST_SEED, // "draw_element", // PRNG_OUTPUT_SIZES, // |b, coin, count| { // for _ in 0..count { // let _element = coin.draw_element(); // } // } // ); // ``` #[macro_export] macro_rules! benchmark_rand_draw { ( $func_name:ident, $coin_type:ty, $seed:expr, $operation:literal, $sizes:expr, $closure:expr ) => { $crate::benchmark_rand_core! { $func_name, $coin_type, $seed, "rand-draw", $operation, $sizes, $closure } }; } // Creates a benchmark for random coin reseeding operations // // # Usage // ```no_run // benchmark_rand_reseed!(rand_rpo_reseed, RpoRandomCoin, TEST_SEED); // ``` #[macro_export] macro_rules! benchmark_rand_reseed { ($func_name:ident, $coin_type:ty, $seed:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group("rand-reseed"); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); let mut coin = <$coin_type>::new($seed); let new_seeds: Vec<miden_crypto::Word> = (0u64..10) .map(|i| miden_crypto::Word::new([miden_crypto::Felt::new((i + 1) as u64); 4])) .collect(); group.bench_function("reseed", |b| { b.iter(|| { for seed in &new_seeds { coin.reseed(black_box(*seed)); } }); }); group.finish(); } }; } /// Creates a benchmark for random coin integer drawing operations /// /// # Usage /// ```no_run /// benchmark_rand_draw_integers!(rand_rpo_draw_integers, RpoRandomCoin, TEST_SEED); /// ``` #[macro_export] macro_rules! benchmark_rand_draw_integers { ($func_name:ident, $coin_type:ty, $seed:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group("rand-draw-integers"); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); let mut coin = <$coin_type>::new($seed); let num_values_list = &[1, 10, 100]; let domain_sizes = &[256, 1024, 4096, 65536]; for &num_values in num_values_list { for &domain_size in domain_sizes { // Ensure num_values < domain_size to avoid assertion error if num_values < domain_size { group.bench_with_input( criterion::BenchmarkId::new( "draw_integers", format!("{num_values}_{domain_size}"), ), &(num_values, domain_size), |b, &(num_values, domain_size)| { b.iter(|| { let _result = coin.draw_integers( black_box(num_values), black_box(domain_size), black_box(0), ); }) }, ); } } } group.finish(); } }; } /// Creates a benchmark for random coin leading zero checking /// /// # Usage /// ```no_run /// benchmark_rand_check_leading_zeros!(rand_rpo_check_leading_zeros, RpoRandomCoin, TEST_SEED); /// ``` #[macro_export] macro_rules! benchmark_rand_check_leading_zeros { ($func_name:ident, $coin_type:ty, $seed:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group("rand-check-leading-zeros"); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); let coin = <$coin_type>::new($seed); let test_values: Vec<u64> = (0u64..100).collect(); group.bench_function("check_leading_zeros", |b| { b.iter(|| { for &value in &test_values { let _zeros = coin.check_leading_zeros(black_box(value)); } }); }); group.finish(); } }; } /// Creates a benchmark for random coin byte filling operations /// /// # Usage /// ```no_run /// benchmark_rand_fill_bytes!( /// rand_rpo_fill_bytes, /// RpoRandomCoin, /// TEST_SEED, /// &[1, 32, 64, 128, 256, 512, 1024] /// ); /// ``` #[macro_export] macro_rules! benchmark_rand_fill_bytes { ($func_name:ident, $coin_type:ty, $seed:expr, $sizes:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group("rand-fill-bytes"); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); let mut coin = <$coin_type>::new($seed); for &size in $sizes { group.bench_with_input( criterion::BenchmarkId::new("fill_bytes", size), &size, |b, &size| { let mut buffer = vec![0u8; size]; b.iter(|| { coin.fill_bytes(black_box(&mut buffer)); }) }, ); } group.finish(); } }; } // Creates a comprehensive benchmark group for random coin implementations // // This macro generates all common random coin benchmarks for a given coin type: // - Initialization // - Element drawing // - Word drawing // - Reseeding // - Integer drawing // - Leading zero checking // - Byte filling // // # Usage // ```no_run // benchmark_rand_comprehensive!( // rand_rpo_, // RpoRandomCoin, // TEST_SEED, // PRNG_OUTPUT_SIZES, // &[1, 32, 64, 128, 256, 512, 1024] // ); // ``` #[macro_export] macro_rules! benchmark_rand_comprehensive { ($prefix:ident, $coin_type:ty, $seed:expr, $output_sizes:expr, $byte_sizes:expr) => { // Initialization benchmark $crate::benchmark_rand_new!($prefix new, $coin_type, $seed); // Element drawing benchmarks $crate::benchmark_rand_draw!( $prefix draw_elements, $coin_type, $seed, "draw_element", $output_sizes, |_b, coin: &mut $coin_type, count| { for _ in 0..count { let _element = coin.draw_element(); } } ); // Word drawing benchmarks $crate::benchmark_rand_draw!( $prefix draw_words, $coin_type, $seed, "draw_word", $output_sizes, |_b, coin: &mut $coin_type, count| { for _ in 0..count { let _word = coin.draw_word(); } } ); // Reseeding benchmark $crate::benchmark_rand_reseed!($prefix reseeding, $coin_type, $seed); // Integer drawing benchmark $crate::benchmark_rand_draw_integers!($prefix draw_integers, $coin_type, $seed); // Leading zero checking benchmark $crate::benchmark_rand_check_leading_zeros!($prefix check_leading_zeros, $coin_type, $seed); // Byte filling benchmark $crate::benchmark_rand_fill_bytes!( $prefix fill_bytes, $coin_type, $seed, $byte_sizes ); }; } // Creates benchmarks for word type conversions with minimal repetition // // This macro generates conversion benchmarks for multiple target types in one call. // It's useful for benchmarking Word::try_into() for various integer types. // // # Usage // ```no_run // benchmark_word_conversions!( // word_convert_basic, // &[bool::default(), u8::default(), u16::default(), u32::default(), u64::default()], // TEST_WORDS // ); // ``` #[macro_export] macro_rules! benchmark_word_conversions { ($func_name:ident, $types:expr, $test_data:expr) => { fn $func_name(c: &mut Criterion) { let mut group = c.benchmark_group("word-conversions-basic"); group.measurement_time($crate::common::config::DEFAULT_MEASUREMENT_TIME); group.sample_size($crate::common::config::DEFAULT_SAMPLE_SIZE); group.bench_function("conversions_batch", |b| { b.iter(|| { for word in $test_data { for &type_template in $types { match type_template { // Handle each type conversion 0 => { let _result: Result<[bool; 4], _> = word.try_into(); }, 1 => { let _result: Result<[u8; 4], _> = word.try_into(); }, 2 => { let _result: Result<[u16; 4], _> = word.try_into(); }, 3 => { let _result: Result<[u32; 4], _> = word.try_into(); }, 4 => { let _result: Result<[u64; 4], _> = word.try_into(); }, _ => {}, } } } }) }); group.finish(); } }; } /// Generates comprehensive AEAD benchmarks for bytes operations. /// /// This macro creates benchmarks for encryption and decryption operations /// using the new standardized approach with consistent data generation, /// throughput measurement, and reduced boilerplate. /// /// # Arguments /// * `$aead_module` - The AEAD module name (e.g., aead_rpo) /// * `$group_prefix` - Human-readable prefix for benchmark group names /// * `$bytes_fn` - The name of the benchmark function to generate for bytes /// * `$group_ident` - The identifier for the criterion group /// /// # Generated benchmarks /// - `$bytes_fn` - Function containing byte array encryption/decryption benchmarks /// - `$group_ident` - Criterion group for the benchmarks #[macro_export] macro_rules! benchmark_aead_bytes { ($aead_module:ident, $group_prefix:expr, $bytes_fn:ident, $group_ident:ident) => { /// Benchmark AEAD operations on byte arrays fn $bytes_fn(c: &mut Criterion) { use miden_crypto::aead::$aead_module::{Nonce, SecretKey}; use rand_chacha::ChaCha20Rng; use rand_core::SeedableRng; let group_name = format!("{} - Byte Arrays", $group_prefix); let mut group = c.benchmark_group(&group_name); let mut rng = ChaCha20Rng::seed_from_u64(42); let key = SecretKey::with_rng(&mut rng); let associated_data = generate_byte_array_sequential(8); for &size in DATA_SIZES { let data = generate_byte_array_random(size); group.throughput(Throughput::Bytes(size as u64)); // Encryption benchmark group.bench_with_input(BenchmarkId::new("encrypt", size), &data, |b, data| { b.iter_batched( || Nonce::with_rng(&mut rng), |nonce| { black_box( key.encrypt_bytes_with_nonce( black_box(data), black_box(&associated_data), black_box(nonce), ) .unwrap(), ); }, criterion::BatchSize::SmallInput, ); }); // Pre-encrypt data for decryption benchmark let nonce = Nonce::with_rng(&mut rng); let encrypted = key.encrypt_bytes_with_nonce(&data, &associated_data, nonce.clone()).unwrap(); // Decryption benchmark group.bench_with_input( BenchmarkId::new("decrypt", size),
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
true
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/common/mod.rs
miden-crypto/benches/common/mod.rs
//! Common benchmark configuration and utilities for systematic benchmarking. //! //! This module provides standardized configuration and helper functions //! to ensure consistent benchmarking across all benchmark modules. //! //! # Organization //! //! All benchmark modules follow this structure: //! 1. Configuration setup (using common helpers) //! 2. Input data generation functions (following naming convention) //! 3. Benchmark functions (following naming convention) //! 4. Group definition and main export //! //! # Naming Conventions //! //! ## Benchmark Functions //! - `hash_<algorithm>_<operation>_<data_type>` (e.g., `hash_rpo256_single_byte`, //! `hash_rpo256_sequential_felt`) //! - `merkle_<structure>_<operation>_<parameter>` (e.g., `merkle_smt_update_sparse`, //! `merkle_mmr_proof_generation`) //! //! ## Input Generation Functions //! - `generate_<data_type>_<size>` (e.g., `generate_byte_array_896` for 896 bytes) //! - `generate_<data_type>_random_<size>` (e.g., `generate_byte_array_random_1024` for 1KB) //! //! ## Configuration Functions //! - `setup_<benchmark_group>_config()` (e.g., `setup_hash_benchmarks_config()`) //! //! # Adding New Benchmarks //! //! To add a new benchmark module: //! 1. Create `benches/<category>_all.rs` (e.g., `benches/hash_all.rs`) //! 2. Import `common::*` //! 3. Follow the naming conventions //! 4. Use the provided configuration helpers //! 5. Export the benchmark group #![allow(dead_code)] // benchmark use doesn't count as "usage" for linting pub mod config; pub mod data; pub mod macros;
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-crypto/benches/common/data.rs
miden-crypto/benches/common/data.rs
//! Data generation utilities for consistent benchmark inputs //! //! This module provides generic functions for generating test data //! across all benchmark modules to ensure reproducible and consistent results. //! //! # Word Patterns //! //! The module provides several predefined word patterns for different use cases: //! - `MerkleStandard`: [i, ONE, ONE, i] - common in Merkle tree benchmarks //! - `Sequential`: [i, i+1, i+2, i+3] - sequential pattern //! - `SpreadSequential`: [i, i+4, i+8, i+12] - spread sequential //! - `Random`: using PRNG for more varied data //! //! # Usage Pattern //! //! ```rust //! use miden_crypto::{Felt, benches::common::data::*}; //! //! // Generate test data using generic functions //! let small_data = generate_byte_array_sequential(100); //! let medium_data = generate_felt_array_sequential(1000); //! let random_data = generate_byte_array_random(1024); //! //! // Generate words using specific patterns //! let merkle_words = generate_words_merkle_std(256); //! let sequential_words = generate_words_pattern(100, WordPattern::Sequential); //! let mixed_entries = generate_smt_entries_mixed(128); // More realistic distribution //! ``` use std::iter; use miden_crypto::{ Felt, ONE, Word, rand::test_utils::{prng_array, rand_value}, }; // === Byte Array Generation === /// Generate byte array of specified size with sequential data pub fn generate_byte_array_sequential(size: usize) -> Vec<u8> { (0..size).map(|i| i as u8).collect() } /// Generate byte array of specified size with random data pub fn generate_byte_array_random(size: usize) -> Vec<u8> { iter::from_fn(|| Some(rand_value::<u8>())).take(size).collect() } // === Field Element Generation === /// Generate field element array with sequential values pub fn generate_felt_array_sequential(size: usize) -> Vec<Felt> { (0..size).map(|i| Felt::new(i as u64)).collect() } /// Generate byte array of specified size with random data pub fn generate_felt_array_random(size: usize) -> Vec<Felt> { iter::from_fn(|| Some(Felt::new(rand_value::<u64>()))).take(size).collect() } // === Word and Value Generation === /// Common word patterns for benchmarking #[derive(Clone, Copy, Debug)] pub enum WordPattern { /// Pattern: [i, ONE, ONE, i] - common in Merkle tree benchmarks MerkleStandard, /// Pattern: [i, i+1, i+2, i+3] - sequential pattern Sequential, /// Pattern: [i, i+4, i+8, i+12] - spread sequential SpreadSequential, /// Pattern using random generation Random, } /// Generate a Word from seed using PRNG pub fn generate_word(seed: &mut [u8; 32]) -> Word { *seed = prng_array(*seed); let nums: [u64; 4] = prng_array(*seed); Word::new([Felt::new(nums[0]), Felt::new(nums[1]), Felt::new(nums[2]), Felt::new(nums[3])]) } /// Generate a generic value from seed using PRNG pub fn generate_value<T: miden_crypto::rand::Randomizable + std::fmt::Debug + Clone>( seed: &mut [u8; 32], ) -> T { *seed = prng_array(*seed); let value: [T; 1] = miden_crypto::rand::test_utils::prng_array(*seed); value[0].clone() } /// Generate word using specified pattern pub fn generate_word_pattern(i: u64, pattern: WordPattern) -> Word { match pattern { WordPattern::MerkleStandard => Word::new([Felt::new(i), ONE, ONE, Felt::new(i)]), WordPattern::Sequential => { Word::new([Felt::new(i), Felt::new(i + 1), Felt::new(i + 2), Felt::new(i + 3)]) }, WordPattern::SpreadSequential => { Word::new([Felt::new(i), Felt::new(i + 4), Felt::new(i + 8), Felt::new(i + 12)]) }, WordPattern::Random => { let mut seed = [0u8; 32]; seed[0..8].copy_from_slice(&i.to_le_bytes()); generate_word(&mut seed) }, } } /// Generate vector of words using specified pattern pub fn generate_words_pattern(count: usize, pattern: WordPattern) -> Vec<Word> { (0..count as u64).map(|i| generate_word_pattern(i, pattern)).collect() } /// Generate vector of words using the common Merkle standard pattern pub fn generate_words_merkle_std(count: usize) -> Vec<Word> { generate_words_pattern(count, WordPattern::MerkleStandard) } /// Prepare key-value entries for SMT benchmarks pub fn prepare_smt_entries(pair_count: u64, seed: &mut [u8; 32]) -> Vec<(Word, Word)> { let entries: Vec<(Word, Word)> = (0..pair_count) .map(|i| { let count = pair_count as f64; let idx = ((i as f64 / count) * (count)) as u64; let key = Word::new([generate_value(seed), ONE, Felt::new(i), Felt::new(idx)]); let value = generate_word(seed); (key, value) }) .collect(); entries } /// Generate test key-value pairs for SMT benchmarks (sequential) pub fn generate_smt_entries_sequential(count: usize) -> Vec<(Word, Word)> { (0..count as u64) .map(|i| { let key = generate_word_pattern(i, WordPattern::Sequential); let value = generate_word_pattern(i + 4, WordPattern::Sequential); (key, value) }) .collect() } /// Generate test entries for SimpleSmt benchmarks (sequential) pub fn generate_simple_smt_entries_sequential(count: usize) -> Vec<(u64, Word)> { (0..count) .map(|i| { let key = i as u64; let value = generate_word_pattern(i as u64, WordPattern::Sequential); (key, value) }) .collect() } /// Generate test keys for lookup operations (sequential) pub fn generate_test_keys_sequential(count: usize) -> Vec<Word> { generate_words_pattern(count, WordPattern::Sequential) } /// More complex SMT entries using mixed patterns for realistic testing pub fn generate_smt_entries_mixed(count: usize) -> Vec<(Word, Word)> { (0..count as u64) .map(|i| { // Use different patterns for keys based on index to create more realistic distribution let key_pattern = match rand_value::<u8>() % 4 { 0 => WordPattern::Sequential, 1 => WordPattern::SpreadSequential, 2 => WordPattern::MerkleStandard, _ => WordPattern::Random, }; // Values use offset sequential pattern let value = generate_word_pattern(i + 1000, WordPattern::Sequential); let key = generate_word_pattern(i, key_pattern); (key, value) }) .collect() } /// Generate SMT entries with clustered distribution (more realistic access patterns) pub fn generate_smt_entries_clustered(count: usize, clusters: usize) -> Vec<(Word, Word)> { let cluster_size = count / clusters; (0..count as u64) .map(|i| { let cluster_id = (i as usize / cluster_size) as u64; let cluster_offset = i % cluster_size as u64; // Keys are clustered around specific base values let base = cluster_id * 10000; let key = generate_word_pattern(base + cluster_offset, WordPattern::Sequential); let value = generate_word_pattern(i, WordPattern::SpreadSequential); (key, value) }) .collect() }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-serde-utils/src/lib.rs
miden-serde-utils/src/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; use alloc::{ collections::{BTreeMap, BTreeSet}, format, string::String, vec::Vec, }; // ERROR // ================================================================================================ /// Defines errors which can occur during deserialization. #[derive(Clone, Debug, PartialEq, Eq)] pub enum DeserializationError { /// Indicates that the deserialization failed because of insufficient data. UnexpectedEOF, /// Indicates that the deserialization failed because the value was not valid. InvalidValue(String), /// Indicates that deserialization failed for an unknown reason. UnknownError(String), } #[cfg(feature = "std")] impl std::error::Error for DeserializationError {} impl core::fmt::Display for DeserializationError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::UnexpectedEOF => write!(f, "unexpected end of file"), Self::InvalidValue(msg) => write!(f, "invalid value: {}", msg), Self::UnknownError(msg) => write!(f, "unknown error: {}", msg), } } } mod byte_reader; #[cfg(feature = "std")] pub use byte_reader::ReadAdapter; pub use byte_reader::{ByteReader, SliceReader}; mod byte_writer; pub use byte_writer::ByteWriter; // SERIALIZABLE TRAIT // ================================================================================================ /// Defines how to serialize `Self` into bytes. pub trait Serializable { // REQUIRED METHODS // -------------------------------------------------------------------------------------------- /// Serializes `self` into bytes and writes these bytes into the `target`. fn write_into<W: ByteWriter>(&self, target: &mut W); // PROVIDED METHODS // -------------------------------------------------------------------------------------------- /// Serializes `self` into a vector of bytes. fn to_bytes(&self) -> Vec<u8> { let mut result = Vec::with_capacity(self.get_size_hint()); self.write_into(&mut result); result } /// Returns an estimate of how many bytes are needed to represent self. /// /// The default implementation returns zero. fn get_size_hint(&self) -> usize { 0 } } impl<T: Serializable> Serializable for &T { fn write_into<W: ByteWriter>(&self, target: &mut W) { (*self).write_into(target) } fn get_size_hint(&self) -> usize { (*self).get_size_hint() } } impl Serializable for () { fn write_into<W: ByteWriter>(&self, _target: &mut W) {} fn get_size_hint(&self) -> usize { 0 } } impl<T1> Serializable for (T1,) where T1: Serializable, { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.0.write_into(target); } fn get_size_hint(&self) -> usize { self.0.get_size_hint() } } impl<T1, T2> Serializable for (T1, T2) where T1: Serializable, T2: Serializable, { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.0.write_into(target); self.1.write_into(target); } fn get_size_hint(&self) -> usize { self.0.get_size_hint() + self.1.get_size_hint() } } impl<T1, T2, T3> Serializable for (T1, T2, T3) where T1: Serializable, T2: Serializable, T3: Serializable, { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.0.write_into(target); self.1.write_into(target); self.2.write_into(target); } fn get_size_hint(&self) -> usize { self.0.get_size_hint() + self.1.get_size_hint() + self.2.get_size_hint() } } impl<T1, T2, T3, T4> Serializable for (T1, T2, T3, T4) where T1: Serializable, T2: Serializable, T3: Serializable, T4: Serializable, { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.0.write_into(target); self.1.write_into(target); self.2.write_into(target); self.3.write_into(target); } fn get_size_hint(&self) -> usize { self.0.get_size_hint() + self.1.get_size_hint() + self.2.get_size_hint() + self.3.get_size_hint() } } impl<T1, T2, T3, T4, T5> Serializable for (T1, T2, T3, T4, T5) where T1: Serializable, T2: Serializable, T3: Serializable, T4: Serializable, T5: Serializable, { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.0.write_into(target); self.1.write_into(target); self.2.write_into(target); self.3.write_into(target); self.4.write_into(target); } fn get_size_hint(&self) -> usize { self.0.get_size_hint() + self.1.get_size_hint() + self.2.get_size_hint() + self.3.get_size_hint() + self.4.get_size_hint() } } impl<T1, T2, T3, T4, T5, T6> Serializable for (T1, T2, T3, T4, T5, T6) where T1: Serializable, T2: Serializable, T3: Serializable, T4: Serializable, T5: Serializable, T6: Serializable, { fn write_into<W: ByteWriter>(&self, target: &mut W) { self.0.write_into(target); self.1.write_into(target); self.2.write_into(target); self.3.write_into(target); self.4.write_into(target); self.5.write_into(target); } fn get_size_hint(&self) -> usize { self.0.get_size_hint() + self.1.get_size_hint() + self.2.get_size_hint() + self.3.get_size_hint() + self.4.get_size_hint() + self.5.get_size_hint() } } impl Serializable for u8 { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u8(*self); } fn get_size_hint(&self) -> usize { core::mem::size_of::<u8>() } } impl Serializable for u16 { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u16(*self); } fn get_size_hint(&self) -> usize { core::mem::size_of::<u16>() } } impl Serializable for u32 { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u32(*self); } fn get_size_hint(&self) -> usize { core::mem::size_of::<u32>() } } impl Serializable for u64 { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u64(*self); } fn get_size_hint(&self) -> usize { core::mem::size_of::<u64>() } } impl Serializable for u128 { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u128(*self); } fn get_size_hint(&self) -> usize { core::mem::size_of::<u128>() } } impl Serializable for usize { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(*self) } fn get_size_hint(&self) -> usize { byte_writer::usize_encoded_len(*self as u64) } } impl<T: Serializable> Serializable for Option<T> { fn write_into<W: ByteWriter>(&self, target: &mut W) { match self { Some(v) => { target.write_bool(true); v.write_into(target); }, None => target.write_bool(false), } } fn get_size_hint(&self) -> usize { core::mem::size_of::<bool>() + self.as_ref().map(|value| value.get_size_hint()).unwrap_or(0) } } impl<T: Serializable, const C: usize> Serializable for [T; C] { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_many(self) } fn get_size_hint(&self) -> usize { let mut size = 0; for item in self { size += item.get_size_hint(); } size } } impl<T: Serializable> Serializable for [T] { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(self.len()); for element in self.iter() { element.write_into(target); } } fn get_size_hint(&self) -> usize { let mut size = self.len().get_size_hint(); for element in self { size += element.get_size_hint(); } size } } impl<T: Serializable> Serializable for Vec<T> { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(self.len()); target.write_many(self); } fn get_size_hint(&self) -> usize { let mut size = self.len().get_size_hint(); for item in self { size += item.get_size_hint(); } size } } impl<K: Serializable, V: Serializable> Serializable for BTreeMap<K, V> { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(self.len()); target.write_many(self); } fn get_size_hint(&self) -> usize { let mut size = self.len().get_size_hint(); for item in self { size += item.get_size_hint(); } size } } impl<T: Serializable> Serializable for BTreeSet<T> { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(self.len()); target.write_many(self); } fn get_size_hint(&self) -> usize { let mut size = self.len().get_size_hint(); for item in self { size += item.get_size_hint(); } size } } impl Serializable for str { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(self.len()); target.write_many(self.as_bytes()); } fn get_size_hint(&self) -> usize { self.len().get_size_hint() + self.len() } } impl Serializable for String { fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_usize(self.len()); target.write_many(self.as_bytes()); } fn get_size_hint(&self) -> usize { self.len().get_size_hint() + self.len() } } // DESERIALIZABLE // ================================================================================================ /// Defines how to deserialize `Self` from bytes. pub trait Deserializable: Sized { // REQUIRED METHODS // -------------------------------------------------------------------------------------------- /// Reads a sequence of bytes from the provided `source`, attempts to deserialize these bytes /// into `Self`, and returns the result. /// /// # Errors /// Returns an error if: /// * The `source` does not contain enough bytes to deserialize `Self`. /// * Bytes read from the `source` do not represent a valid value for `Self`. fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError>; // PROVIDED METHODS // -------------------------------------------------------------------------------------------- /// Attempts to deserialize the provided `bytes` into `Self` and returns the result. /// /// # Errors /// Returns an error if: /// * The `bytes` do not contain enough information to deserialize `Self`. /// * The `bytes` do not represent a valid value for `Self`. /// /// Note: if `bytes` contains more data than needed to deserialize `self`, no error is /// returned. fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> { Self::read_from(&mut SliceReader::new(bytes)) } } impl Deserializable for () { fn read_from<R: ByteReader>(_source: &mut R) -> Result<Self, DeserializationError> { Ok(()) } } impl<T1> Deserializable for (T1,) where T1: Deserializable, { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let v1 = T1::read_from(source)?; Ok((v1,)) } } impl<T1, T2> Deserializable for (T1, T2) where T1: Deserializable, T2: Deserializable, { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let v1 = T1::read_from(source)?; let v2 = T2::read_from(source)?; Ok((v1, v2)) } } impl<T1, T2, T3> Deserializable for (T1, T2, T3) where T1: Deserializable, T2: Deserializable, T3: Deserializable, { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let v1 = T1::read_from(source)?; let v2 = T2::read_from(source)?; let v3 = T3::read_from(source)?; Ok((v1, v2, v3)) } } impl<T1, T2, T3, T4> Deserializable for (T1, T2, T3, T4) where T1: Deserializable, T2: Deserializable, T3: Deserializable, T4: Deserializable, { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let v1 = T1::read_from(source)?; let v2 = T2::read_from(source)?; let v3 = T3::read_from(source)?; let v4 = T4::read_from(source)?; Ok((v1, v2, v3, v4)) } } impl<T1, T2, T3, T4, T5> Deserializable for (T1, T2, T3, T4, T5) where T1: Deserializable, T2: Deserializable, T3: Deserializable, T4: Deserializable, T5: Deserializable, { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let v1 = T1::read_from(source)?; let v2 = T2::read_from(source)?; let v3 = T3::read_from(source)?; let v4 = T4::read_from(source)?; let v5 = T5::read_from(source)?; Ok((v1, v2, v3, v4, v5)) } } impl<T1, T2, T3, T4, T5, T6> Deserializable for (T1, T2, T3, T4, T5, T6) where T1: Deserializable, T2: Deserializable, T3: Deserializable, T4: Deserializable, T5: Deserializable, T6: Deserializable, { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let v1 = T1::read_from(source)?; let v2 = T2::read_from(source)?; let v3 = T3::read_from(source)?; let v4 = T4::read_from(source)?; let v5 = T5::read_from(source)?; let v6 = T6::read_from(source)?; Ok((v1, v2, v3, v4, v5, v6)) } } impl Deserializable for u8 { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { source.read_u8() } } impl Deserializable for u16 { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { source.read_u16() } } impl Deserializable for u32 { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { source.read_u32() } } impl Deserializable for u64 { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { source.read_u64() } } impl Deserializable for u128 { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { source.read_u128() } } impl Deserializable for usize { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { source.read_usize() } } impl<T: Deserializable> Deserializable for Option<T> { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let contains = source.read_bool()?; match contains { true => Ok(Some(T::read_from(source)?)), false => Ok(None), } } } impl<T: Deserializable, const C: usize> Deserializable for [T; C] { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let data: Vec<T> = source.read_many(C)?; // SAFETY: the call above only returns a Vec if there are `C` elements, this conversion // always succeeds let res = data.try_into().unwrap_or_else(|v: Vec<T>| { panic!("Expected a Vec of length {} but it was {}", C, v.len()) }); Ok(res) } } impl<T: Deserializable> Deserializable for Vec<T> { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let len = source.read_usize()?; source.read_many(len) } } impl<K: Deserializable + Ord, V: Deserializable> Deserializable for BTreeMap<K, V> { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let len = source.read_usize()?; let data = source.read_many(len)?; Ok(BTreeMap::from_iter(data)) } } impl<T: Deserializable + Ord> Deserializable for BTreeSet<T> { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let len = source.read_usize()?; let data = source.read_many(len)?; Ok(BTreeSet::from_iter(data)) } } impl Deserializable for String { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let len = source.read_usize()?; let data = source.read_many(len)?; String::from_utf8(data).map_err(|err| DeserializationError::InvalidValue(format!("{err}"))) } } // GOLDILOCKS FIELD ELEMENT IMPLEMENTATIONS // ================================================================================================ impl Serializable for p3_miden_goldilocks::Goldilocks { fn write_into<W: ByteWriter>(&self, target: &mut W) { use p3_field::PrimeField64; target.write_u64(self.as_canonical_u64()); } fn get_size_hint(&self) -> usize { core::mem::size_of::<u64>() } } impl Deserializable for p3_miden_goldilocks::Goldilocks { fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { use p3_field::integers::QuotientMap; let value = source.read_u64()?; Self::from_canonical_checked(value).ok_or_else(|| { DeserializationError::InvalidValue(format!( "value {} is not a valid Goldilocks field element", value )) }) } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-serde-utils/src/byte_writer.rs
miden-serde-utils/src/byte_writer.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crate::Serializable; // BYTE WRITER TRAIT // ================================================================================================ /// Defines how primitive values are to be written into `Self`. pub trait ByteWriter: Sized { // REQUIRED METHODS // -------------------------------------------------------------------------------------------- /// Writes a single byte into `self`. /// /// # Panics /// Panics if the byte could not be written into `self`. fn write_u8(&mut self, value: u8); /// Writes a sequence of bytes into `self`. /// /// # Panics /// Panics if the sequence of bytes could not be written into `self`. fn write_bytes(&mut self, values: &[u8]); // PROVIDED METHODS // -------------------------------------------------------------------------------------------- /// Writes a boolean value into `self`. /// /// A boolean value is written as a single byte. /// /// # Panics /// Panics if the value could not be written into `self`. fn write_bool(&mut self, val: bool) { self.write_u8(val as u8); } /// Writes a u16 value in little-endian byte order into `self`. /// /// # Panics /// Panics if the value could not be written into `self`. fn write_u16(&mut self, value: u16) { self.write_bytes(&value.to_le_bytes()); } /// Writes a u32 value in little-endian byte order into `self`. /// /// # Panics /// Panics if the value could not be written into `self`. fn write_u32(&mut self, value: u32) { self.write_bytes(&value.to_le_bytes()); } /// Writes a u64 value in little-endian byte order into `self`. /// /// # Panics /// Panics if the value could not be written into `self`. fn write_u64(&mut self, value: u64) { self.write_bytes(&value.to_le_bytes()); } /// Writes a u128 value in little-endian byte order into `self`. /// /// # Panics /// Panics if the value could not be written into `self`. fn write_u128(&mut self, value: u128) { self.write_bytes(&value.to_le_bytes()); } /// Writes a usize value in [vint64](https://docs.rs/vint64/latest/vint64/) format into `self`. /// /// # Panics /// Panics if the value could not be written into `self`. fn write_usize(&mut self, value: usize) { // convert the value into a u64 so that we always get 8 bytes from to_le_bytes() call let value = value as u64; let length = usize_encoded_len(value); // 9-byte special case if length == 9 { // length byte is zero in this case self.write_u8(0); self.write(value.to_le_bytes()); } else { let encoded_bytes = (((value << 1) | 1) << (length - 1)).to_le_bytes(); self.write_bytes(&encoded_bytes[..length]); } } /// Writes a serializable value into `self`. /// /// # Panics /// Panics if the value could not be written into `self`. fn write<S: Serializable>(&mut self, value: S) { value.write_into(self) } /// Serializes all `elements` and writes the resulting bytes into `self`. /// /// This method does not write any metadata (e.g. number of serialized elements) into `self`. fn write_many<S, T>(&mut self, elements: T) where T: IntoIterator<Item = S>, S: Serializable, { for element in elements { element.write_into(self); } } } // BYTE WRITER IMPLEMENTATIONS // ================================================================================================ #[cfg(feature = "std")] impl<W: std::io::Write> ByteWriter for W { #[inline(always)] fn write_u8(&mut self, byte: u8) { <W as std::io::Write>::write_all(self, &[byte]).expect("write failed") } #[inline(always)] fn write_bytes(&mut self, bytes: &[u8]) { <W as std::io::Write>::write_all(self, bytes).expect("write failed") } } #[cfg(not(feature = "std"))] impl ByteWriter for alloc::vec::Vec<u8> { fn write_u8(&mut self, value: u8) { self.push(value); } fn write_bytes(&mut self, values: &[u8]) { self.extend_from_slice(values); } } // HELPER FUNCTIONS // ================================================================================================ /// Returns the length of the usize value in vint64 encoding. pub(super) fn usize_encoded_len(value: u64) -> usize { let zeros = value.leading_zeros() as usize; let len = zeros.saturating_sub(1) / 7; 9 - core::cmp::min(len, 8) } #[cfg(all(test, feature = "std"))] mod tests { use std::io::Cursor; use super::*; #[test] fn write_adapter_passthrough() { let mut writer = Cursor::new([0u8; 128]); writer.write_bytes(b"nope"); let buf = writer.get_ref(); assert_eq!(&buf[..4], b"nope"); } #[test] #[should_panic] fn write_adapter_writer_out_of_capacity() { let mut writer = Cursor::new([0; 2]); writer.write_bytes(b"nope"); } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
0xMiden/crypto
https://github.com/0xMiden/crypto/blob/b30552ecceb5f70565cc0267fca227f30c5af7ab/miden-serde-utils/src/byte_reader.rs
miden-serde-utils/src/byte_reader.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #[cfg(feature = "std")] use alloc::string::ToString; use alloc::{format, string::String, vec::Vec}; #[cfg(feature = "std")] use core::cell::{Ref, RefCell}; #[cfg(feature = "std")] use std::io::BufRead; use crate::{Deserializable, DeserializationError}; // BYTE READER TRAIT // ================================================================================================ /// Defines how primitive values are to be read from `Self`. /// /// Whenever data is read from the reader using any of the `read_*` functions, the reader advances /// to the next unread byte. If the error occurs, the reader is not rolled back to the state prior /// to calling any of the function. pub trait ByteReader { // REQUIRED METHODS // -------------------------------------------------------------------------------------------- /// Returns a single byte read from `self`. /// /// # Errors /// Returns a [DeserializationError] error the reader is at EOF. fn read_u8(&mut self) -> Result<u8, DeserializationError>; /// Returns the next byte to be read from `self` without advancing the reader to the next byte. /// /// # Errors /// Returns a [DeserializationError] error the reader is at EOF. fn peek_u8(&self) -> Result<u8, DeserializationError>; /// Returns a slice of bytes of the specified length read from `self`. /// /// # Errors /// Returns a [DeserializationError] if a slice of the specified length could not be read /// from `self`. fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError>; /// Returns a byte array of length `N` read from `self`. /// /// # Errors /// Returns a [DeserializationError] if an array of the specified length could not be read /// from `self`. fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError>; /// Checks if it is possible to read at least `num_bytes` bytes from this ByteReader /// /// # Errors /// Returns an error if, when reading the requested number of bytes, we go beyond the /// the data available in the reader. fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError>; /// Returns true if there are more bytes left to be read from `self`. fn has_more_bytes(&self) -> bool; // PROVIDED METHODS // -------------------------------------------------------------------------------------------- /// Returns a boolean value read from `self` consuming 1 byte from the reader. /// /// # Errors /// Returns a [DeserializationError] if a u16 value could not be read from `self`. fn read_bool(&mut self) -> Result<bool, DeserializationError> { let byte = self.read_u8()?; match byte { 0 => Ok(false), 1 => Ok(true), _ => Err(DeserializationError::InvalidValue(format!("{byte} is not a boolean value"))), } } /// Returns a u16 value read from `self` in little-endian byte order. /// /// # Errors /// Returns a [DeserializationError] if a u16 value could not be read from `self`. fn read_u16(&mut self) -> Result<u16, DeserializationError> { let bytes = self.read_array::<2>()?; Ok(u16::from_le_bytes(bytes)) } /// Returns a u32 value read from `self` in little-endian byte order. /// /// # Errors /// Returns a [DeserializationError] if a u32 value could not be read from `self`. fn read_u32(&mut self) -> Result<u32, DeserializationError> { let bytes = self.read_array::<4>()?; Ok(u32::from_le_bytes(bytes)) } /// Returns a u64 value read from `self` in little-endian byte order. /// /// # Errors /// Returns a [DeserializationError] if a u64 value could not be read from `self`. fn read_u64(&mut self) -> Result<u64, DeserializationError> { let bytes = self.read_array::<8>()?; Ok(u64::from_le_bytes(bytes)) } /// Returns a u128 value read from `self` in little-endian byte order. /// /// # Errors /// Returns a [DeserializationError] if a u128 value could not be read from `self`. fn read_u128(&mut self) -> Result<u128, DeserializationError> { let bytes = self.read_array::<16>()?; Ok(u128::from_le_bytes(bytes)) } /// Returns a usize value read from `self` in [vint64](https://docs.rs/vint64/latest/vint64/) /// format. /// /// # Errors /// Returns a [DeserializationError] if: /// * usize value could not be read from `self`. /// * encoded value is greater than `usize` maximum value on a given platform. fn read_usize(&mut self) -> Result<usize, DeserializationError> { let first_byte = self.peek_u8()?; let length = first_byte.trailing_zeros() as usize + 1; let result = if length == 9 { // 9-byte special case self.read_u8()?; let value = self.read_array::<8>()?; u64::from_le_bytes(value) } else { let mut encoded = [0u8; 8]; let value = self.read_slice(length)?; encoded[..length].copy_from_slice(value); u64::from_le_bytes(encoded) >> length }; // check if the result value is within acceptable bounds for `usize` on a given platform if result > usize::MAX as u64 { return Err(DeserializationError::InvalidValue(format!( "Encoded value must be less than {}, but {} was provided", usize::MAX, result ))); } Ok(result as usize) } /// Returns a byte vector of the specified length read from `self`. /// /// # Errors /// Returns a [DeserializationError] if a vector of the specified length could not be read /// from `self`. fn read_vec(&mut self, len: usize) -> Result<Vec<u8>, DeserializationError> { let data = self.read_slice(len)?; Ok(data.to_vec()) } /// Returns a String of the specified length read from `self`. /// /// # Errors /// Returns a [DeserializationError] if a String of the specified length could not be read /// from `self`. fn read_string(&mut self, num_bytes: usize) -> Result<String, DeserializationError> { let data = self.read_vec(num_bytes)?; String::from_utf8(data).map_err(|err| DeserializationError::InvalidValue(format!("{err}"))) } /// Reads a deserializable value from `self`. /// /// # Errors /// Returns a [DeserializationError] if the specified value could not be read from `self`. fn read<D>(&mut self) -> Result<D, DeserializationError> where Self: Sized, D: Deserializable, { D::read_from(self) } /// Reads a sequence of bytes from `self`, attempts to deserialize these bytes into a vector /// with the specified number of `D` elements, and returns the result. /// /// # Errors /// Returns a [DeserializationError] if the specified number elements could not be read from /// `self`. fn read_many<D>(&mut self, num_elements: usize) -> Result<Vec<D>, DeserializationError> where Self: Sized, D: Deserializable, { let mut result = Vec::with_capacity(num_elements); for _ in 0..num_elements { let element = D::read_from(self)?; result.push(element) } Ok(result) } } // STANDARD LIBRARY ADAPTER // ================================================================================================ /// An adapter of [ByteReader] to any type that implements [std::io::Read] /// /// In particular, this covers things like [std::fs::File], standard input, etc. #[cfg(feature = "std")] pub struct ReadAdapter<'a> { // NOTE: The [ByteReader] trait does not currently support reader implementations that require // mutation during `peek_u8`, `has_more_bytes`, and `check_eor`. These (or equivalent) // operations on the standard library [std::io::BufRead] trait require a mutable reference, as // it may be necessary to read from the underlying input to implement them. // // To handle this, we wrap the underlying reader in an [RefCell], this allows us to mutate the // reader if necessary during a call to one of the above-mentioned trait methods, without // sacrificing safety - at the cost of enforcing Rust's borrowing semantics dynamically. // // This should not be a problem in practice, except in the case where `read_slice` is called, // and the reference returned is from `reader` directly, rather than `buf`. If a call to one // of the above-mentioned methods is made while that reference is live, and we attempt to read // from `reader`, a panic will occur. // // Ultimately, this should be addressed by making the [ByteReader] trait align with the // standard library I/O traits, so this is a temporary solution. reader: RefCell<std::io::BufReader<&'a mut dyn std::io::Read>>, // A temporary buffer to store chunks read from `reader` that are larger than what is required // for the higher-level [ByteReader] APIs. // // By default we attempt to satisfy reads from `reader` directly, but that is not always // possible. buf: alloc::vec::Vec<u8>, // The position in `buf` at which we should start reading the next byte, when `buf` is // non-empty. pos: usize, // This is set when we attempt to read from `reader` and get an empty buffer. This indicates // that once we exhaust `buf`, we have truly reached end-of-file. // // We will use this to more accurately handle functions like `has_more_bytes` when this is set. guaranteed_eof: bool, } #[cfg(feature = "std")] impl<'a> ReadAdapter<'a> { /// Create a new [ByteReader] adapter for the given implementation of [std::io::Read] pub fn new(reader: &'a mut dyn std::io::Read) -> Self { Self { reader: RefCell::new(std::io::BufReader::with_capacity(256, reader)), buf: Default::default(), pos: 0, guaranteed_eof: false, } } /// Get the internal adapter buffer as a (possibly empty) slice of bytes #[inline(always)] fn buffer(&self) -> &[u8] { self.buf.get(self.pos..).unwrap_or(&[]) } /// Get the internal adapter buffer as a slice of bytes, or `None` if the buffer is empty #[inline(always)] fn non_empty_buffer(&self) -> Option<&[u8]> { self.buf.get(self.pos..).filter(|b| !b.is_empty()) } /// Return the current reader buffer as a (possibly empty) slice of bytes. /// /// This buffer being empty _does not_ mean we're at EOF, you must call /// [non_empty_reader_buffer_mut] first. #[inline(always)] fn reader_buffer(&self) -> Ref<'_, [u8]> { Ref::map(self.reader.borrow(), |r| r.buffer()) } /// Return the current reader buffer, reading from the underlying reader /// if the buffer is empty. /// /// Returns `Ok` only if the buffer is non-empty, and no errors occurred /// while filling it (if filling was needed). fn non_empty_reader_buffer_mut(&mut self) -> Result<&[u8], DeserializationError> { use std::io::ErrorKind; let buf = self.reader.get_mut().fill_buf().map_err(|e| match e.kind() { ErrorKind::UnexpectedEof => DeserializationError::UnexpectedEOF, e => DeserializationError::UnknownError(e.to_string()), })?; if buf.is_empty() { self.guaranteed_eof = true; Err(DeserializationError::UnexpectedEOF) } else { Ok(buf) } } /// Same as [non_empty_reader_buffer_mut], but with dynamically-enforced /// borrow check rules so that it can be called in functions like `peek_u8`. /// /// This comes with overhead for the dynamic checks, so you should prefer /// to call [non_empty_reader_buffer_mut] if you already have a mutable /// reference to `self` fn non_empty_reader_buffer(&self) -> Result<Ref<'_, [u8]>, DeserializationError> { use std::io::ErrorKind; let mut reader = self.reader.borrow_mut(); let buf = reader.fill_buf().map_err(|e| match e.kind() { ErrorKind::UnexpectedEof => DeserializationError::UnexpectedEOF, e => DeserializationError::UnknownError(e.to_string()), })?; if buf.is_empty() { Err(DeserializationError::UnexpectedEOF) } else { // Re-borrow immutably drop(reader); Ok(self.reader_buffer()) } } /// Returns true if there is sufficient capacity remaining in `buf` to hold `n` bytes #[inline] fn has_remaining_capacity(&self, n: usize) -> bool { let remaining = self.buf.capacity() - self.buffer().len(); remaining >= n } /// Takes the next byte from the input, returning an error if the operation fails fn pop(&mut self) -> Result<u8, DeserializationError> { if let Some(byte) = self.non_empty_buffer().map(|b| b[0]) { self.pos += 1; return Ok(byte); } let result = self.non_empty_reader_buffer_mut().map(|b| b[0]); if result.is_ok() { self.reader.get_mut().consume(1); } else { self.guaranteed_eof = true; } result } /// Takes the next `N` bytes from the input as an array, returning an error if the operation /// fails fn read_exact<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> { let buf = self.buffer(); let mut output = [0; N]; match buf.len() { 0 => { let buf = self.non_empty_reader_buffer_mut()?; if buf.len() < N { return Err(DeserializationError::UnexpectedEOF); } // SAFETY: This copy is guaranteed to be safe, as we have validated above // that `buf` has at least N bytes, and `output` is defined to be exactly // N bytes. unsafe { core::ptr::copy_nonoverlapping(buf.as_ptr(), output.as_mut_ptr(), N); } self.reader.get_mut().consume(N); }, n if n >= N => { // SAFETY: This copy is guaranteed to be safe, as we have validated above // that `buf` has at least N bytes, and `output` is defined to be exactly // N bytes. unsafe { core::ptr::copy_nonoverlapping(buf.as_ptr(), output.as_mut_ptr(), N); } self.pos += N; }, n => { // We have to fill from both the local and reader buffers self.non_empty_reader_buffer_mut()?; let reader_buf = self.reader_buffer(); match reader_buf.len() { #[cfg(debug_assertions)] 0 => unreachable!("expected reader buffer to be non-empty to reach here"), #[cfg(not(debug_assertions))] // SAFETY: The call to `non_empty_reader_buffer_mut` will return an error // if `reader_buffer` is non-empty, as a result is is impossible to reach // here with a length of 0. 0 => unsafe { core::hint::unreachable_unchecked() }, // We got enough in one request m if m + n >= N => { let needed = N - n; let dst = output.as_mut_ptr(); // SAFETY: Both copies are guaranteed to be in-bounds: // // * `output` is defined to be exactly N bytes // * `buf` is guaranteed to be < N bytes // * `reader_buf` is guaranteed to have the remaining bytes needed, // and we only copy exactly that many bytes unsafe { core::ptr::copy_nonoverlapping(self.buffer().as_ptr(), dst, n); core::ptr::copy_nonoverlapping(reader_buf.as_ptr(), dst.add(n), needed); drop(reader_buf); } self.pos += n; self.reader.get_mut().consume(needed); }, // We didn't get enough, but haven't necessarily reached eof yet, so fall back // to filling `self.buf` m => { let needed = N - (m + n); drop(reader_buf); self.buffer_at_least(needed)?; debug_assert!( self.buffer().len() >= N, "expected buffer to be at least {N} bytes after call to buffer_at_least" ); // SAFETY: This is guaranteed to be an in-bounds copy unsafe { core::ptr::copy_nonoverlapping( self.buffer().as_ptr(), output.as_mut_ptr(), N, ); } self.pos += N; return Ok(output); }, } }, } // Check if we should reset our internal buffer if self.buffer().is_empty() && self.pos > 0 { unsafe { self.buf.set_len(0); } } Ok(output) } /// Fill `self.buf` with `count` bytes /// /// This should only be called when we can't read from the reader directly fn buffer_at_least(&mut self, mut count: usize) -> Result<(), DeserializationError> { // Read until we have at least `count` bytes, or until we reach end-of-file, // which ever comes first. loop { // If we have successfully read `count` bytes, we're done if count == 0 || self.buffer().len() >= count { break Ok(()); } // This operation will return an error if the underlying reader hits EOF self.non_empty_reader_buffer_mut()?; // Extend `self.buf` with the bytes read from the underlying reader. // // NOTE: We have to re-borrow the reader buffer here, since we can't get a mutable // reference to `self.buf` while holding an immutable reference to the reader buffer. let reader = self.reader.get_mut(); let buf = reader.buffer(); let consumed = buf.len(); self.buf.extend_from_slice(buf); reader.consume(consumed); count = count.saturating_sub(consumed); } } } #[cfg(feature = "std")] impl ByteReader for ReadAdapter<'_> { #[inline(always)] fn read_u8(&mut self) -> Result<u8, DeserializationError> { self.pop() } /// NOTE: If we happen to not have any bytes buffered yet when this is called, then we will be /// forced to try and read from the underlying reader. This requires a mutable reference, which /// is obtained dynamically via [RefCell]. /// /// <div class="warning"> /// Callers must ensure that they do not hold any immutable references to the buffer of this /// reader when calling this function so as to avoid a situation in which the dynamic borrow /// check fails. Specifically, you must not be holding a reference to the result of /// [Self::read_slice] when this function is called. /// </div> fn peek_u8(&self) -> Result<u8, DeserializationError> { if let Some(byte) = self.buffer().first() { return Ok(*byte); } self.non_empty_reader_buffer().map(|b| b[0]) } fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> { // Edge case if len == 0 { return Ok(&[]); } // If we have unused buffer, and the consumed portion is // large enough, we will move the unused portion of the buffer // to the start, freeing up bytes at the end for more reads // before forcing a reallocation let should_optimize_storage = self.pos >= 16 && !self.has_remaining_capacity(len); if should_optimize_storage { // We're going to optimize storage first let buf = self.buffer(); let src = buf.as_ptr(); let count = buf.len(); let dst = self.buf.as_mut_ptr(); unsafe { core::ptr::copy(src, dst, count); self.buf.set_len(count); self.pos = 0; } } // Fill the buffer so we have at least `len` bytes available, // this will return an error if we hit EOF first self.buffer_at_least(len)?; let slice = &self.buf[self.pos..(self.pos + len)]; self.pos += len; Ok(slice) } #[inline] fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> { if N == 0 { return Ok([0; N]); } self.read_exact() } fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> { // Do we have sufficient data in the local buffer? let buffer_len = self.buffer().len(); if buffer_len >= num_bytes { return Ok(()); } // What about if we include what is in the local buffer and the reader's buffer? let reader_buffer_len = self.non_empty_reader_buffer().map(|b| b.len())?; let buffer_len = buffer_len + reader_buffer_len; if buffer_len >= num_bytes { return Ok(()); } // We have no more input, thus can't fulfill a request of `num_bytes` if self.guaranteed_eof { return Err(DeserializationError::UnexpectedEOF); } // Because this function is read-only, we must optimistically assume we can read `num_bytes` // from the input, and fail later if that does not hold. We know we're not at EOF yet, but // that's all we can say without buffering more from the reader. We could make use of // `buffer_at_least`, which would guarantee a correct result, but it would also impose // additional restrictions on the use of this function, e.g. not using it while holding a // reference returned from `read_slice`. Since it is not a memory safety violation to return // an optimistic result here, it makes for a better tradeoff. Ok(()) } #[inline] fn has_more_bytes(&self) -> bool { !self.buffer().is_empty() || self.non_empty_reader_buffer().is_ok() } } // CURSOR // ================================================================================================ #[cfg(feature = "std")] macro_rules! cursor_remaining_buf { ($cursor:ident) => {{ let buf = $cursor.get_ref().as_ref(); let start = $cursor.position().min(buf.len() as u64) as usize; &buf[start..] }}; } #[cfg(feature = "std")] impl<T: AsRef<[u8]>> ByteReader for std::io::Cursor<T> { fn read_u8(&mut self) -> Result<u8, DeserializationError> { let buf = cursor_remaining_buf!(self); if buf.is_empty() { Err(DeserializationError::UnexpectedEOF) } else { let byte = buf[0]; self.set_position(self.position() + 1); Ok(byte) } } fn peek_u8(&self) -> Result<u8, DeserializationError> { cursor_remaining_buf!(self) .first() .copied() .ok_or(DeserializationError::UnexpectedEOF) } fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> { let pos = self.position(); let size = self.get_ref().as_ref().len() as u64; if size.saturating_sub(pos) < len as u64 { Err(DeserializationError::UnexpectedEOF) } else { self.set_position(pos + len as u64); let start = pos.min(size) as usize; Ok(&self.get_ref().as_ref()[start..(start + len)]) } } fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> { self.read_slice(N).map(|bytes| { let mut result = [0u8; N]; result.copy_from_slice(bytes); result }) } fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> { if cursor_remaining_buf!(self).len() >= num_bytes { Ok(()) } else { Err(DeserializationError::UnexpectedEOF) } } #[inline] fn has_more_bytes(&self) -> bool { let pos = self.position(); let size = self.get_ref().as_ref().len() as u64; pos < size } } // SLICE READER // ================================================================================================ /// Implements [ByteReader] trait for a slice of bytes. /// /// NOTE: If you are building with the `std` feature, you should probably prefer [std::io::Cursor] /// instead. However, [SliceReader] is still useful in no-std environments until stabilization of /// the `core_io_borrowed_buf` feature. pub struct SliceReader<'a> { source: &'a [u8], pos: usize, } impl<'a> SliceReader<'a> { /// Creates a new slice reader from the specified slice. pub fn new(source: &'a [u8]) -> Self { SliceReader { source, pos: 0 } } } impl ByteReader for SliceReader<'_> { fn read_u8(&mut self) -> Result<u8, DeserializationError> { self.check_eor(1)?; let result = self.source[self.pos]; self.pos += 1; Ok(result) } fn peek_u8(&self) -> Result<u8, DeserializationError> { self.check_eor(1)?; Ok(self.source[self.pos]) } fn read_slice(&mut self, len: usize) -> Result<&[u8], DeserializationError> { self.check_eor(len)?; let result = &self.source[self.pos..self.pos + len]; self.pos += len; Ok(result) } fn read_array<const N: usize>(&mut self) -> Result<[u8; N], DeserializationError> { self.check_eor(N)?; let mut result = [0_u8; N]; result.copy_from_slice(&self.source[self.pos..self.pos + N]); self.pos += N; Ok(result) } fn check_eor(&self, num_bytes: usize) -> Result<(), DeserializationError> { if self.pos + num_bytes > self.source.len() { return Err(DeserializationError::UnexpectedEOF); } Ok(()) } fn has_more_bytes(&self) -> bool { self.pos < self.source.len() } } #[cfg(all(test, feature = "std"))] mod tests { use std::io::Cursor; use super::*; use crate::ByteWriter; #[test] fn read_adapter_empty() -> Result<(), DeserializationError> { let mut reader = std::io::empty(); let mut adapter = ReadAdapter::new(&mut reader); assert!(!adapter.has_more_bytes()); assert_eq!(adapter.check_eor(8), Err(DeserializationError::UnexpectedEOF)); assert_eq!(adapter.peek_u8(), Err(DeserializationError::UnexpectedEOF)); assert_eq!(adapter.read_u8(), Err(DeserializationError::UnexpectedEOF)); assert_eq!(adapter.read_slice(0), Ok([].as_slice())); assert_eq!(adapter.read_slice(1), Err(DeserializationError::UnexpectedEOF)); assert_eq!(adapter.read_array(), Ok([])); assert_eq!(adapter.read_array::<1>(), Err(DeserializationError::UnexpectedEOF)); Ok(()) } #[test] fn read_adapter_passthrough() -> Result<(), DeserializationError> { let mut reader = std::io::repeat(0b101); let mut adapter = ReadAdapter::new(&mut reader); assert!(adapter.has_more_bytes()); assert_eq!(adapter.check_eor(8), Ok(())); assert_eq!(adapter.peek_u8(), Ok(0b101)); assert_eq!(adapter.read_u8(), Ok(0b101)); assert_eq!(adapter.read_slice(0), Ok([].as_slice())); assert_eq!(adapter.read_slice(4), Ok([0b101, 0b101, 0b101, 0b101].as_slice())); assert_eq!(adapter.read_array(), Ok([])); assert_eq!(adapter.read_array(), Ok([0b101, 0b101])); Ok(()) } #[test] fn read_adapter_exact() { const VALUE: usize = 2048; let mut reader = Cursor::new(VALUE.to_le_bytes()); let mut adapter = ReadAdapter::new(&mut reader); assert_eq!(usize::from_le_bytes(adapter.read_array().unwrap()), VALUE); assert!(!adapter.has_more_bytes()); assert_eq!(adapter.peek_u8(), Err(DeserializationError::UnexpectedEOF)); assert_eq!(adapter.read_u8(), Err(DeserializationError::UnexpectedEOF)); } #[test] fn read_adapter_roundtrip() { const VALUE: usize = 2048; // Write VALUE to storage let mut cursor = Cursor::new([0; core::mem::size_of::<usize>()]); cursor.write_usize(VALUE); // Read VALUE from storage cursor.set_position(0); let mut adapter = ReadAdapter::new(&mut cursor); assert_eq!(adapter.read_usize(), Ok(VALUE)); } #[test] fn read_adapter_for_file() { use std::fs::File; use crate::ByteWriter; let path = std::env::temp_dir().join("read_adapter_for_file.bin"); // Encode some data to a buffer, then write that buffer to a file { let mut buf = Vec::<u8>::with_capacity(256); buf.write_bytes(b"MAGIC\0"); buf.write_bool(true); buf.write_u32(0xbeef); buf.write_usize(0xfeed); buf.write_u16(0x5); std::fs::write(&path, &buf).unwrap(); } // Open the file, and try to decode the encoded items let mut file = File::open(&path).unwrap(); let mut reader = ReadAdapter::new(&mut file); assert_eq!(reader.peek_u8().unwrap(), b'M'); assert_eq!(reader.read_slice(6).unwrap(), b"MAGIC\0"); assert!(reader.read_bool().unwrap()); assert_eq!(reader.read_u32().unwrap(), 0xbeef); assert_eq!(reader.read_usize().unwrap(), 0xfeed); assert_eq!(reader.read_u16().unwrap(), 0x5); assert!(!reader.has_more_bytes(), "expected there to be no more data in the input"); } #[test] fn read_adapter_issue_383() { const STR_BYTES: &[u8] = b"just a string"; use std::fs::File; use crate::ByteWriter; let path = std::env::temp_dir().join("issue_383.bin"); // Encode some data to a buffer, then write that buffer to a file { let mut buf = vec![0u8; 1024]; unsafe { buf.set_len(0); } buf.write_u128(2 * u64::MAX as u128); unsafe { buf.set_len(512); } buf.write_bytes(STR_BYTES); buf.write_u32(0xbeef); std::fs::write(&path, &buf).unwrap(); } // Open the file, and try to decode the encoded items let mut file = File::open(&path).unwrap(); let mut reader = ReadAdapter::new(&mut file); assert_eq!(reader.read_u128().unwrap(), 2 * u64::MAX as u128); assert_eq!(reader.buf.len(), 0); assert_eq!(reader.pos, 0); // Read to offset 512 (we're 16 bytes into the underlying file, i.e. offset of 496) reader.read_slice(496).unwrap(); assert_eq!(reader.buf.len(), 496); assert_eq!(reader.pos, 496); // The byte string is 13 bytes, followed by 4 bytes containing the trailing u32 value. // We expect that the underlying reader will buffer the remaining bytes of the file when // reading STR_BYTES, so the total size of our adapter's buffer should be // 496 + STR_BYTES.len() + size_of::<u32>(); assert_eq!(reader.read_slice(STR_BYTES.len()).unwrap(), STR_BYTES); assert_eq!(reader.buf.len(), 496 + STR_BYTES.len() + core::mem::size_of::<u32>()); // We haven't read the u32 yet assert_eq!(reader.pos, 509); assert_eq!(reader.read_u32().unwrap(), 0xbeef); // Now we have assert_eq!(reader.pos, 513); assert!(!reader.has_more_bytes(), "expected there to be no more data in the input"); } }
rust
Apache-2.0
b30552ecceb5f70565cc0267fca227f30c5af7ab
2026-01-04T20:24:48.363198Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/mylib.rs
activities/src/mylib.rs
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a31.rs
activities/src/bin/a31.rs
// Topic: Trait Objects // // Summary: // A contractor wants a program that can sum the cost of materials based // on how many square meters are required for a job. // // Requirements: // * Calculate multiple material types with different costs // * Must be able to process a list of varying materials // * Material types and cost includes: // * Carpet - $10 per square meter // * Tile - $15 per square meter // * Wood - $20 per square meter // * Square meters must be taken into account // // Notes: // * Create a trait that can be used to retrieve the cost of a material // * Create trait objects and store them in a vector for processing // * Use a function to calculate the total cost // * Process at least 3 different materials fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-basic-match.rs
activities/src/bin/demo-basic-match.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a42.rs
activities/src/bin/a42.rs
// Topic: Implementing Iterator // // Summary: // A game uses a scoring system that includes a score multiplier. // The multiplier starts at 1 and increases by 1 each iteration. // The amount the multiplier increases each iteration can be // adjusted through in-game powerups. // // Example multiplier progression: // 1, 2, 3, (+1 powerup obtained), 5, 7, 9, ... // // Requirements: // * Write a program that uses an iterator to generate a score multiplier // * The iterator must start at 1 and increase by 1 each iteration // * It must be possible to increase the per-iteration amount through powerups // // Notes: // * Use the .next() method to advance the iterator to confirm it works correctly // * Only the Iterator trait needs to be implemented for this activity fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a29.rs
activities/src/bin/a29.rs
// Topic: Generics & Functions // // Requirements: // * Create a function that accepts the Priority trait as a generic parameter // * The function should print out the guest and their priority // * Use the function with at least two different guests // // Notes: // * Use the debug token "{:?}" to print out the information // * Use the compiler to guide you to the correct generic constraints needed #[derive(Debug)] enum ServicePriority { High, Standard, } trait Priority { fn get_priority(&self) -> ServicePriority; } #[derive(Debug)] struct ImportantGuest; impl Priority for ImportantGuest { fn get_priority(&self) -> ServicePriority { ServicePriority::High } } #[derive(Debug)] struct Guest; impl Priority for Guest { fn get_priority(&self) -> ServicePriority { ServicePriority::Standard } } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a23.rs
activities/src/bin/a23.rs
// Topic: Option combinators // // Requirements: // * Use combinators as described in the functions: // part_1, part_2, and part_3 // // Notes: // * Run `cargo test --bin a23` to check your program. // * Only edit the part_1, part_2, and part_3 functions. fn part_1() -> bool { // We are checking whether or not this particular user // has an access level. The "admin" user does have // an access level. // Note: Use is_some or is_none. maybe_access("admin") } fn part_2() -> Option<Access> { // "Root" is equivalent to Access::Admin, but it is // not listed in the maybe_access function. // Note: Use or_else and root(). maybe_access("root") } fn part_3() -> Access { // "Alice" is not a listed user, so she will be a guest. // Note: Use unwrap_or_else. maybe_access("Alice") } #[derive(Debug, Eq, PartialEq)] enum Access { Admin, User, Guest, } fn maybe_access(name: &str) -> Option<Access> { match name { "admin" => Some(Access::Admin), "gary" => Some(Access::User), _ => None, } } fn root() -> Option<Access> { Some(Access::Admin) } fn main() {} #[cfg(test)] mod test { use crate::*; #[test] fn check_part_1() { assert_eq!(part_1(), true, "Admins have an access level"); } #[test] fn check_part_2() { assert_eq!( part_2(), Some(Access::Admin), "Root users have Admin access" ); } #[test] fn check_part_3() { assert_eq!(part_3(), Access::Guest, "Alice is a guest"); } }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-macro-impl-blocks.rs
activities/src/bin/demo-macro-impl-blocks.rs
#[derive(Clone, Copy)] struct Volume(usize); trait ReagentContainer { fn max_volume(&self) -> Volume; fn current_volume(&self) -> Volume; } struct TallFlask { current_volume: Volume, } struct TestTube { current_volume: Volume, } struct Pipette { current_volume: Volume, } struct OtherTube { current_volume: Volume, max_volume: Volume, } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-trait-objects.rs
activities/src/bin/demo-trait-objects.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-structs.rs
activities/src/bin/demo-structs.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a41.rs
activities/src/bin/a41.rs
// Topic: Arc, Mutex, and Threads // // Summary: // Modify the existing multi-threaded program to include a global // counter shared among the threads. The counter should increase // by 1 whenever a worker completes a job. // // Requirements: // * The total number of jobs completed must be displayed // at the end of the program. // * Use Arc & Mutex to share the total count among threads. // * Arc is in the standard library // * Mutex is in the parking_lot crate // // Notes: // * Ensure following crates are added to your Cargo.toml file: // - crossbeam-channel // - parking_lot use crossbeam_channel::{unbounded, Receiver, Sender}; use std::collections::VecDeque; use std::thread::{self, JoinHandle}; use std::time::Duration; /// Job given to workers. #[derive(Clone)] enum Job { Print(String), Sum(isize, isize), } /// Message sent to workers. #[derive(Clone)] enum Message { AddJob(Job), Quit, } struct Worker<M> { tx: Sender<M>, _rx: Receiver<M>, handle: JoinHandle<()>, } impl Worker<Message> { fn add_job(&self, job: Job) { self.tx .send(Message::AddJob(job)) .expect("failed to add job"); } fn join(self) { self.handle.join().expect("failed to join thread"); } fn send_msg(&self, msg: Message) { self.tx.send(msg).expect("failed to send message"); } } /// Create a new worker to receive jobs. fn spawn_worker() -> Worker<Message> { let (tx, rx) = unbounded(); // We clone the receiving end here so we have a copy to give to the // thread. This allows us to save the `tx` and `rx` into the Worker struct. let rx_thread = rx.clone(); // Spawn a new thread. let handle = thread::spawn(move || { // VecDeque allows us to get jobs in the order they arrive. let mut jobs = VecDeque::new(); // Outer loop is so we can have a brief delay when no // jobs are available. loop { // Inner loop continuously processes jobs until // no more are available. loop { // Get the next job. for job in jobs.pop_front() { match job { Job::Print(msg) => println!("{}", msg), Job::Sum(lhs, rhs) => println!("{}+{}={}", lhs, rhs, lhs + rhs), } } // Check for messages on the channel. if let Ok(msg) = rx_thread.try_recv() { match msg { Message::AddJob(job) => { // When we receive a new job, add it // to the jobs list. jobs.push_back(job); // Continue processing jobs. continue; } Message::Quit => return, } } else { // No messages on the channel, break from inner loop // and thread will wait momentarily for more messages. break; } } // Pause to wait for more messages to arrive on channel. thread::sleep(Duration::from_millis(100)); } }); Worker { tx, _rx: rx, handle, } } fn main() { let jobs = vec![ Job::Print("hello".to_owned()), Job::Sum(2, 2), Job::Print("world".to_owned()), Job::Sum(4, 4), Job::Print("two words".to_owned()), Job::Sum(1, 1), Job::Print("a print job".to_owned()), Job::Sum(10, 10), Job::Print("message".to_owned()), Job::Sum(3, 4), Job::Print("thread".to_owned()), Job::Sum(9, 8), Job::Print("rust".to_owned()), Job::Sum(1, 2), Job::Print("compiler".to_owned()), Job::Sum(9, 1), ]; let jobs_sent = jobs.len(); let mut workers = vec![]; // Spawn 4 workers to process jobs. for _ in 0..4 { let worker = spawn_worker(); workers.push(worker); } // Create an iterator that cycles through each worker endlessly. let mut worker_ring = workers.iter().cycle(); for job in jobs.into_iter() { // Get next worker let worker = worker_ring.next().expect("failed to get worker"); // Add the job worker.add_job(job); } // Ask all workers to quit. for worker in &workers { worker.send_msg(Message::Quit); } // Wait for workers to terminate. for worker in workers { worker.join(); } println!("Jobs sent: {}", jobs_sent); // print out the number of jobs completed here. }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-lifetimes.rs
activities/src/bin/demo-lifetimes.rs
#[derive(Debug)] struct Cards { inner: Vec<IdCard>, } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] enum City { Barland, Bazopolis, Fooville, } #[derive(Debug)] struct IdCard { name: String, age: u8, city: City, } impl IdCard { pub fn new(name: &str, age: u8, city: City) -> Self { Self { name: name.to_string(), age, city, } } } fn new_ids() -> Cards { Cards { inner: vec![ IdCard::new("Amy", 1, City::Fooville), IdCard::new("Matt", 10, City::Barland), IdCard::new("Bailee", 20, City::Barland), IdCard::new("Anthony", 30, City::Bazopolis), IdCard::new("Tina", 40, City::Bazopolis), ], } } fn main() { let ids = new_ids(); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a26c.rs
activities/src/bin/a26c.rs
// Topic: External Modules // // Summary: // The existing program is complete, but all the code exists // in a single module. This code can benefit from being organized // into multiple external modules. // // Requirements: // * Organize the code into two external modules based on their functionality: // - msg: string formatting functions // - math: math functions // * Update the main function to use the functionality from the modules // // Notes: // * Update your Cargo.toml to include a library file // * After moving the functions into modules, try running // `cargo check --bin a26c` to get a listing of required code changes fn trim(msg: &str) -> &str { msg.trim() } fn capitalize(msg: &str) -> std::borrow::Cow<'_, str> { if let Some(letter) = msg.get(0..1) { format!("{}{}", letter.to_uppercase(), &msg[1..msg.len()]).into() } else { msg.into() } } fn exciting(msg: &str) -> String { format!("{}!", msg) } fn add(lhs: isize, rhs: isize) -> isize { lhs + rhs } fn sub(lhs: isize, rhs: isize) -> isize { lhs - rhs } fn mul(lhs: isize, rhs: isize) -> isize { lhs * rhs } fn main() { // Part 1: math functions let result = { let two_plus_two = add(2, 2); let three = sub(two_plus_two, 1); mul(three, three) }; // Ensure we have a correct result. assert_eq!(result, 9); println!("(2 + 2 - 1) * 3 = {}", result); // Part 2: string functions let hello = { let msg = "hello "; let msg = trim(msg); capitalize(msg) }; let world = { let msg = "world"; exciting(msg) }; let msg = format!("{}, {}", hello, world); // Ensure we have a correct result. assert_eq!(&msg, "Hello, world!"); println!("{}", msg); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-strings.rs
activities/src/bin/demo-strings.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-blanket-impl.rs
activities/src/bin/demo-blanket-impl.rs
trait IdentifyUser { // return user id to identify them fn get_user_id(&self) -> u32; } struct User { user_id: u32, } impl IdentifyUser for User { fn get_user_id(&self) -> u32 { self.user_id } } fn main() { let user = User { user_id: 42 }; // using the `get_user_id` method from the `IdentifyUser` trait println!("User ID: {}", user.get_user_id()); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-tuples.rs
activities/src/bin/demo-tuples.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-ranges.rs
activities/src/bin/demo-ranges.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-macro-checked-config.rs
activities/src/bin/demo-macro-checked-config.rs
use std::collections::HashMap; #[derive(Debug)] struct ConfigSection<'a> { name: &'a str, data: HashMap<&'a str, String>, } impl<'a> ConfigSection<'a> { pub fn insert(&mut self, key: &'a str, value: String) { self.data.insert(key, value); } } #[derive(Debug)] struct Configuration<'a> { sections: HashMap<&'a str, ConfigSection<'a>>, } impl<'a> Configuration<'a> { pub fn new() -> Self { Self { sections: HashMap::new(), } } pub fn get_section(&self, name: &str) -> Option<&ConfigSection<'a>> { self.sections.get(name) } pub fn add_section(&mut self, name: &'a str) { let section = ConfigSection { name, data: HashMap::new(), }; self.sections.insert(name, section); } pub fn insert(&mut self, section_name: &'a str, key: &'a str, value: String) { let section = self.sections.entry(section_name).or_insert(ConfigSection { name: section_name, data: HashMap::new(), }); section.insert(key, value); } } fn add(lhs: usize, rhs: usize) -> usize { lhs + rhs } fn main() { let mut config = Configuration::new(); // [section] // key=value; // key2=value2; // [next_section] // a=b; }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/m4.rs
activities/src/bin/m4.rs
// Topic: Basic syntax extension macro // // Summary: // Create a syntax extension macro that allows selecting items out of an iterator // using human-readable terms. // // Requirements: // * Implement the remaining macro_rules matchers using the formats shown in the main function. // * The type returned by the macro must match the annotations in the main function. // // Notes: // * One matcher for the macro is provided & can be used as a guide. // * Run `cargo test --bin m4` to check your work. macro_rules! get { // first k items from iterable (first $count:literal items from $iterable:expr) => { $iterable.iter().take($count) }; } fn main() { let data = vec![1, 2, 3, 4, 5]; let first_3: Vec<&i32> = get!(first 3 items from data).collect::<Vec<_>>(); let last_3: Vec<&i32> = get!(last 3 items from data).collect::<Vec<_>>(); let first_item: Option<&i32> = get!(first item from data); let last_item: Option<&i32> = get!(last item from data); } #[cfg(test)] mod test { #[test] fn first_item() { let data = vec![1, 2, 3, 4, 5]; let first = get!(first item from data); assert_eq!(first.unwrap(), &1); } #[test] fn last_item() { let data = vec![1, 2, 3, 4, 5]; let last = get!(last item from data); assert_eq!(last.unwrap(), &5); } #[test] fn first_k_items() { let data = vec![1, 2, 3, 4, 5]; let first: Vec<_> = get!(first 3 items from data).collect(); assert_eq!(first, vec![&1, &2, &3]); } #[test] fn last_k_items() { let data = vec![1, 2, 3, 4, 5]; let last: Vec<_> = get!(last 3 items from data).collect(); assert_eq!(last, vec![&3, &4, &5]); } }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/mc-02.rs
activities/src/bin/mc-02.rs
// Topic: Delegating functionality // // Summary: // The below program is used as part of an inventory management system that tracks the total // quantity of available items. The business would like a notification to be sent when the // inventory of an item gets low. // // Requirements: // - Create a proxy structure named `InventoryAlerter` around `BasicInventory` that prints a // message whenever the quantity of an item reaches or falls below a set threshold. // - The threshold should be specified per-item // - The default threshold is 50 items. // - The message should be `Low quantity of {item}: {amount}` // - Implement a method named `set_alert_threshold` on the `InventoryAlerter` to set // the alert threshold per item // - Update the main function to use the `InventoryAlerter` // - When implemented correctly, you should get 2 alerts: // low quantity of apple: 50 // low quantity of cilantro: 54 use std::collections::HashMap; /// Manages the quantity of an inventory. pub trait InventoryManager { /// Change the quantity of an item. If the item does not exist, it will be added. fn update_quantity<I: Into<String>>(&mut self, item: I, amount: i32); /// Returns the total quantity of an item, if the item was found. fn get_quantity<I: AsRef<str>>(&self, item: I) -> Option<i32>; } /// An in-memory inventory manager backed by a hashmap. #[derive(Debug, Default)] struct BasicInventory { inventory: HashMap<String, i32>, } impl InventoryManager for BasicInventory { fn update_quantity<I: Into<String>>(&mut self, item: I, amount: i32) { let item = item.into(); let entry = self.inventory.entry(item).or_default(); *entry += amount; } fn get_quantity<I: AsRef<str>>(&self, item: I) -> Option<i32> { self.inventory.get(item.as_ref()).copied() } } /*********************************************************************************************** * Do not edit this function. It should work with the structure that you create without having to * make any modifications to the function. ***********************************************************************************************/ fn change_quantity<M, I>(manager: &mut M, item: I, amount: i32) where M: InventoryManager, I: Into<String>, { manager.update_quantity(item, amount); } fn main() { /****************************************************** * Change the below line to create your proxy structure ******************************************************/ let mut inventory = BasicInventory::default(); /*********************************************************************************************** * Do not change anything else in this function. When implemented correctly, you should get 2 * alerts printed to the terminal. **********************************************************************************************/ // should have an alert: at or below default threshold of 50 inventory.update_quantity("apple", 50); // no alert: above default threshold of 50 inventory.update_quantity("tomato", 120); // no alert: above default threshold of 50 inventory.update_quantity("cilantro", 60); // change the threshold for cilantro inventory.set_alert_threshold("cilantro", 55); // should have an alert: 60-6 = 54 cilantro which is below the new threshold of 55 change_quantity(&mut inventory, "cilantro", -6); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a8.rs
activities/src/bin/a8.rs
// Topic: Organizing similar data using structs // // Requirements: // * Print the flavor of a drink and it's fluid ounces // // Notes: // * Use an enum to create different flavors of drinks // * Use a struct to store drink flavor and fluid ounce information // * Use a function to print out the drink flavor and ounces // * Use a match expression to print the drink flavor fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-tdd-maintainable-tests.rs
activities/src/bin/demo-tdd-maintainable-tests.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-expressions.rs
activities/src/bin/demo-expressions.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-ext-trait-1.rs
activities/src/bin/demo-ext-trait-1.rs
fn main() { let number = 4; }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-macro-syntax-extensions.rs
activities/src/bin/demo-macro-syntax-extensions.rs
// iterable[start:end-1] // iterable[1:3] -> items at index 1 and 2 // iterable[k] // iterable[3] -> retrieve item at index 3 // iterable[start:] // iterable[3:] -> skip 3, until the end // iterable[:end-1] // iterable[:5] -> take everything up to (but not including) index 5 fn main() {} #[cfg(test)] mod test { #[test] fn iter_range() { let numbers = vec![1, 2, 3, 4, 5, 6]; // iterable[start:end-1] // iterable[1:3] -> items at index 1 and 2 let new_iter = iterslice!(numbers[1:5]); let expected = vec![2, 3, 4, 5]; for (expect, actual) in new_iter.zip(expected.iter()) { assert_eq!(expect, actual); } } #[test] fn iter_until_n() { let numbers = vec![1, 2, 3, 4, 5, 6]; // iterable[:end-1] // iterable[:5] -> take everything up to (but not including) index 5 let new_iter = iterslice!(numbers[:4]); let expected = vec![1, 2, 3, 4]; for (expect, actual) in new_iter.zip(expected.iter()) { assert_eq!(expect, actual); } } #[test] fn iter_from_n_until_end() { let numbers = vec![1, 2, 3, 4, 5, 6]; // iterable[start:] // iterable[3:] -> skip 3, until the end let new_iter = iterslice!(numbers[2:]); let expected = vec![3, 4, 5, 6]; for (expect, actual) in new_iter.zip(expected.iter()) { assert_eq!(expect, actual); } } #[test] fn get_index() { let numbers = vec![1, 2, 3, 4, 5, 6]; // iterable[k] // iterable[3] -> retrieve item at index 3 let value = iterslice!(numbers[4]); let expected = &5; assert_eq!(expected, value); } }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a1.rs
activities/src/bin/a1.rs
// Topic: Functions // // Program requirements: // * Displays your first and last name // // Notes: // * Use a function to display your first name // * Use a function to display your last name // * Use the println macro to display messages to the terminal fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a20.rs
activities/src/bin/a20.rs
// Topic: User input // // Requirements: // * Verify user input against pre-defined keywords // * The keywords represent possible power options for a computer: // * Off // * Sleep // * Reboot // * Shutdown // * Hibernate // * If the user enters one of the keywords, a message should be printed to // the console indicating which action will be taken // * Example: If the user types in "shutdown" a message should display such // as "shutting down" // * If the keyword entered does not exist, an appropriate error message // should be displayed // // Notes: // * Use an enum to store the possible power states // * Use a function with a match expression to print out the power messages // * The function should accept the enum as an input // * Use a match expression to convert the user input into the power state enum // * The program should be case-insensitive (the user should be able to type // Reboot, reboot, REBOOT, etc.) fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a37.rs
activities/src/bin/a37.rs
// Topic: TryFrom/TryInto // // Summary: // * A library is needed for an application to convert hex color codes // into their component color values (red, green, and blue). Hex color codes // consist of a hash symbol followed by six hex digits. Every two hex digits // represent a color component in the order of red, green, blue. // // Example hex color codes: // #ffffff -> Rgb(255, 255, 255) // #001122 -> Rgb(0, 17, 34) // // Requirements: // * Create a program to convert a hex code (as &str) into an Rgb struct // * Implement TryFrom to perform the conversion // * Utilize the question mark operator in your implementation // // Notes: // * See the `from_str_radix` function in the stdlib docs for `u8` // to convert hex digits to `u8` // * Hex digits use a radix value of 16 // * Utilize the `thiserror` crate for your error type // * Run `cargo test --bin a37` to test your implementation #[derive(Debug, Eq, PartialEq)] struct Rgb(u8, u8, u8); fn main() { // Use `cargo test --bin a37` to test your implementation } #[cfg(test)] mod test { use super::Rgb; use std::convert::TryFrom; #[test] fn converts_valid_hex_color() { let expected = Rgb(0, 204, 102); let actual = Rgb::try_from("#00cc66"); assert_eq!( actual.is_ok(), true, "valid hex code should be converted to Rgb" ); assert_eq!(actual.unwrap(), expected, "wrong Rgb value"); } #[test] fn fails_on_invalid_hex_digits() { assert_eq!( Rgb::try_from("#0011yy").is_err(), true, "should be an error with invalid hex color" ); } #[test] fn fails_when_missing_hash() { assert_eq!( Rgb::try_from("001100").is_err(), true, "should be an error when missing hash symbol" ); } #[test] fn fails_when_missing_color_components() { assert_eq!( Rgb::try_from("#0011f").is_err(), true, "should be an error when missing one or more color components" ); } #[test] fn fails_with_too_many_color_components() { assert_eq!( Rgb::try_from("#0011ffa").is_err(), true, "should be an error when too many color components are provided" ); } }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/mc-04.rs
activities/src/bin/mc-04.rs
// Topic: Test-driven development (TDD) // // Summary: // You have been tasked to create a system that records and analyzes readings from a temperature // sensor. Implement the program requirements using TDD. // // Requirements: // - Define a `TemperatureSensor` struct that stores a list of temperature readings (e.g., as a `Vec<f64>`). // - Implement these methods: // - `record_temperature`: adds a new temperature reading to the sensor's list // - `get_average_temperature`: returns the average temperature from the recorded readings // - `get_max_temperature`: returns the highest temperature recorded by the sensor // // Notes: // - When using TDD, use the `red-green-refactor` method: // 1. Red: Write _one_ test and then run it to make sure it fails // 2. Green: Implement the code to make the test pass // 3. Refactor: Clean up your implementation (if needed) and reduce duplication in your test cases // - Feel free to add extra methods as needed (like to check if any temperatures have been recorded) // - Use `cargo test --bin mc-04` to run your tests // - The `.max()` method on iterators won't work for f64. Consider writing a `for` loop and // manually track the highest temperature, or use `.fold` fn main() {} #[cfg(test)] mod tests { use super::*; #[test] fn feature() { todo!() } }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a12.rs
activities/src/bin/a12.rs
// Topic: Implementing functionality with the impl keyword // // Requirements: // * Print the characteristics of a shipping box // * Must include dimensions, weight, and color // // Notes: // * Use a struct to encapsulate the box characteristics // * Use an enum for the box color // * Implement functionality on the box struct to create a new box // * Implement functionality on the box struct to print the characteristics fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a18.rs
activities/src/bin/a18.rs
// Topic: Result // // Requirements: // * Create an structure named `Adult` that represents a person aged 21 or older: // * The structure must contain the person's name and age // * Implement Debug print functionality using `derive` // * Implement a `new` function for the `Adult` structure that returns a Result: // * The Ok variant should contain the initialized structure, but only // if the person is aged 21 or older // * The Err variant should contain a String (or &str) that explains why // the structure could not be created // * Instantiate two `Adult` structures: // * One should be aged under 21 // * One should be 21 or over // * Use `match` to print out a message for each `Adult`: // * For the Ok variant, print any message you want // * For the Err variant, print out the error message fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a26b.rs
activities/src/bin/a26b.rs
// Topic: Inline Modules // // Summary: // The existing program is complete, but all the code exists // in a single module. This code can benefit from being organized // into multiple modules. // // Requirements: // * Organize the code into two modules based on their functionality: // - msg: string formatting functions // - math: math functions // * Update the main function to use the functionality from the modules // // Notes: // * After moving the functions into modules, try running // `cargo check --bin a26b` to get a listing of required code changes fn trim(msg: &str) -> &str { msg.trim() } fn capitalize(msg: &str) -> std::borrow::Cow<'_, str> { if let Some(letter) = msg.get(0..1) { format!("{}{}", letter.to_uppercase(), &msg[1..msg.len()]).into() } else { msg.into() } } fn exciting(msg: &str) -> String { format!("{}!", msg) } fn add(lhs: isize, rhs: isize) -> isize { lhs + rhs } fn sub(lhs: isize, rhs: isize) -> isize { lhs - rhs } fn mul(lhs: isize, rhs: isize) -> isize { lhs * rhs } fn main() { // Part 1: math functions let result = { let two_plus_two = add(2, 2); let three = sub(two_plus_two, 1); mul(three, three) }; // Ensure we have a correct result. assert_eq!(result, 9); println!("(2 + 2 - 1) * 3 = {}", result); // Part 2: string functions let hello = { let msg = "hello "; let msg = trim(msg); capitalize(msg) }; let world = { let msg = "world"; exciting(msg) }; let msg = format!("{}, {}", hello, world); // Ensure we have a correct result. assert_eq!(&msg, "Hello, world!"); println!("{}", msg); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a13.rs
activities/src/bin/a13.rs
// Topic: Vectors // // Requirements: // * Print 10, 20, "thirty", and 40 in a loop // * Print the total number of elements in a vector // // Notes: // * Use a vector to store 4 numbers // * Iterate through the vector using a for..in loop // * Determine whether to print the number or print "thirty" inside the loop // * Use the .len() function to print the number of elements in a vector fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-testing.rs
activities/src/bin/demo-testing.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a32.rs
activities/src/bin/a32.rs
// Topic: Lifetimes & Structures // // Requirements: // * Display just the names and titles of persons from the mock-data.csv file // * The names & titles must be stored in a struct separately from the mock // data for potential later usage // * None of the mock data may be duplicated in memory // // Notes: // * The mock data has already been loaded with the include_str! macro, so all functionality // must be implemented using references/borrows const MOCK_DATA: &'static str = include_str!("mock-data.csv"); fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/mc-03.rs
activities/src/bin/mc-03.rs
// Topic: Extension traits // // Summary: // The following program simulates an account management system where users can deposit and // withdraw money. The goal is to extend basic account operations with additional features using // an extension trait. // // Requirements: // - Create an extension trait named `AccountExt` that adds two methods to the `Account` trait: // - `withdraw`: removes a specified amount from the account. // - `deposit`: adds a specified amount to the account. // - Implement the `AccountExtensions` trait for any type that implements the `Account` trait by // using a blanket implementation. // - Do not change any of the existing code. Only add and implement an extension trait. // // Expected Output: // Adjusted balance by $50.00. New balance: $150.00 // Adjusted balance by -$30.00. New balance: $120.00 // Adjusted balance by $20.00. New balance: $140.00 /********************************************** * Do not change **********************************************/ trait Account { fn adjust(&mut self, amount: f64); } struct BankAccount { balance: f64, } /********************************************** * Do not change **********************************************/ impl BankAccount { fn new(initial_balance: f64) -> Self { BankAccount { balance: initial_balance, } } } /********************************************** * Do not change **********************************************/ impl Account for BankAccount { fn adjust(&mut self, amount: f64) { self.balance += amount; println!( "Adjusted balance by ${:.2}. New balance: ${:.2}", amount, self.balance ); } } /********************************************** * Do not change **********************************************/ fn main() { let mut account = BankAccount::new(100.0); // Using the basic process method to deposit money account.adjust(50.0); // Using the extended withdraw method to withdraw money account.withdraw(30.0); // Using the extended deposit method to deposit money account.deposit(20.0); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/m3.rs
activities/src/bin/m3.rs
// Topic: Basic macro repetitions // // Requirements: // * Create a macro to generate hashmaps. // * The macro must be able to accept multiple key/value pairs. // * Print out the generated hashmap using the `dbg!` macro to ensure it works. fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-option-combinator-pattern.rs
activities/src/bin/demo-option-combinator-pattern.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-tdd-struct.rs
activities/src/bin/demo-tdd-struct.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a27.rs
activities/src/bin/a27.rs
// Topic: Custom error types // // Requirements: // * Modify the `ProgramError` enum in order to make the program compile // and run. Do not modify any other part of the program. // * The output should display a menu error followed by a math error when running. // // Notes: // * Use `#[error("description")]` on the enum variants // * Use `#[from] ErrorType` to convert the existing errors into a `ProgramError` use thiserror::Error; enum ProgramError {} #[derive(Debug, Error)] enum MenuError { #[error("menu item not found")] NotFound, } #[derive(Debug, Error)] enum MathError { #[error("divide by zero error")] DivideByZero, } fn pick_menu(choice: &str) -> Result<i32, MenuError> { match choice { "1" => Ok(1), "2" => Ok(2), "3" => Ok(3), _ => Err(MenuError::NotFound), } } fn divide(a: i32, b: i32) -> Result<i32, MathError> { if b != 0 { Ok(a / b) } else { Err(MathError::DivideByZero) } } fn run(step: i32) -> Result<(), ProgramError> { if step == 1 { pick_menu("4")?; } else if step == 2 { divide(1, 0)?; } Ok(()) } fn main() { println!("{:?}", run(1)); println!("{:?}", run(2)); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-tdd-fn.rs
activities/src/bin/demo-tdd-fn.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a4a.rs
activities/src/bin/a4a.rs
// Topic: Decision making with match // // Program requirements: // * Display "it's true" or "it's false" based on the value of a variable // // Notes: // * Use a variable set to either true or false // * Use a match expression to determine which message to display fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a15.rs
activities/src/bin/a15.rs
// Topic: Advanced match // // Requirements: // * Print out a list of tickets and their information for an event // * Tickets can be Backstage, Vip, and Standard // * Backstage and Vip tickets include the ticket holder's name // * All tickets include the price // // Notes: // * Use an enum for the tickets with data associated with each variant // * Create one of each ticket and place into a vector // * Use a match expression while iterating the vector to print the ticket info fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-result.rs
activities/src/bin/demo-result.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-control-flow-if-else.rs
activities/src/bin/demo-control-flow-if-else.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-proxy-delegate.rs
activities/src/bin/demo-proxy-delegate.rs
pub trait Printer { fn print(&self, msg: String); } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-arc-mutex.rs
activities/src/bin/demo-arc-mutex.rs
use parking_lot::Mutex; use std::sync::Arc; use std::thread; use std::time::Duration; type SharedSignData = Arc<Mutex<String>>; struct DigitalSignBoard { display: SharedSignData, } fn spawn_display_thread(display_data: SharedSignData) { thread::spawn(|| {}); } fn change_data(display_data: SharedSignData, new_data: &str) {} fn main() { let display_data = Arc::new(Mutex::new("initial".to_owned())); spawn_display_thread(Arc::clone(&display_data)); thread::sleep(Duration::from_millis(100)); change_data(Arc::clone(&display_data), "message 1"); thread::sleep(Duration::from_millis(500)); change_data(Arc::clone(&display_data), "another message"); thread::sleep(Duration::from_millis(500)); change_data(Arc::clone(&display_data), "goodbye"); thread::sleep(Duration::from_millis(500)); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a19.rs
activities/src/bin/a19.rs
// Topic: HashMap // // Requirements: // * Print the name and number of items in stock for a furniture store // * If the number of items is 0, print "out of stock" instead of 0 // * The store has: // * 5 Chairs // * 3 Beds // * 2 Tables // * 0 Couches // * Print the total number of items in stock // // Notes: // * Use a HashMap for the furniture store stock fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-vector-basics.rs
activities/src/bin/demo-vector-basics.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a14.rs
activities/src/bin/a14.rs
// Topic: Strings // // Requirements: // * Print out the name and favorite colors of people aged 10 and under // // Notes: // * Use a struct for a persons age, name, and favorite color // * The color and name should be stored as a String // * Create and store at least 3 people in a vector // * Iterate through the vector using a for..in loop // * Use an if expression to determine which person's info should be printed // * The name and colors should be printed using a function fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a11.rs
activities/src/bin/a11.rs
// Topic: Ownership // // Requirements: // * Print out the quantity and id number of a grocery item // // Notes: // * Use a struct for the grocery item // * Use two i32 fields for the quantity and id number // * Create a function to display the quantity, with the struct as a parameter // * Create a function to display the id number, with the struct as a parameter fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/p1.rs
activities/src/bin/p1.rs
// Project 1: Interactive bill manager // // Summary: // Create a command line bills/expenses manager that runs // interactively. This mini project brings together many of // the concepts learn thus far into a single application. // // The user stories/requirements are split into stages. // Fully implement each stage as a complete working program // before making changes for the next stage. Leverage the // compiler by using `cargo check --bin p1` when changing // between stages to help identify adjustments that need // to be made. // // User stories: // * Stage 1: // - I want to add bills, including the name and amount owed. // - I want to view existing bills. // * Stage 2: // - I want to remove bills. // * Stage 3: // - I want to edit existing bills. // - I want to go back if I change my mind. // // Tips: // * Use the loop keyword to create an interactive menu. // * Each menu choice should be it's own function, so you can work on the // the functionality for that menu in isolation. // * A vector is the easiest way to store the bills at stage 1, but a // hashmap will be easier to work with at stages 2 and 3. fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-loop-expression.rs
activities/src/bin/demo-loop-expression.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a35.rs
activities/src/bin/a35.rs
// Topic: Match guards & binding // // Summary: // * A tile-based game requires different logic for different kinds // of tiles. Print different messages depending on the kind of // tile selected. // // Requirements: // * Bricks: // * Colored bricks should print "The brick color is [color]" // * Other bricks should print "[Bricktype] brick" // * Water: // * Pressure levels 10 and over should print "High water pressure!" // * Pressure levels under 10 should print "Water pressure level: [Pressure]" // * Grass, Dirt, and Sand should all print "Ground tile" // * Treasure Chests: // * If the treasure is Gold and the amount is at least 100, print "Lots of gold!" // * Everything else shoud not print any messages // // Notes: // * Use a single match expression utilizing guards to implement the program // * Run the program and print the messages with at least 4 different tiles #[derive(Debug)] enum TreasureItem { Gold, SuperPower, } #[derive(Debug)] struct TreasureChest { content: TreasureItem, amount: usize, } #[derive(Debug)] struct Pressure(u16); #[derive(Debug)] enum BrickStyle { Dungeon, Gray, Red, } #[derive(Debug)] enum Tile { Brick(BrickStyle), Dirt, Grass, Sand, Treasure(TreasureChest), Water(Pressure), Wood, } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-if-let-else.rs
activities/src/bin/demo-if-let-else.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-custom-error-types.rs
activities/src/bin/demo-custom-error-types.rs
use chrono::{DateTime, Duration, Utc}; use thiserror::Error; struct SubwayPass { id: usize, funds: isize, expires: DateTime<Utc>, } fn swipe_card() -> Result<SubwayPass, PassError> { // Err(PassError::ReadError("magstrip failure".to_owned())) Ok(SubwayPass { id: 0, funds: 200, expires: Utc::now() + Duration::weeks(52), }) } fn use_pass(pass: &mut SubwayPass, cost: isize) -> Result<(), PassError> { if Utc::now() > pass.expires { Err(PassError::PassExpired) } else { if pass.funds - cost < 0 { Err(PassError::InsufficientFunds(pass.funds)) } else { pass.funds = pass.funds - cost; Ok(()) } } } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-implementing-default.rs
activities/src/bin/demo-implementing-default.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a22.rs
activities/src/bin/a22.rs
// Topic: Testing // // Requirements: // * Write tests for the existing program to ensure proper functionality. // // Notes: // * Create at least two test cases for each function. // * Use `cargo test` to test the program. // * There are intentional bugs in the program that need to be fixed. // * Check the documentation comments for the functions to // determine how the they should operate. /// Ensures n is >= lower and <= upper. fn clamp(n: i32, lower: i32, upper: i32) -> i32 { if n < lower { lower } else if n > upper { upper } else { n } } /// Divides a and b. fn div(a: i32, b: i32) -> Option<i32> { Some(a / b) } /// Takes two strings and places them immediately one after another. fn concat(first: &str, second: &str) -> String { format!("{} {}", first, second) } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-traits.rs
activities/src/bin/demo-traits.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a33.rs
activities/src/bin/a33.rs
// Topic: Lifetimes & Functions // // Summary: // Create a program that compares which string is longer (highest length). // // Requirements: // * The comparison must be done using a function named `longest` // * No data may be copied (cannot use .to_owned() or .to_string()) // * If both strings are the same length, the first one should be returned fn main() { let short = "hello"; let long = "this is a long message"; println!("{}", longest(short, long)) }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-advanced-match.rs
activities/src/bin/demo-advanced-match.rs
enum Discount { Percent(i32), Flat(i32), } struct Ticket { event: String, price: i32, } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/m2.rs
activities/src/bin/m2.rs
// Topic: Writing implementations with macros // // Summary: // There are multiple id types for this program. Implement the `Deref` trait // for all id structures. // // Requirements: // * Create a macro which can generate an implementation block. // * Use the macro to implement Deref for: // * ContractorId // * EmployeeId // * GuestId // * InvestorId // * ManagerId // * VendorId // // Notes: // * Use the existing `Deref` implementation as a template for your macro. // * Run `cargo check --bin m2` to check your work. A successful check means // the activity is complete. use std::ops::Deref; #[derive(Debug)] struct Id(usize); struct ContractorId(Id); struct EmployeeId(Id); struct GuestId(Id); struct InvestorId(Id); struct ManagerId(Id); struct VendorId(Id); impl Deref for ContractorId { type Target = Id; fn deref(&self) -> &Self::Target { &self.0 } } /// This function can accept any type which can be dereferenced into an Id. fn check_id(id: &Id) { println!("id {:?} ok!", id); } fn main() { // No need to edit the main function. These will be compiler errors until // there is an implementation of `Deref` for the Id types listed as part // of the program requirements. let contractor = ContractorId(Id(1)); let employee = EmployeeId(Id(2)); let guest = GuestId(Id(4)); let investor = InvestorId(Id(3)); let manager = ManagerId(Id(5)); let vendor = VendorId(Id(6)); check_id(&contractor); check_id(&employee); check_id(&guest); check_id(&investor); check_id(&manager); check_id(&vendor); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a9.rs
activities/src/bin/a9.rs
// Topic: Data management using tuples // // Requirements: // * Print whether the y-value of a cartesian coordinate is // greater than 5, less than 5, or equal to 5 // // Notes: // * Use a function that returns a tuple // * Destructure the return value into two variables // * Use an if..else if..else block to determine what to print fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-macro-repetitions.rs
activities/src/bin/demo-macro-repetitions.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-macro-recursive.rs
activities/src/bin/demo-macro-recursive.rs
macro_rules! html { } #[allow(unused_must_use)] fn main() { use std::fmt::Write; let mut data = String::new(); html!(&mut data, html[ head[ title["Demo title"] ] body[ h1["Sample"] p["This is a macro demo"] ] ]); dbg!(data); }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-while-loop.rs
activities/src/bin/demo-while-loop.rs
fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/a40.rs
activities/src/bin/a40.rs
// Topic: Smart Pointers & RefCell // // Summary: // A vehicle rental company wants to access the rentals available // at storefront locations. Create a program that provides access // to storefront rentals from the corporate headquarters. // // Requirements: // * Corporate must be able to access the rentals at a storefront // * Storefronts must be able to rent out vehicles // * Rentals have the following attributes: // - Type of vehicle // - Vehicle Identification Number (VIN) // - Vehicle status: // * Available, Unavailable, Maintenance, Rented // // Notes: // * Use Rc and RefCell to create shared mutable data structures // * Create at least two rentals and ensure that Corporate and StoreFront // can both access the rental information // * Test your program by changing the vehicle status from both a storefront // and from corporate struct Corporate; struct StoreFront; fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/demo-typestate-pattern.rs
activities/src/bin/demo-typestate-pattern.rs
struct Employee<State> { name: String, state: State, } struct Agreement; struct Signature; struct Training; struct FailedTraining { score: u8, } struct OnboardingComplete { score: u8, } impl Employee<Agreement> { fn new(name: &str) -> Self { Self { name: name.to_string(), state: Agreement, } } fn read_agreement(self) -> Employee<Signature> { self.transition(Signature) } } #[rustfmt::skip] impl Employee<Training> { fn train(self, score: u8) -> Result<Employee<OnboardingComplete>, Employee<FailedTraining>> { if score >= 7 { Ok(self.transition(OnboardingComplete { score })) } else { Err(self.transition(FailedTraining { score })) } } } fn main() {}
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false
jayson-lennon/ztm-rust
https://github.com/jayson-lennon/ztm-rust/blob/cb0ac4768346c7270ba3655b32bef022b4803460/activities/src/bin/m1.rs
activities/src/bin/m1.rs
// Topic: Control flow with macros // // Summary: // The existing program has multiple checks to confirm that a user can access // a resource. Refactor the `get_data` function to use a macro to check for // all of the requirements. // // Requirements: // * Create a macro that returns early from a function. // // Notes: // * The macro should check for all existing requirements as indicated in // the `get_data` function. // * Use `cargo test --bin m1` to check your work. use std::error::Error; use std::fmt; struct Resource(String); impl From<Resource> for Vec<u8> { fn from(resource: Resource) -> Vec<u8> { resource.0.as_bytes().into() } } #[derive(Clone, Copy)] struct UserId(usize); #[derive(Debug)] enum ServeError { AccountInactive, NotLoggedIn, Unauthorized, } impl Error for ServeError {} impl fmt::Display for ServeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::AccountInactive => write!(f, "Account not active"), Self::NotLoggedIn => write!(f, "Login required"), Self::Unauthorized => write!(f, "Unauthorized"), } } } fn account_is_active(user: UserId) -> bool { match user.0 { 1 | 2 | 3 => true, _ => false, } } fn is_logged_in(user: UserId) -> bool { match user.0 { 2 | 3 => true, _ => false, } } fn is_authorized(user: UserId) -> bool { match user.0 { 3 => true, _ => false, } } fn get_data<T: Into<Vec<u8>>>(resource: T, user: UserId) -> Result<Vec<u8>, ServeError> { if !account_is_active(user) { return Err(ServeError::AccountInactive); } if !is_logged_in(user) { return Err(ServeError::NotLoggedIn); } if !is_authorized(user) { return Err(ServeError::Unauthorized); } Ok(resource.into()) } fn main() { // Use `cargo test --bin m1` to check your work. } #[cfg(test)] mod test { use super::*; #[test] fn errors_when_user_inactive() { let resource = Resource("Sample".into()); let user = UserId(4); let data = get_data(resource, user); assert!( matches!(data, Err(ServeError::AccountInactive)), "should be an AccountInactive error" ); } #[test] fn errors_when_user_not_logged_in() { let resource = Resource("Sample".into()); let user = UserId(1); let data = get_data(resource, user); assert!( matches!(data, Err(ServeError::NotLoggedIn)), "should be a NotLoggedIn error" ); } #[test] fn errors_when_user_not_authorized() { let resource = Resource("Sample".into()); let user = UserId(2); let data = get_data(resource, user); assert!( matches!(data, Err(ServeError::Unauthorized)), "should be an Unauthorized error" ); } #[test] fn ok_when_all_checks_pass() { let resource = Resource("Sample".into()); let user = UserId(3); let data = get_data(resource, user); assert!(data.is_ok()); } }
rust
MIT
cb0ac4768346c7270ba3655b32bef022b4803460
2026-01-04T20:24:50.396322Z
false