commonware-cryptography 2026.10.0

Generate keys, sign arbitrary messages, and deterministically verify signatures.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! Generate keys, sign arbitrary messages, and deterministically verify signatures.
//!
//! # Randomness
//!
//! Cryptographic operations that accept an RNG require a cryptographically secure and
//! unpredictable source unless documented otherwise. A weak or predictable RNG may compromise
//! security.
//!
//! # Status
//!
//! Stability varies by primitive. See [README](https://github.com/commonwarexyz/monorepo#stability) for details.

#![doc(
    html_logo_url = "https://commonware.xyz/imgs/rustdoc_logo.svg",
    html_favicon_url = "https://commonware.xyz/favicon.ico"
)]
#![cfg_attr(not(any(feature = "std", test)), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;

// Modules containing #[macro_export] macros must use verbose cfg.
// See rust-lang/rust#52234: macro-expanded macro_export macros cannot be referenced by absolute paths.
#[cfg(all(
    feature = "bls12381",
    not(any(
        commonware_stability_GAMMA,
        commonware_stability_DELTA,
        commonware_stability_EPSILON,
        commonware_stability_RESERVED
    ))
))] // BETA
pub mod bls12381;
#[cfg(not(any(
    commonware_stability_GAMMA,
    commonware_stability_DELTA,
    commonware_stability_EPSILON,
    commonware_stability_RESERVED
)))] // BETA
pub mod ed25519;
#[cfg(not(any(
    commonware_stability_BETA,
    commonware_stability_GAMMA,
    commonware_stability_DELTA,
    commonware_stability_EPSILON,
    commonware_stability_RESERVED
)))] // ALPHA
pub mod secp256r1;

