Skip to main content

commonware_cryptography/
lib.rs

1//! Generate keys, sign arbitrary messages, and deterministically verify signatures.
2//!
3//! # Status
4//!
5//! Stability varies by primitive. See [README](https://github.com/commonwarexyz/monorepo#stability) for details.
6
7#![doc(
8    html_logo_url = "https://commonware.xyz/imgs/rustdoc_logo.svg",
9    html_favicon_url = "https://commonware.xyz/favicon.ico"
10)]
11#![cfg_attr(not(any(feature = "std", test)), no_std)]
12
13#[cfg(not(feature = "std"))]
14extern crate alloc;
15
16// Modules containing #[macro_export] macros must use verbose cfg.
17// See rust-lang/rust#52234: macro-expanded macro_export macros cannot be referenced by absolute paths.
18#[cfg(not(any(
19    commonware_stability_GAMMA,
20    commonware_stability_DELTA,
21    commonware_stability_EPSILON,
22    commonware_stability_RESERVED
23)))] // BETA
24pub mod bls12381;
25#[cfg(not(any(
26    commonware_stability_GAMMA,
27    commonware_stability_DELTA,
28    commonware_stability_EPSILON,
29    commonware_stability_RESERVED
30)))] // BETA
31pub mod ed25519;
32#[cfg(not(any(
33    commonware_stability_BETA,
34    commonware_stability_GAMMA,
35    commonware_stability_DELTA,
36    commonware_stability_EPSILON,
37    commonware_stability_RESERVED
38)))] // ALPHA
39pub mod secp256r1;
40
41commonware_macros::stability_scope!(ALPHA {
42    pub mod bloomfilter;
43    pub use crate::bloomfilter::BloomFilter;
44
45    pub mod lthash;
46    pub use crate::lthash::LtHash;
47});
48commonware_macros::stability_scope!(BETA {
49    use commonware_codec::{Encode, ReadExt};
50    use commonware_math::algebra::Random;
51    use commonware_utils::Array;
52    use rand::SeedableRng as _;
53    use rand_chacha::ChaCha20Rng;
54    use rand_core::CryptoRngCore;
55
56    pub mod secret;
57    pub use crate::secret::Secret;
58
59    pub mod certificate;
60    pub mod transcript;
61
62    pub mod sha256;
63    pub use crate::sha256::{CoreSha256, Sha256};
64    pub mod blake3;
65    pub use crate::blake3::{Blake3, CoreBlake3};
66    pub mod crc32;
67    pub use crate::crc32::Crc32;
68
69    #[cfg(feature = "std")]
70    pub mod handshake;
71
72    /// Produces [Signature]s over messages that can be verified with a corresponding [PublicKey].
73    pub trait Signer: Random + Send + Sync + Clone + 'static {
74        /// The type of [Signature] produced by this [Signer].
75        type Signature: Signature;
76
77        /// The corresponding [PublicKey] type.
78        type PublicKey: PublicKey<Signature = Self::Signature>;
79
80        /// Returns the [PublicKey] corresponding to this [Signer].
81        fn public_key(&self) -> Self::PublicKey;
82
83        /// Sign a message with the given namespace.
84        ///
85        /// The message should not be hashed prior to calling this function. If a particular scheme
86        /// requires a payload to be hashed before it is signed, it will be done internally.
87        ///
88        /// A namespace must be used to prevent cross-domain attacks (where a signature can be reused
89        /// in a different context). It must be prepended to the message so that a signature meant for
90        /// one context cannot be used unexpectedly in another (i.e. signing a message on the network
91        /// layer can't accidentally spend funds on the execution layer). See
92        /// [commonware_utils::union_unique] for details.
93        fn sign(&self, namespace: &[u8], msg: &[u8]) -> Self::Signature;
94
95        /// Create a [Signer] from a seed.
96        ///
97        /// # Warning
98        ///
99        /// This function is insecure and should only be used for examples
100        /// and testing.
101        fn from_seed(seed: u64) -> Self {
102            Self::random(&mut ChaCha20Rng::seed_from_u64(seed))
103        }
104    }
105
106    /// A [Signer] that can be serialized/deserialized.
107    pub trait PrivateKey: Signer + Sized + ReadExt + Encode {}
108
109    /// Verifies [Signature]s over messages.
110    pub trait Verifier {
111        /// The type of [Signature] that this verifier can verify.
112        type Signature: Signature;
113
114        /// Verify that a [Signature] is a valid over a given message.
115        ///
116        /// The message should not be hashed prior to calling this function. If a particular
117        /// scheme requires a payload to be hashed before it is signed, it will be done internally.
118        ///
119        /// Because namespace is prepended to message before signing, the namespace provided here must
120        /// match the namespace provided during signing.
121        fn verify(&self, namespace: &[u8], msg: &[u8], sig: &Self::Signature) -> bool;
122    }
123
124    /// A [PublicKey], able to verify [Signature]s.
125    pub trait PublicKey: Verifier + Sized + ReadExt + Encode + PartialEq + Array {}
126
127    /// A [Signature] over a message.
128    pub trait Signature: Sized + Clone + ReadExt + Encode + PartialEq + Array {}
129
130    /// An extension of [Signature] that supports public key recovery.
131    pub trait Recoverable: Signature {
132        /// The type of [PublicKey] that can be recovered from this [Signature].
133        type PublicKey: PublicKey<Signature = Self>;
134
135        /// Recover the [PublicKey] of the signer that created this [Signature] over the given message.
136        ///
137        /// The message should not be hashed prior to calling this function. If a particular
138        /// scheme requires a payload to be hashed before it is signed, it will be done internally.
139        ///
140        /// Like when verifying a signature, the namespace must match what was used during signing exactly.
141        fn recover_signer(&self, namespace: &[u8], msg: &[u8]) -> Option<Self::PublicKey>;
142    }
143
144    /// Verifies whether all [Signature]s are correct or that some [Signature] is incorrect.
145    pub trait BatchVerifier<K: PublicKey> {
146        /// Create a new batch verifier.
147        fn new() -> Self;
148
149        /// Append item to the batch.
150        ///
151        /// The message should not be hashed prior to calling this function. If a particular scheme
152        /// requires a payload to be hashed before it is signed, it will be done internally.
153        ///
154        /// A namespace must be used to prevent replay attacks. It will be prepended to the message so
155        /// that a signature meant for one context cannot be used unexpectedly in another (i.e. signing
156        /// a message on the network layer can't accidentally spend funds on the execution layer). See
157        /// [commonware_utils::union_unique] for details.
158        fn add(
159            &mut self,
160            namespace: &[u8],
161            message: &[u8],
162            public_key: &K,
163            signature: &K::Signature,
164        ) -> bool;
165
166        /// Verify all items added to the batch.
167        ///
168        /// Returns `true` if all items are valid, `false` otherwise.
169        ///
170        /// # Why Randomness?
171        ///
172        /// When performing batch verification, it is often important to add some randomness
173        /// to prevent an attacker from constructing a malicious batch of signatures that pass
174        /// batch verification but are invalid individually. Abstractly, think of this as
175        /// there existing two valid signatures (`c_1` and `c_2`) and an attacker proposing
176        /// (`c_1 + d` and `c_2 - d`).
177        ///
178        /// You can read more about this [here](https://ethresear.ch/t/security-of-bls-batch-verification/10748#the-importance-of-randomness-4).
179        fn verify<R: CryptoRngCore>(self, rng: &mut R) -> bool;
180    }
181
182    /// Specializes the [commonware_utils::Array] trait with the Copy trait for cryptographic digests
183    /// (which should be cheap to clone).
184    ///
185    /// # Warning
186    ///
187    /// This trait requires [`Random::random`], but generating a digest at random is
188    /// typically reserved for testing, and not production use.
189    pub trait Digest: Array + Copy + Random {
190        /// An empty (all-zero) digest.
191        const EMPTY: Self;
192    }
193
194    /// An object that can be uniquely represented as a [Digest].
195    pub trait Digestible: Clone + Sized + Send + Sync + 'static {
196        /// The type of digest produced by this object.
197        type Digest: Digest;
198
199        /// Returns a unique representation of the object as a [Digest].
200        ///
201        /// If many objects with [Digest]s are related (map to some higher-level
202        /// group [Digest]), you should also implement [Committable].
203        fn digest(&self) -> Self::Digest;
204    }
205
206    /// An object that can produce a commitment of itself.
207    pub trait Committable: Clone + Sized + Send + Sync + 'static {
208        /// The type of commitment produced by this object.
209        type Commitment: Digest;
210
211        /// Returns the unique commitment of the object as a [Digest].
212        ///
213        /// For simple objects (like a block), this is often just the digest of the object
214        /// itself. For more complex objects, however, this may represent some root or base
215        /// of a proof structure (where many unique objects map to the same commitment).
216        ///
217        /// # Warning
218        ///
219        /// It must not be possible for two objects with the same [Digest] to map
220        /// to different commitments. Primitives assume there is a one-to-one
221        /// relation between digest and commitment and a one-to-many relation
222        /// between commitment and digest.
223        fn commitment(&self) -> Self::Commitment;
224    }
225
226    pub type DigestOf<H> = <H as Hasher>::Digest;
227
228    /// Interface that commonware crates rely on for hashing.
229    ///
230    /// Hash functions in commonware primitives are not typically hardcoded
231    /// to a specific algorithm (e.g. SHA-256) because different hash functions
232    /// may work better with different cryptographic schemes, may be more efficient
233    /// to use in STARK/SNARK proofs, or provide different levels of security (with some
234    /// performance/size penalty).
235    ///
236    /// This trait is required to implement the `Clone` trait because it is often
237    /// part of a struct that is cloned. In practice, implementations do not actually
238    /// clone the hasher state but users should not rely on this behavior and call `reset`
239    /// after cloning.
240    pub trait Hasher: Default + Clone + Send + Sync + 'static {
241        /// Digest generated by the hasher.
242        type Digest: Digest;
243
244        /// Create a new, empty hasher.
245        fn new() -> Self {
246            Self::default()
247        }
248
249        /// Append message to previously recorded data.
250        fn update(&mut self, message: &[u8]) -> &mut Self;
251
252        /// Hash all recorded data and reset the hasher
253        /// to the initial state.
254        fn finalize(&mut self) -> Self::Digest;
255
256        /// Reset the hasher without generating a hash.
257        ///
258        /// This function does not need to be called after `finalize`.
259        fn reset(&mut self) -> &mut Self;
260
261        /// Hash a single message with a one-time-use hasher.
262        fn hash(message: &[u8]) -> Self::Digest {
263            Self::new().update(message).finalize()
264        }
265    }
266});
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271    use commonware_codec::{DecodeExt, FixedSize};
272    use commonware_utils::test_rng;
273
274    fn test_validate<C: PrivateKey>() {
275        let private_key = C::random(&mut test_rng());
276        let public_key = private_key.public_key();
277        assert!(C::PublicKey::decode(public_key.as_ref()).is_ok());
278    }
279
280    fn test_validate_invalid_public_key<C: Signer>() {
281        let result = C::PublicKey::decode(vec![0; 1024].as_ref());
282        assert!(result.is_err());
283    }
284
285    fn test_sign_and_verify<C: PrivateKey>() {
286        let private_key = C::from_seed(0);
287        let namespace = b"test_namespace";
288        let message = b"test_message";
289        let signature = private_key.sign(namespace, message);
290        let public_key = private_key.public_key();
291        assert!(public_key.verify(namespace, message, &signature));
292    }
293
294    fn test_sign_and_verify_wrong_message<C: PrivateKey>() {
295        let private_key = C::from_seed(0);
296        let namespace = b"test_namespace";
297        let message = b"test_message";
298        let wrong_message = b"wrong_message";
299        let signature = private_key.sign(namespace, message);
300        let public_key = private_key.public_key();
301        assert!(!public_key.verify(namespace, wrong_message, &signature));
302    }
303
304    fn test_sign_and_verify_wrong_namespace<C: PrivateKey>() {
305        let private_key = C::from_seed(0);
306        let namespace = b"test_namespace";
307        let wrong_namespace = b"wrong_namespace";
308        let message = b"test_message";
309        let signature = private_key.sign(namespace, message);
310        let public_key = private_key.public_key();
311        assert!(!public_key.verify(wrong_namespace, message, &signature));
312    }
313
314    fn test_empty_namespace<C: PrivateKey>() {
315        let private_key = C::from_seed(0);
316        let empty_namespace = b"";
317        let message = b"test_message";
318        let signature = private_key.sign(empty_namespace, message);
319        let public_key = private_key.public_key();
320        assert!(public_key.verify(empty_namespace, message, &signature));
321    }
322
323    fn test_signature_determinism<C: PrivateKey>() {
324        let private_key_1 = C::from_seed(0);
325        let private_key_2 = C::from_seed(0);
326        let namespace = b"test_namespace";
327        let message = b"test_message";
328        let signature_1 = private_key_1.sign(namespace, message);
329        let signature_2 = private_key_2.sign(namespace, message);
330        assert_eq!(private_key_1.public_key(), private_key_2.public_key());
331        assert_eq!(signature_1, signature_2);
332    }
333
334    fn test_invalid_signature_publickey_pair<C: PrivateKey>() {
335        let private_key = C::from_seed(0);
336        let private_key_2 = C::from_seed(1);
337        let namespace = b"test_namespace";
338        let message = b"test_message";
339        let signature = private_key.sign(namespace, message);
340        let public_key = private_key_2.public_key();
341        assert!(!public_key.verify(namespace, message, &signature));
342    }
343
344    #[test]
345    fn test_ed25519_validate() {
346        test_validate::<ed25519::PrivateKey>();
347    }
348
349    #[test]
350    fn test_ed25519_validate_invalid_public_key() {
351        test_validate_invalid_public_key::<ed25519::PrivateKey>();
352    }
353
354    #[test]
355    fn test_ed25519_sign_and_verify() {
356        test_sign_and_verify::<ed25519::PrivateKey>();
357    }
358
359    #[test]
360    fn test_ed25519_sign_and_verify_wrong_message() {
361        test_sign_and_verify_wrong_message::<ed25519::PrivateKey>();
362    }
363
364    #[test]
365    fn test_ed25519_sign_and_verify_wrong_namespace() {
366        test_sign_and_verify_wrong_namespace::<ed25519::PrivateKey>();
367    }
368
369    #[test]
370    fn test_ed25519_empty_namespace() {
371        test_empty_namespace::<ed25519::PrivateKey>();
372    }
373
374    #[test]
375    fn test_ed25519_signature_determinism() {
376        test_signature_determinism::<ed25519::PrivateKey>();
377    }
378
379    #[test]
380    fn test_ed25519_invalid_signature_publickey_pair() {
381        test_invalid_signature_publickey_pair::<ed25519::PrivateKey>();
382    }
383
384    #[test]
385    fn test_ed25519_len() {
386        assert_eq!(ed25519::PublicKey::SIZE, 32);
387        assert_eq!(ed25519::Signature::SIZE, 64);
388    }
389
390    #[test]
391    fn test_bls12381_validate() {
392        test_validate::<bls12381::PrivateKey>();
393    }
394
395    #[test]
396    fn test_bls12381_validate_invalid_public_key() {
397        test_validate_invalid_public_key::<bls12381::PrivateKey>();
398    }
399
400    #[test]
401    fn test_bls12381_sign_and_verify() {
402        test_sign_and_verify::<bls12381::PrivateKey>();
403    }
404
405    #[test]
406    fn test_bls12381_sign_and_verify_wrong_message() {
407        test_sign_and_verify_wrong_message::<bls12381::PrivateKey>();
408    }
409
410    #[test]
411    fn test_bls12381_sign_and_verify_wrong_namespace() {
412        test_sign_and_verify_wrong_namespace::<bls12381::PrivateKey>();
413    }
414
415    #[test]
416    fn test_bls12381_empty_namespace() {
417        test_empty_namespace::<bls12381::PrivateKey>();
418    }
419
420    #[test]
421    fn test_bls12381_signature_determinism() {
422        test_signature_determinism::<bls12381::PrivateKey>();
423    }
424
425    #[test]
426    fn test_bls12381_invalid_signature_publickey_pair() {
427        test_invalid_signature_publickey_pair::<bls12381::PrivateKey>();
428    }
429
430    #[test]
431    fn test_bls12381_len() {
432        assert_eq!(bls12381::PublicKey::SIZE, 48);
433        assert_eq!(bls12381::Signature::SIZE, 96);
434    }
435
436    #[test]
437    fn test_secp256r1_standard_validate() {
438        test_validate::<secp256r1::standard::PrivateKey>();
439    }
440
441    #[test]
442    fn test_secp256r1_standard_validate_invalid_public_key() {
443        test_validate_invalid_public_key::<secp256r1::standard::PrivateKey>();
444    }
445
446    #[test]
447    fn test_secp256r1_standard_sign_and_verify() {
448        test_sign_and_verify::<secp256r1::standard::PrivateKey>();
449    }
450
451    #[test]
452    fn test_secp256r1_standard_sign_and_verify_wrong_message() {
453        test_sign_and_verify_wrong_message::<secp256r1::standard::PrivateKey>();
454    }
455
456    #[test]
457    fn test_secp256r1_standard_sign_and_verify_wrong_namespace() {
458        test_sign_and_verify_wrong_namespace::<secp256r1::standard::PrivateKey>();
459    }
460
461    #[test]
462    fn test_secp256r1_standard_empty_namespace() {
463        test_empty_namespace::<secp256r1::standard::PrivateKey>();
464    }
465
466    #[test]
467    fn test_secp256r1_standard_signature_determinism() {
468        test_signature_determinism::<secp256r1::standard::PrivateKey>();
469    }
470
471    #[test]
472    fn test_secp256r1_standard_invalid_signature_publickey_pair() {
473        test_invalid_signature_publickey_pair::<secp256r1::standard::PrivateKey>();
474    }
475
476    #[test]
477    fn test_secp256r1_standard_len() {
478        assert_eq!(secp256r1::standard::PublicKey::SIZE, 33);
479        assert_eq!(secp256r1::standard::Signature::SIZE, 64);
480    }
481
482    #[test]
483    fn test_secp256r1_recoverable_validate() {
484        test_validate::<secp256r1::recoverable::PrivateKey>();
485    }
486
487    #[test]
488    fn test_secp256r1_recoverable_validate_invalid_public_key() {
489        test_validate_invalid_public_key::<secp256r1::recoverable::PrivateKey>();
490    }
491
492    #[test]
493    fn test_secp256r1_recoverable_sign_and_verify() {
494        test_sign_and_verify::<secp256r1::recoverable::PrivateKey>();
495    }
496
497    #[test]
498    fn test_secp256r1_recoverable_sign_and_verify_wrong_message() {
499        test_sign_and_verify_wrong_message::<secp256r1::recoverable::PrivateKey>();
500    }
501
502    #[test]
503    fn test_secp256r1_recoverable_sign_and_verify_wrong_namespace() {
504        test_sign_and_verify_wrong_namespace::<secp256r1::recoverable::PrivateKey>();
505    }
506
507    #[test]
508    fn test_secp256r1_recoverable_empty_namespace() {
509        test_empty_namespace::<secp256r1::recoverable::PrivateKey>();
510    }
511
512    #[test]
513    fn test_secp256r1_recoverable_signature_determinism() {
514        test_signature_determinism::<secp256r1::recoverable::PrivateKey>();
515    }
516
517    #[test]
518    fn test_secp256r1_recoverable_invalid_signature_publickey_pair() {
519        test_invalid_signature_publickey_pair::<secp256r1::recoverable::PrivateKey>();
520    }
521
522    #[test]
523    fn test_secp256r1_recoverable_len() {
524        assert_eq!(secp256r1::recoverable::PublicKey::SIZE, 33);
525        assert_eq!(secp256r1::recoverable::Signature::SIZE, 65);
526    }
527
528    fn test_hasher_multiple_runs<H: Hasher>() {
529        // Generate initial hash
530        let mut hasher = H::new();
531        hasher.update(b"hello world");
532        let digest = hasher.finalize();
533        assert!(H::Digest::decode(digest.as_ref()).is_ok());
534        assert_eq!(digest.as_ref().len(), H::Digest::SIZE);
535
536        // Reuse hasher without reset
537        hasher.update(b"hello world");
538        let digest_again = hasher.finalize();
539        assert!(H::Digest::decode(digest_again.as_ref()).is_ok());
540        assert_eq!(digest, digest_again);
541
542        // Reuse hasher with reset
543        hasher.update(b"hello mars");
544        hasher.reset();
545        hasher.update(b"hello world");
546        let digest_reset = hasher.finalize();
547        assert!(H::Digest::decode(digest_reset.as_ref()).is_ok());
548        assert_eq!(digest, digest_reset);
549
550        // Hash different data
551        hasher.update(b"hello mars");
552        let digest_mars = hasher.finalize();
553        assert!(H::Digest::decode(digest_mars.as_ref()).is_ok());
554        assert_ne!(digest, digest_mars);
555    }
556
557    fn test_hasher_multiple_updates<H: Hasher>() {
558        // Generate initial hash
559        let mut hasher = H::new();
560        hasher.update(b"hello");
561        hasher.update(b" world");
562        let digest = hasher.finalize();
563        assert!(H::Digest::decode(digest.as_ref()).is_ok());
564
565        // Generate hash in oneshot
566        let mut hasher = H::new();
567        hasher.update(b"hello world");
568        let digest_oneshot = hasher.finalize();
569        assert!(H::Digest::decode(digest_oneshot.as_ref()).is_ok());
570        assert_eq!(digest, digest_oneshot);
571    }
572
573    fn test_hasher_empty_input<H: Hasher>() {
574        let mut hasher = H::new();
575        let digest = hasher.finalize();
576        assert!(H::Digest::decode(digest.as_ref()).is_ok());
577    }
578
579    fn test_hasher_large_input<H: Hasher>() {
580        let mut hasher = H::new();
581        let data = vec![1; 1024];
582        hasher.update(&data);
583        let digest = hasher.finalize();
584        assert!(H::Digest::decode(digest.as_ref()).is_ok());
585    }
586
587    #[test]
588    fn test_sha256_hasher_multiple_runs() {
589        test_hasher_multiple_runs::<Sha256>();
590    }
591
592    #[test]
593    fn test_sha256_hasher_multiple_updates() {
594        test_hasher_multiple_updates::<Sha256>();
595    }
596
597    #[test]
598    fn test_sha256_hasher_empty_input() {
599        test_hasher_empty_input::<Sha256>();
600    }
601
602    #[test]
603    fn test_sha256_hasher_large_input() {
604        test_hasher_large_input::<Sha256>();
605    }
606}