commonware_cryptography/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Generate keys, sign arbitrary messages, and deterministically verify signatures.
//!
//! # Status
//!
//! `commonware-cryptography` is **ALPHA** software and is not yet recommended for production use. Developers should
//! expect breaking changes and occasional instability.

use bytes::Buf;
use commonware_utils::SizedSerialize;
use rand::{CryptoRng, Rng, RngCore, SeedableRng};
use std::fmt::Display;
use std::{fmt::Debug, hash::Hash, ops::Deref};
use thiserror::Error;

pub mod bls12381;
pub use bls12381::Bls12381;
pub mod ed25519;
pub use ed25519::{Ed25519, Ed25519Batch};
pub mod sha256;
pub use sha256::{hash, Sha256};
pub mod secp256r1;
pub use secp256r1::Secp256r1;

/// Errors that can occur when interacting with cryptographic primitives.
#[derive(Error, Debug, PartialEq)]
pub enum Error {
    #[error("invalid digest length")]
    InvalidDigestLength,
    #[error("invalid private key")]
    InvalidPrivateKey,
    #[error("invalid private key length")]
    InvalidPrivateKeyLength,
    #[error("invalid public key")]
    InvalidPublicKey,
    #[error("invalid public key length")]
    InvalidPublicKeyLength,
    #[error("invalid signature")]
    InvalidSignature,
    #[error("invalid signature length")]
    InvalidSignatureLength,
    #[error("invalid bytes")]
    InsufficientBytes,
}

/// Types that can be fallibly read from a fixed-size byte sequence.
///
/// `Array` is typically used to parse things like `PublicKeys` and `Signatures`
/// from an untrusted network connection. Once parsed, these types are assumed
/// to be well-formed (which prevents duplicate validation).
///
/// If a byte sequencer is not properly formatted, `TryFrom` must return an error.
pub trait Array:
    Clone
    + Send
    + Sync
    + 'static
    + Eq
    + PartialEq
    + Ord
    + PartialOrd
    + Debug
    + Hash
    + Display
    + AsRef<[u8]>
    + Deref<Target = [u8]>
    + for<'a> TryFrom<&'a [u8], Error = Error>
    + for<'a> TryFrom<&'a Vec<u8>, Error = Error>
    + TryFrom<Vec<u8>, Error = Error>
    + SizedSerialize
{
    /// Attempts to read an array from the provided buffer.
    fn read_from<B: Buf>(buf: &mut B) -> Result<Self, Error> {
        // Check if there are enough bytes in the buffer to read a digest.
        let len = Self::SERIALIZED_LEN;
        if buf.remaining() < len {
            return Err(Error::InsufficientBytes);
        }

        // If there are enough contiguous bytes in the buffer, use them directly.
        let chunk = buf.chunk();
        if chunk.len() >= len {
            let array = Self::try_from(&chunk[..len])?;
            buf.advance(len);
            return Ok(array);
        }

        // Otherwise, copy the bytes into a temporary buffer.
        let mut temp = vec![0u8; len];
        buf.copy_to_slice(&mut temp);
        Self::try_from(temp)
    }
}

/// Interface that commonware crates rely on for most cryptographic operations.
pub trait Scheme: Clone + Send + Sync + 'static {
    /// Private key used for signing.
    type PrivateKey: Array;

    /// Public key used for verifying signatures.
    type PublicKey: Array;

    /// Signature generated by signing a message.
    type Signature: Array;

    /// Returns a new instance of the scheme.
    fn new<R: Rng + CryptoRng>(rng: &mut R) -> Self;

    /// Returns a new instance of the scheme from a secret key.
    fn from(private_key: Self::PrivateKey) -> Option<Self>;

    /// Returns a new instance of the scheme from a provided seed.
    ///
    /// # Warning
    ///
    /// This function is insecure and should only be used for examples
    /// and testing.
    fn from_seed(seed: u64) -> Self {
        let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
        Self::new(&mut rng)
    }

    /// Returns the private key of the signer.
    fn private_key(&self) -> Self::PrivateKey;

    /// Returns the public key of the signer.
    fn public_key(&self) -> Self::PublicKey;

    /// Sign the given message.
    ///
    /// The message should not be hashed prior to calling this function. If a particular scheme
    /// requires a payload to be hashed before it is signed, it will be done internally.
    ///
    /// A namespace should be used to prevent replay attacks. It will be prepended to the message so
    /// that a signature meant for one context cannot be used unexpectedly in another (i.e. signing
    /// a message on the network layer can't accidentally spend funds on the execution layer). See
    /// [union_unique](commonware_utils::union_unique) for details.
    fn sign(&mut self, namespace: Option<&[u8]>, message: &[u8]) -> Self::Signature;

    /// Check that a signature is valid for the given message and public key.
    ///
    /// The message should not be hashed prior to calling this function. If a particular
    /// scheme requires a payload to be hashed before it is signed, it will be done internally.
    ///
    /// Because namespace is prepended to message before signing, the namespace provided here must
    /// match the namespace provided during signing.
    fn verify(
        namespace: Option<&[u8]>,
        message: &[u8],
        public_key: &Self::PublicKey,
        signature: &Self::Signature,
    ) -> bool;
}