commonware_macros::stability_scope!(ALPHA {
    #[cfg(feature = "std")]
    pub mod banderwagon;
    pub mod bloomfilter;
    pub use crate::bloomfilter::BloomFilter;

    #[cfg(any(test, feature = "fuzz"))]
    pub mod fuzz;

    pub mod keccak256;
    pub use crate::keccak256::{CoreKeccak256, Keccak256};

    pub mod lthash;
    pub use crate::lthash::LtHash;

    pub mod reed_solomon;

    pub mod sha512;
    pub use crate::sha512::{CoreSha512, Sha512};

    pub mod zk;
});
commonware_macros::stability_scope!(BETA {
    #[cfg(not(feature = "std"))]
    use alloc::{sync::Arc, vec::Vec};
    use commonware_codec::{BufsMut, Encode, EncodeSize, ReadExt, Write};
    use commonware_math::algebra::Random;
    use commonware_parallel::Strategy;
    use commonware_utils::Array;
    use core::{fmt, future::Future, num::NonZeroUsize};
    use rand_chacha::ChaCha20Rng;
    use rand_core::{CryptoRng, SeedableRng as _};
    #[cfg(feature = "std")]
    use std::{sync::Arc, vec::Vec};

    pub mod secret;
    pub use crate::secret::Secret;

    pub mod certificate;
    pub mod transcript;

    pub mod sha256;
    pub use crate::sha256::{CoreSha256, Sha256};
    pub mod blake3;
    pub use crate::blake3::{Blake3, CoreBlake3};
    #[cfg(feature = "std")]
    pub mod crc32;
    #[cfg(feature = "std")]
    pub use crate::crc32::Crc32;

    #[cfg(feature = "std")]
    pub mod chacha20_poly1305;
    #[cfg(feature = "std")]
    pub use crate::chacha20_poly1305::ChaCha20Poly1305;

    #[cfg(feature = "std")]
    pub mod handshake;

    /// Produces [Signature]s over messages that can be verified with a corresponding [PublicKey].
    pub trait Signer: Random + Send + Sync + Clone + 'static {
        /// The type of [Signature] produced by this [Signer].
        type Signature: Signature;

        /// The corresponding [PublicKey] type.
        type PublicKey: PublicKey<Signature = Self::Signature>;

        /// Returns the [PublicKey] corresponding to this [Signer].
        fn public_key(&self) -> Self::PublicKey;

        /// Sign a message with the given namespace.
        ///
        /// 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 must be used to prevent cross-domain attacks (where a signature can be reused
        /// in a different context). It must 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
        /// [commonware_utils::union_unique] for details.
        fn sign(&self, namespace: &[u8], msg: &[u8]) -> Self::Signature;

        /// Create a [Signer] from a seed.
        ///
        /// # Warning
        ///
        /// This function is insecure and should only be used for examples
        /// and testing.
        fn from_seed(seed: u64) -> Self {
            Self::random(ChaCha20Rng::seed_from_u64(seed))
        }
    }

    /// A [Signer] that can be serialized/deserialized.
    pub trait PrivateKey: Signer + Sized + ReadExt + Encode {}

    /// Verifies [Signature]s over messages.
    pub trait Verifier {
        /// The type of [Signature] that this verifier can verify.
        type Signature: Signature;

        /// Verify that a [Signature] is a valid over a 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.
        ///
        /// Because namespace is prepended to message before signing, the namespace provided here must
        /// match the namespace provided during signing.
        fn verify(&self, namespace: &[u8], msg: &[u8], sig: &Self::Signature) -> bool;
    }

    /// A [PublicKey], able to verify [Signature]s.
    pub trait PublicKey: Verifier + Sized + ReadExt + Array {}

    /// A [Signature] over a message.
    pub trait Signature: Sized + ReadExt + Array {}

    /// An extension of [Signature] that supports public key recovery.
    pub trait Recoverable: Signature {
        /// The type of [PublicKey] that can be recovered from this [Signature].
        type PublicKey: PublicKey<Signature = Self>;

        /// Recover the [PublicKey] of the signer that created this [Signature] over 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.
        ///
        /// Like when verifying a signature, the namespace must match what was used during signing exactly.
        fn recover_signer(&self, namespace: &[u8], msg: &[u8]) -> Option<Self::PublicKey>;
    }

    /// A borrowed view of one signature and the message it authenticates.
    #[derive(Clone)]
    pub struct BatchEntry<'a, P: PublicKey> {
        /// The namespace used during signing.
        pub namespace: &'a [u8],
        /// The message used during signing.
        pub message: &'a [u8],
        /// The signer's public key.
        pub public_key: &'a P,
        /// The signature to verify.
        pub signature: &'a P::Signature,
    }

    impl<P: PublicKey> Copy for BatchEntry<'_, P> {}

    /// A [PublicKey] that supports batch verification of [Signature]s.
    pub trait BatchVerifier: PublicKey {
        /// Verify all signatures projected from a slice of items.
        ///
        /// The projection receives each item's original slice index. It must
        /// return the same entry for a given index and item.
        ///
        /// Messages should not be hashed before calling this function. Any hashing
        /// required by the signature scheme is performed internally.
        ///
        /// Each namespace must match the one used during signing exactly. Use distinct
        /// namespaces for distinct signing contexts to prevent replay attacks. For
        /// example, a signature on a message in the network layer must not authorize
        /// spending funds in the execution layer.
        ///
        /// Returns `false` if the slice is empty or any signature is invalid.
        ///
        /// # Examples
        ///
        /// ```
        /// use commonware_cryptography::{
        ///     BatchEntry, BatchVerifier, Signer,
        ///     ed25519::{PrivateKey, PublicKey},
        /// };
        /// use commonware_math::algebra::Random;
        /// use commonware_parallel::Sequential;
        /// use commonware_utils::test_rng;
        ///
        /// let key = PrivateKey::random(test_rng());
        /// let public_key = key.public_key();
        /// let namespace = b"example";
        /// let records = [(b"message".as_slice(), key.sign(namespace, b"message"))];
        /// assert!(PublicKey::verify_batch(
        ///     &mut test_rng(),
        ///     &records,
        ///     |_, (message, signature)| BatchEntry {
        ///         namespace,
        ///         message,
        ///         public_key: &public_key,
        ///         signature,
        ///     },
        ///     &Sequential,
        /// ));
        /// ```
        ///
        /// # 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_batch<'a, R, T, F>(
            rng: &mut R,
            items: &'a [T],
            project: F,
            strategy: &impl Strategy,
        ) -> bool
        where
            R: CryptoRng,
            T: Sync,
            F: Fn(usize, &'a T) -> BatchEntry<'a, Self> + Sync;
    }

    /// Specializes the [commonware_utils::Array] trait with the Copy trait for cryptographic digests
    /// (which should be cheap to clone).
    ///
    /// # Warning
    ///
    /// This trait requires [`Random::random`], but generating a digest at random is
    /// typically reserved for testing, and not production use.
    pub trait Digest: Array + Copy + Random {
        /// An empty (all-zero) digest.
        const EMPTY: Self;
    }

    /// An object that can be uniquely represented as a [Digest].
    pub trait Digestible: Clone + Sized + Send + Sync + 'static {
        /// The type of digest produced by this object.
        type Digest: Digest;

        /// Returns a unique representation of the object as a [Digest].
        ///
        /// If many objects with [Digest]s are related (map to some higher-level
        /// group [Digest]), you should also implement [Committable].
        fn digest(&self) -> Self::Digest;

        /// Returns the object's digest, splitting any work in computing it across `strategy`.
        fn digest_across(&self, _strategy: &impl Strategy) -> Self::Digest {
            self.digest()
        }
    }

    impl<T: Digestible> Digestible for Arc<T> {
        type Digest = T::Digest;

        fn digest(&self) -> Self::Digest {
            self.as_ref().digest()
        }

        fn digest_across(&self, strategy: &impl Strategy) -> Self::Digest {
            self.as_ref().digest_across(strategy)
        }
    }

    /// A shared value paired with its [Digest].
    ///
    /// [`Digested::compute`] hashes the value as a job on a [Strategy], and
    /// [`Digested::precomputed`] pairs it with a digest a local source already computed from this
    /// exact value. Holders read the digest for free and never choose a strategy. The value must
    /// not change anything its digest covers while a carrier refers to it.
    ///
    /// Cloning shares the value. Two values are equal when their digests are equal, which the
    /// [Digestible] contract makes equivalent to the values being equal. The value encodes as the
    /// inner value does, and there is no decoding. A decoded value is paired with its digest by
    /// one of the constructors.
    pub struct Digested<T: Digestible> {
        inner: Arc<T>,
        digest: T::Digest,
    }

    impl<T: Digestible> Digested<T> {
        /// Computes the digest of `inner` as a job on `strategy`.
        #[track_caller]
        pub fn compute(
            inner: impl Into<Arc<T>>,
            strategy: &impl Strategy,
        ) -> impl Future<Output = Self> + Send + 'static
        where
            T: EncodeSize,
        {
            let inner: Arc<T> = inner.into();
            strategy.spawn(inner.encode_size(), move |strategy| {
                let digest = inner.digest_across(&strategy);
                Self { inner, digest }
            })
        }

        /// Pairs `inner` with a digest already computed from this exact value.
        ///
        /// `digest` must come from a local source bound to `inner`, such as the key the value was
        /// stored under, a commitment checked against its bytes, or an earlier [`Self::compute`].
        /// It says nothing about whether the value is valid or certified.
        pub fn precomputed(inner: impl Into<Arc<T>>, digest: T::Digest) -> Self {
            Self {
                inner: inner.into(),
                digest,
            }
        }

        /// Returns a reference to the value.
        pub fn inner(&self) -> &T {
            &self.inner
        }

        /// Returns a shared reference to the value.
        pub fn inner_shared(&self) -> Arc<T> {
            Arc::clone(&self.inner)
        }
    }

    impl<T: Digestible> Clone for Digested<T> {
        fn clone(&self) -> Self {
            Self {
                inner: Arc::clone(&self.inner),
                digest: self.digest,
            }
        }
    }

    impl<T: Digestible + fmt::Debug> fmt::Debug for Digested<T> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("Digested")
                .field("digest", &self.digest)
                .field("inner", &self.inner)
                .finish()
        }
    }

    impl<T: Digestible> PartialEq for Digested<T> {
        fn eq(&self, other: &Self) -> bool {
            self.digest == other.digest
        }
    }

    impl<T: Digestible> Eq for Digested<T> {}

    impl<T: Digestible> Digestible for Digested<T> {
        type Digest = T::Digest;

        fn digest(&self) -> Self::Digest {
            self.digest
        }
    }

    impl<T: Digestible + Write> Write for Digested<T> {
        fn write(&self, buf: &mut impl bytes::BufMut) {
            self.inner.write(buf);
        }

        fn write_bufs(&self, buf: &mut impl BufsMut) {
            self.inner.write_bufs(buf);
        }
    }

    impl<T: Digestible + EncodeSize> EncodeSize for Digested<T> {
        fn encode_size(&self) -> usize {
            self.inner.encode_size()
        }

        fn encode_inline_size(&self) -> usize {
            self.inner.encode_inline_size()
        }
    }

    impl<T: Digestible> From<Digested<T>> for Arc<T> {
        fn from(digested: Digested<T>) -> Self {
            digested.inner
        }
    }

    #[cfg(feature = "arbitrary")]
    impl<'a, T> arbitrary::Arbitrary<'a> for Digested<T>
    where
        T: Digestible + arbitrary::Arbitrary<'a>,
    {
        fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
            let inner = T::arbitrary(u)?;
            let digest = inner.digest();
            Ok(Self::precomputed(inner, digest))
        }
    }

    /// An object that can produce a commitment of itself.
    pub trait Committable: Clone + Sized + Send + Sync + 'static {
        /// The type of commitment produced by this object.
        type Commitment: Digest;

        /// Returns the unique commitment of the object as a [Digest].
        ///
        /// For simple objects (like a block), this is often just the digest of the object
        /// itself. For more complex objects, however, this may represent some root or base
        /// of a proof structure (where many unique objects map to the same commitment).
        ///
        /// # Warning
        ///
        /// It must not be possible for two objects with the same [Digest] to map
        /// to different commitments. Primitives assume there is a one-to-one
        /// relation between digest and commitment and a one-to-many relation
        /// between commitment and digest.
        fn commitment(&self) -> Self::Commitment;
    }

    pub type DigestOf<H> = <H as Hasher>::Digest;

    /// 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).
    ///
    /// Hashers are cheap to construct: callers that need a fresh hasher should
    /// create one with [`Default`] rather than duplicating an existing instance.
    pub trait Hasher: Default + Send + Sync + 'static {
        /// Digest generated by the hasher.
        type Digest: Digest;

        /// Hash the concatenation of `parts` in a single shot.
        ///
        /// This is the preferred entrypoint for hashing data that is fully
        /// available up-front. Implementations are free to specialize this for
        /// small, fixed-shape inputs (e.g. hashing a pair of digests) to avoid
        /// the overhead of the streaming machinery.
        fn hash(parts: &[&[u8]]) -> Self::Digest;

        /// Hash the concatenation of `parts` in a single shot, splitting the
        /// work across `strategy` when the hash function allows it.
        ///
        /// Returns the same digest as [`Hasher::hash`], which the default
        /// implementation calls.
        fn hash_across(parts: &[&[u8]], _strategy: &impl Strategy) -> Self::Digest {
            Self::hash(parts)
        }

        /// Hash two messages, each given as a concatenation of parts, in a
        /// single shot, splitting the work across `strategy` when the hash
        /// function allows it.
        ///
        /// Must be equivalent to hashing each message with [`Hasher::hash`].
        fn hash_pair(
            left: &[&[u8]],
            right: &[&[u8]],
            strategy: &impl Strategy,
        ) -> (Self::Digest, Self::Digest);

        /// Hash multiple independent byte slices, splitting them across
        /// `strategy`.
        ///
        /// Returns one digest per input in the same order. Inputs may be empty,
        /// differ in length, or overlap. Output position `i` is equivalent to
        /// `Self::hash(&[messages[i].as_ref()])`.
        fn hash_many<M: AsRef<[u8]> + Sync>(
            messages: &[M],
            strategy: &impl Strategy,
        ) -> Vec<Self::Digest> {
            hash_batches(messages, 1, strategy, |batch| {
                batch
                    .iter()
                    .map(|message| Self::hash_across(&[message.as_ref()], strategy))
                    .collect()
            })
        }

        /// Append `bytes` to the hasher's running state.
        fn update(&mut self, bytes: &[u8]) -> &mut Self;

        /// Consume the hasher, returning a freshly-reset hasher alongside the
        /// digest of everything written so far.
        fn finalize(self) -> (Self, Self::Digest);
    }

    /// Hash `messages` in strategy-supplied batches of whole units of `lanes` (at least one)
    /// messages, so a kernel that hashes `lanes` messages at once finds every unit but the last
    /// one full.
    ///
    /// `hash` must return one digest per message of its batch, in order. The work estimate is
    /// the total length of the messages in bytes.
    pub(crate) fn hash_batches<D, M>(
        messages: &[M],
        lanes: usize,
        strategy: &impl Strategy,
        hash: impl Fn(&[M]) -> Vec<D> + Sync,
    ) -> Vec<D>
    where
        D: Clone + Send,
        M: AsRef<[u8]> + Sync,
    {
        if messages.is_empty() {
            return Vec::new();
        }
        let units = messages.len().div_ceil(lanes);
        let bytes = messages.iter().fold(0usize, |bytes, message| {
            bytes.saturating_add(message.as_ref().len())
        });
        strategy.run_batches(units, NonZeroUsize::MIN, bytes.div_ceil(units), |batches| {
            // A serial run hashes the whole input as one batch, whose digests need no copy.
            if batches.is_whole() {
                return hash(messages);
            }
            batches
                .map_collect_vec(
                    |ranges| {
                        ranges.into_iter().map(|range| {
                            let end = range.end.saturating_mul(lanes).min(messages.len());
                            &messages[range.start * lanes..end]
                        })
                    },
                    &hash,
                )
                .concat()
        })
    }

    /// Authenticated encryption of an ordered sequence of messages.
    ///
    /// Every message is encrypted and authenticated with its associated data. The nth call to
    /// [Cipher::open] accepts only the nth message sealed under the same key, so replayed,
    /// reordered, or modified messages fail to open. A failed call consumes the cipher. At most
    /// one instance may seal under a given key.
    pub trait Cipher: Random + Sized + Send + Sync + 'static {
        /// Authentication tag produced for each message.
        type Tag: Array;

        /// Encrypts the next message in place, authenticated together with `aad`, and returns
        /// the cipher with the tag.
        ///
        /// Returns `None` if sealing fails, in which case the contents of `data` are unspecified.
        #[must_use = "the cipher is returned only if sealing succeeds"]
        fn seal(self, aad: &[u8], data: &mut [u8]) -> Option<(Self, Self::Tag)>;

        /// Decrypts the next message in place if `tag` authenticates it together with `aad`, and
        /// returns the cipher.
        ///
        /// Returns `None` if opening fails, in which case the contents of `data` are unspecified.
        #[must_use = "data is authentic only if opening succeeds"]
        fn open(self, aad: &[u8], data: &mut [u8], tag: &Self::Tag) -> Option<Self>;
    }
});

