commonware_cryptography/
lib.rs

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