/// Interface that commonware crates rely on for batched cryptographic operations.
pub trait BatchScheme {
    /// Public key used for verifying signatures.
    type PublicKey: Array;

    /// Signature generated by signing a message.
    type Signature: Array;

    /// Create a new batch scheme.
    fn new() -> Self;

    /// Append item to the batch.
    ///
    /// The message should not be hashed prior to calling this function. If a particular scheme
    /// requires a payload to be hashed before it is signed, it will be done internally.
    ///
    /// A namespace should be used to prevent replay attacks. It will be prepended to the message so
    /// that a signature meant for one context cannot be used unexpectedly in another (i.e. signing
    /// a message on the network layer can't accidentally spend funds on the execution layer). See
    /// [union_unique](commonware_utils::union_unique) for details.
    fn add(
        &mut self,
        namespace: Option<&[u8]>,
        message: &[u8],
        public_key: &Self::PublicKey,
        signature: &Self::Signature,
    ) -> bool;

    /// Verify all items added to the batch.
    ///
    /// Returns `true` if all items are valid, `false` otherwise.
    ///
    /// # Why Randomness?
    ///
    /// When performing batch verification, it is often important to add some randomness
    /// to prevent an attacker from constructing a malicious batch of signatures that pass
    /// batch verification but are invalid individually. Abstractly, think of this as
    /// there existing two valid signatures (`c_1` and `c_2`) and an attacker proposing
    /// (`c_1 + d` and `c_2 - d`).
    ///
    /// You can read more about this [here](https://ethresear.ch/t/security-of-bls-batch-verification/10748#the-importance-of-randomness-4).
    fn verify<R: RngCore + CryptoRng>(self, rng: &mut R) -> bool;
}