#[cfg(test)]
mod tests {
    use super::*;
    use commonware_codec::{DecodeExt, FixedSize};
    use commonware_parallel::mocks::{Explorer, pooled};
    use commonware_utils::{NZUsize, test_rng};
    use std::collections::HashSet;

    fn test_validate<C: PrivateKey>() {
        let mut rng = test_rng();
        let private_key = C::random(&mut rng);
        let public_key = private_key.public_key();
        let decoded = C::PublicKey::decode(commonware_codec::Copying(public_key.as_ref())).unwrap();
        assert_eq!(public_key, decoded);
        assert_eq!(public_key.cmp(&decoded), core::cmp::Ordering::Equal);

        let other = C::random(&mut rng).public_key();
        assert_ne!(public_key, other);
        let mut keys = HashSet::from([public_key]);
        assert!(!keys.insert(decoded));
        assert!(keys.insert(other));
    }

    fn test_public_key_order<C: PrivateKey>() {
        let mut rng = test_rng();
        let mut keys = Vec::new();
        for _ in 0..16 {
            let key = C::random(&mut rng).public_key();
            let decoded = C::PublicKey::decode(commonware_codec::Copying(key.as_ref())).unwrap();
            keys.extend([key, decoded]);
        }

        for a in &keys {
            for b in &keys {
                let expected = a.as_ref().cmp(b.as_ref());
                assert_eq!(a.cmp(b), expected);
                assert_eq!(a.partial_cmp(b), Some(expected));
                assert_eq!(a == b, expected.is_eq());
            }
        }
    }

    fn test_validate_invalid_public_key<C: Signer>() {
        let result = C::PublicKey::decode(vec![0; 1024]);
        assert!(result.is_err());
    }

    fn test_sign_and_verify<C: PrivateKey>() {
        let private_key = C::from_seed(0);
        let namespace = b"test_namespace";
        let message = b"test_message";
        let signature = private_key.sign(namespace, message);
        let public_key = private_key.public_key();
        assert!(public_key.verify(namespace, message, &signature));
    }

    fn test_sign_and_verify_wrong_message<C: PrivateKey>() {
        let private_key = C::from_seed(0);
        let namespace = b"test_namespace";
        let message = b"test_message";
        let wrong_message = b"wrong_message";
        let signature = private_key.sign(namespace, message);
        let public_key = private_key.public_key();
        assert!(!public_key.verify(namespace, wrong_message, &signature));
    }

    fn test_sign_and_verify_wrong_namespace<C: PrivateKey>() {
        let private_key = C::from_seed(0);
        let namespace = b"test_namespace";
        let wrong_namespace = b"wrong_namespace";
        let message = b"test_message";
        let signature = private_key.sign(namespace, message);
        let public_key = private_key.public_key();
        assert!(!public_key.verify(wrong_namespace, message, &signature));
    }

    fn test_empty_namespace<C: PrivateKey>() {
        let private_key = C::from_seed(0);
        let empty_namespace = b"";
        let message = b"test_message";
        let signature = private_key.sign(empty_namespace, message);
        let public_key = private_key.public_key();
        assert!(public_key.verify(empty_namespace, message, &signature));
    }