/// Interface that commonware crates rely on for hashing.
///
/// Hash functions in commonware primitives are not typically hardcoded
/// to a specific algorithm (e.g. SHA-256) because different hash functions
/// may work better with different cryptographic schemes, may be more efficient
/// to use in STARK/SNARK proofs, or provide different levels of security (with some
/// performance/size penalty).
///
/// This trait is required to implement the `Clone` trait because it is often
/// part of a struct that is cloned. In practice, implementations do not actually
/// clone the hasher state but users should not rely on this behavior and call `reset`
/// after cloning.
pub trait Hasher: Clone + Send + Sync + 'static {
    /// Digest generated by the hasher.
    type Digest: Array;

    /// Create a new hasher.
    fn new() -> Self;

    /// Append message to previously recorded data.
    fn update(&mut self, message: &[u8]);

    /// Hash all recorded data and reset the hasher
    /// to the initial state.
    fn finalize(&mut self) -> Self::Digest;

    /// Reset the hasher without generating a hash.
    ///
    /// This function does not need to be called after `finalize`.
    fn reset(&mut self);

    /// Generate a random digest.
    ///
    /// # Warning
    ///
    /// This function is typically used for testing and is not recommended
    /// for production use.
    fn random<R: Rng + CryptoRng>(rng: &mut R) -> Self::Digest;
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::OsRng;

    fn test_validate<C: Scheme>() {
        let signer = C::new(&mut OsRng);
        let public_key = signer.public_key();
        assert!(C::PublicKey::try_from(public_key.as_ref()).is_ok());
    }

    fn test_from_valid_private_key<C: Scheme>() {
        let signer = C::new(&mut OsRng);
        let private_key = signer.private_key();
        let public_key = signer.public_key();
        let signer = C::from(private_key).unwrap();
        assert_eq!(public_key, signer.public_key());
    }

    fn test_validate_invalid_public_key<C: Scheme>() {
        let result = C::PublicKey::try_from(vec![0; 1024]);
        assert_eq!(result, Err(Error::InvalidPublicKeyLength));
    }

    fn test_sign_and_verify<C: Scheme>() {
        let mut signer = C::from_seed(0);
        let namespace = Some(&b"test_namespace"[..]);
        let message = b"test_message";
        let signature = signer.sign(namespace, message);
        let public_key = signer.public_key();
        assert!(C::verify(namespace, message, &public_key, &signature));
    }

    fn test_sign_and_verify_wrong_message<C: Scheme>() {
        let mut signer = C::from_seed(0);
        let namespace: Option<&[u8]> = Some(&b"test_namespace"[..]);
        let message = b"test_message";
        let wrong_message = b"wrong_message";
        let signature = signer.sign(namespace, message);
        let public_key = signer.public_key();
        assert!(!C::verify(
            namespace,
            wrong_message,
            &public_key,
            &signature
        ));
    }

    fn test_sign_and_verify_wrong_namespace<C: Scheme>() {
        let mut signer = C::from_seed(0);
        let namespace = Some(&b"test_namespace"[..]);
        let wrong_namespace = Some(&b"wrong_namespace"[..]);
        let message = b"test_message";
        let signature = signer.sign(namespace, message);
        let public_key = signer.public_key();
        assert!(!C::verify(
            wrong_namespace,
            message,
            &public_key,
            &signature
        ));
    }

    fn test_empty_vs_none_namespace<C: Scheme>() {
        let mut signer = C::from_seed(0);
        let empty_namespace = Some(&b""[..]);
        let message = b"test_message";
        let signature = signer.sign(empty_namespace, message);
        let public_key = signer.public_key();
        assert!(C::verify(empty_namespace, message, &public_key, &signature));
        assert!(!C::verify(None, message, &public_key, &signature));
    }

    fn test_signature_determinism<C: Scheme>() {
        let mut signer_1 = C::from_seed(0);
        let mut signer_2 = C::from_seed(0);
        let namespace = Some(&b"test_namespace"[..]);
        let message = b"test_message";
        let signature_1 = signer_1.sign(namespace, message);
        let signature_2 = signer_2.sign(namespace, message);
        assert_eq!(signer_1.public_key(), signer_2.public_key());
        assert_eq!(signature_1, signature_2);
    }

    fn test_invalid_signature_publickey_pair<C: Scheme>() {
        let mut signer = C::from_seed(0);
        let signer_2 = C::from_seed(1);
        let namespace = Some(&b"test_namespace"[..]);
        let message = b"test_message";
        let signature = signer.sign(namespace, message);
        let public_key = signer_2.public_key();
        assert!(!C::verify(namespace, message, &public_key, &signature));
    }

    #[test]
    fn test_ed25519_validate() {
        test_validate::<Ed25519>();
    }

    #[test]
    fn test_ed25519_validate_invalid_public_key() {
        test_validate_invalid_public_key::<Ed25519>();
    }

    #[test]
    fn test_ed25519_from_valid_private_key() {
        test_from_valid_private_key::<Ed25519>();
    }

    #[test]
    fn test_ed25519_sign_and_verify() {
        test_sign_and_verify::<Ed25519>();
    }

    #[test]
    fn test_ed25519_sign_and_verify_wrong_message() {
        test_sign_and_verify_wrong_message::<Ed25519>();
    }

    #[test]
    fn test_ed25519_sign_and_verify_wrong_namespace() {
        test_sign_and_verify_wrong_namespace::<Ed25519>();
    }

    #[test]
    fn test_ed25519_empty_vs_none_namespace() {
        test_empty_vs_none_namespace::<Ed25519>();
    }

    #[test]
    fn test_ed25519_signature_determinism() {
        test_signature_determinism::<Ed25519>();
    }

    #[test]
    fn test_ed25519_invalid_signature_publickey_pair() {
        test_invalid_signature_publickey_pair::<Ed25519>();
    }

    #[test]
    fn test_ed25519_len() {
        assert_eq!(<Ed25519 as Scheme>::PublicKey::SERIALIZED_LEN, 32);
        assert_eq!(<Ed25519 as Scheme>::Signature::SERIALIZED_LEN, 64);
    }

    #[test]
    fn test_bls12381_validate() {
        test_validate::<Bls12381>();
    }

    #[test]
    fn test_bls12381_validate_invalid_public_key() {
        test_validate_invalid_public_key::<Bls12381>();
    }

    #[test]
    fn test_bls12381_from_valid_private_key() {
        test_from_valid_private_key::<Bls12381>();
    }

    #[test]
    fn test_bls12381_sign_and_verify() {
        test_sign_and_verify::<Bls12381>();
    }

    #[test]
    fn test_bls12381_sign_and_verify_wrong_message() {
        test_sign_and_verify_wrong_message::<Bls12381>();
    }

    #[test]
    fn test_bls12381_sign_and_verify_wrong_namespace() {
        test_sign_and_verify_wrong_namespace::<Bls12381>();
    }

    #[test]
    fn test_bls12381_empty_vs_none_namespace() {
        test_empty_vs_none_namespace::<Bls12381>();
    }

    #[test]
    fn test_bls12381_signature_determinism() {
        test_signature_determinism::<Bls12381>();
    }

    #[test]
    fn test_bls12381_invalid_signature_publickey_pair() {
        test_invalid_signature_publickey_pair::<Bls12381>();
    }

    #[test]
    fn test_bls12381_len() {
        assert_eq!(<Bls12381 as Scheme>::PublicKey::SERIALIZED_LEN, 48);
        assert_eq!(<Bls12381 as Scheme>::Signature::SERIALIZED_LEN, 96);
    }

    #[test]
    fn test_secp256r1_validate() {
        test_validate::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_validate_invalid_public_key() {
        test_validate_invalid_public_key::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_from_valid_private_key() {
        test_from_valid_private_key::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_sign_and_verify() {
        test_sign_and_verify::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_sign_and_verify_wrong_message() {
        test_sign_and_verify_wrong_message::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_sign_and_verify_wrong_namespace() {
        test_sign_and_verify_wrong_namespace::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_empty_vs_none_namespace() {
        test_empty_vs_none_namespace::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_signature_determinism() {
        test_signature_determinism::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_invalid_signature_publickey_pair() {
        test_invalid_signature_publickey_pair::<Secp256r1>();
    }

    #[test]
    fn test_secp256r1_len() {
        assert_eq!(<Secp256r1 as Scheme>::PublicKey::SERIALIZED_LEN, 33);
        assert_eq!(<Secp256r1 as Scheme>::Signature::SERIALIZED_LEN, 64);
    }

    fn test_hasher_multiple_runs<H: Hasher>() {
        // Generate initial hash
        let mut hasher = H::new();
        hasher.update(b"hello world");
        let digest = hasher.finalize();
        assert!(H::Digest::try_from(digest.as_ref()).is_ok());
        assert_eq!(digest.as_ref().len(), H::Digest::SERIALIZED_LEN);

        // Reuse hasher without reset
        hasher.update(b"hello world");
        let digest_again = hasher.finalize();
        assert!(H::Digest::try_from(digest_again.as_ref()).is_ok());
        assert_eq!(digest, digest_again);

        // Reuse hasher with reset
        hasher.update(b"hello mars");
        hasher.reset();
        hasher.update(b"hello world");
        let digest_reset = hasher.finalize();
        assert!(H::Digest::try_from(digest_reset.as_ref()).is_ok());
        assert_eq!(digest, digest_reset);

        // Hash different data
        hasher.update(b"hello mars");
        let digest_mars = hasher.finalize();
        assert!(H::Digest::try_from(digest_mars.as_ref()).is_ok());
        assert_ne!(digest, digest_mars);
    }

    fn test_hasher_multiple_updates<H: Hasher>() {
        // Generate initial hash
        let mut hasher = H::new();
        hasher.update(b"hello");
        hasher.update(b" world");
        let digest = hasher.finalize();
        assert!(H::Digest::try_from(digest.as_ref()).is_ok());

        // Generate hash in oneshot
        let mut hasher = H::new();
        hasher.update(b"hello world");
        let digest_oneshot = hasher.finalize();
        assert!(H::Digest::try_from(digest_oneshot.as_ref()).is_ok());
        assert_eq!(digest, digest_oneshot);
    }

    fn test_hasher_empty_input<H: Hasher>() {
        let mut hasher = H::new();
        let digest = hasher.finalize();
        assert!(H::Digest::try_from(digest.as_ref()).is_ok());
    }

    fn test_hasher_large_input<H: Hasher>() {
        let mut hasher = H::new();
        let data = vec![1; 1024];
        hasher.update(&data);
        let digest = hasher.finalize();
        assert!(H::Digest::try_from(digest.as_ref()).is_ok());
    }

    #[test]
    fn test_sha256_hasher_multiple_runs() {
        test_hasher_multiple_runs::<Sha256>();
    }

    #[test]
    fn test_sha256_hasher_multiple_updates() {
        test_hasher_multiple_updates::<Sha256>();
    }

    #[test]
    fn test_sha256_hasher_empty_input() {
        test_hasher_empty_input::<Sha256>();
    }

    #[test]
    fn test_sha256_hasher_large_input() {
        test_hasher_large_input::<Sha256>();
    }
}