    fn test_signature_determinism<C: PrivateKey>() {
        let private_key_1 = C::from_seed(0);
        let private_key_2 = C::from_seed(0);
        let namespace = b"test_namespace";
        let message = b"test_message";
        let signature_1 = private_key_1.sign(namespace, message);
        let signature_2 = private_key_2.sign(namespace, message);
        assert_eq!(private_key_1.public_key(), private_key_2.public_key());
        assert_eq!(signature_1, signature_2);
    }

    fn test_invalid_signature_publickey_pair<C: PrivateKey>() {
        let private_key = C::from_seed(0);
        let private_key_2 = C::from_seed(1);
        let namespace = b"test_namespace";
        let message = b"test_message";
        let signature = private_key.sign(namespace, message);
        let public_key = private_key_2.public_key();
        assert!(!public_key.verify(namespace, message, &signature));
    }

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

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

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

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

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

    #[test]
    fn test_ed25519_empty_namespace() {
        test_empty_namespace::<ed25519::PrivateKey>();
    }

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

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

    #[test]
    fn test_ed25519_len() {
        assert_eq!(ed25519::PublicKey::SIZE, 32);
        assert_eq!(ed25519::Signature::SIZE, 64);
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_validate() {
        test_validate::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_validate_invalid_public_key() {
        test_validate_invalid_public_key::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_sign_and_verify() {
        test_sign_and_verify::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_sign_and_verify_wrong_message() {
        test_sign_and_verify_wrong_message::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_sign_and_verify_wrong_namespace() {
        test_sign_and_verify_wrong_namespace::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_empty_namespace() {
        test_empty_namespace::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_signature_determinism() {
        test_signature_determinism::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_invalid_signature_publickey_pair() {
        test_invalid_signature_publickey_pair::<bls12381::PrivateKey>();
    }

    #[test]
    #[cfg(feature = "bls12381")]
    fn test_bls12381_len() {
        assert_eq!(bls12381::PublicKey::SIZE, 48);
        assert_eq!(bls12381::Signature::SIZE, 96);
    }

    #[test]
    fn test_secp256r1_standard_validate() {
        test_validate::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_public_key_order() {
        test_public_key_order::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_validate_invalid_public_key() {
        test_validate_invalid_public_key::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_sign_and_verify() {
        test_sign_and_verify::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_sign_and_verify_wrong_message() {
        test_sign_and_verify_wrong_message::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_sign_and_verify_wrong_namespace() {
        test_sign_and_verify_wrong_namespace::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_empty_namespace() {
        test_empty_namespace::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_signature_determinism() {
        test_signature_determinism::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_invalid_signature_publickey_pair() {
        test_invalid_signature_publickey_pair::<secp256r1::standard::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_standard_len() {
        assert_eq!(secp256r1::standard::PublicKey::SIZE, 33);
        assert_eq!(secp256r1::standard::Signature::SIZE, 64);
    }

    #[test]
    fn test_secp256r1_recoverable_validate() {
        test_validate::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_public_key_order() {
        test_public_key_order::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_validate_invalid_public_key() {
        test_validate_invalid_public_key::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_sign_and_verify() {
        test_sign_and_verify::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_sign_and_verify_wrong_message() {
        test_sign_and_verify_wrong_message::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_sign_and_verify_wrong_namespace() {
        test_sign_and_verify_wrong_namespace::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_empty_namespace() {
        test_empty_namespace::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_signature_determinism() {
        test_signature_determinism::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_invalid_signature_publickey_pair() {
        test_invalid_signature_publickey_pair::<secp256r1::recoverable::PrivateKey>();
    }

    #[test]
    fn test_secp256r1_recoverable_len() {
        assert_eq!(secp256r1::recoverable::PublicKey::SIZE, 33);
        assert_eq!(secp256r1::recoverable::Signature::SIZE, 65);
    }

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

        // Reuse the reset hasher returned by finalize
        let mut hasher = hasher;
        hasher.update(b"hello world");
        let (hasher, digest_again) = hasher.finalize();
        assert!(H::Digest::decode(commonware_codec::Copying(digest_again.as_ref())).is_ok());
        assert_eq!(digest, digest_again);

        // Hash via the one-shot API
        let digest_oneshot = H::hash(&[b"hello world"]);
        assert!(H::Digest::decode(commonware_codec::Copying(digest_oneshot.as_ref())).is_ok());
        assert_eq!(digest, digest_oneshot);

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

    #[test]
    fn test_keccak256_hasher_multiple_runs() {
        test_hasher_multiple_runs::<Keccak256>();
    }

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

    #[test]
    fn test_sha512_hasher_multiple_runs() {
        test_hasher_multiple_runs::<Sha512>();
    }

    /// Shares cut the messages only between whole units of `lanes`, cover every message once,
    /// and return their digests in input order.
    #[test]
    fn test_hash_batches_shares_whole_units() {
        let strategy = Explorer::parallel(&pooled(NZUsize!(4), NZUsize!(8)));
        for lanes in [1, 2, 8, 16] {
            for count in [0, 1, lanes + 1, 3 * lanes, 7 * lanes + 1, 9 * lanes, 100] {
                // Each message holds its index, and its digest pairs that index with the index of
                // the first message in its share.
                let messages: Vec<[u8; 4]> = (0..count as u32).map(u32::to_le_bytes).collect();
                let digests = hash_batches(&messages, lanes, &strategy, |batch| {
                    let first = u32::from_le_bytes(batch[0]);
                    batch
                        .iter()
                        .map(|message| (u32::from_le_bytes(*message), first))
                        .collect()
                });
                assert!(digests.iter().map(|&(index, _)| index).eq(0..count as u32));

                // Every unit but the last is whole, so every share but the last holds a multiple
                // of `lanes` messages.
                let shares: Vec<_> = digests.chunk_by(|a, b| a.1 == b.1).collect();
                assert_eq!(shares.len(), count.div_ceil(lanes).min(8));
                if let Some((_, rest)) = shares.split_last() {
                    assert!(rest.iter().all(|share| share.len() % lanes == 0));
                }
            }
        }
    }
}