mithril_stm/
lib.rs

1#![doc = include_str!("../README.md")]
2//! Implementation of Stake-based Threshold Multisignatures
3//! Top-level API for Mithril Stake-based Threshold Multisignature scheme.
4//! See figure 6 of [the paper](https://eprint.iacr.org/2021/916) for most of the
5//! protocol.
6//!
7//! What follows is a simple example showing the usage of STM.
8//!
9//! ```rust
10//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
11//! use blake2::{Blake2b, digest::consts::U32};
12//! use rand_chacha::ChaCha20Rng;
13//! use rand_core::{RngCore, SeedableRng};
14//! use rayon::prelude::*; // We use par_iter to speed things up
15//!
16//! use mithril_stm::{
17//!    AggregateSignatureType, AggregationError, Clerk, Initializer, KeyRegistration, Parameters,
18//!    RegistrationEntry, Signer, SingleSignature, MithrilMembershipDigest,
19//! };
20//!
21//! let nparties = 4; // Use a small number of parties for this example
22//! type D = MithrilMembershipDigest; // Setting the hash function for convenience
23//!
24//! let mut rng = ChaCha20Rng::from_seed([0u8; 32]); // create and initialize rng
25//! let mut msg = [0u8; 16]; // setting an arbitrary message
26//! rng.fill_bytes(&mut msg);
27//!
28//! // In the following, we will have 4 parties try to sign `msg`, then aggregate and
29//! // verify those signatures.
30//!
31//! //////////////////////////
32//! // initialization phase //
33//! //////////////////////////
34//!
35//! // Set low parameters for testing
36//! // XXX: not for production
37//! let params = Parameters {
38//!     m: 100, // Security parameter XXX: not for production
39//!     k: 2, // Quorum parameter XXX: not for production
40//!     phi_f: 0.2, // Lottery parameter XXX: not for production
41//! };
42//!
43//! // Generate some arbitrary stake for each party
44//! // Stake is an integer.
45//! // Total stake of all parties is total stake in the system.
46//! let stakes = (0..nparties)
47//!     .into_iter()
48//!     .map(|_| 1 + (rng.next_u64() % 9999))
49//!     .collect::<Vec<_>>();
50//!
51//! // Create a new key registry from the parties and their stake
52//! let mut key_reg = KeyRegistration::initialize();
53//!
54//! // For each party, crate a Initializer.
55//! // This struct can create keys for the party.
56//! let mut ps: Vec<Initializer> = Vec::with_capacity(nparties);
57//! for stake in stakes {
58//!     // Create keys for this party
59//!     let p = Initializer::new(params, stake, &mut rng);
60//!     // Register keys with the KeyRegistration service
61//!     let entry = RegistrationEntry::new(
62//!         p.get_verification_key_proof_of_possession_for_concatenation(),
63//!         p.stake,
64//!     )
65//!     .unwrap();
66//!     key_reg.register_by_entry(&entry).unwrap();
67//!     ps.push(p);
68//! }
69//!
70//! // Close the key registration.
71//! let closed_reg = key_reg.close_registration();
72//!
73//! // Finalize the Initializer and turn it into a Signer, which can execute the
74//! // rest of the protocol.
75//! let ps = ps
76//!     .into_par_iter()
77//!     .map(|p| p.try_create_signer(&closed_reg).unwrap())
78//!     .collect::<Vec<Signer<D>>>();
79//!
80//! /////////////////////
81//! // operation phase //
82//! /////////////////////
83//!
84//! // Next, each party tries to sign the message for each index available.
85//! // We collect the successful signatures into a vec.
86//! let sigs = ps
87//!     .par_iter()
88//!     .filter_map(|p| p.create_single_signature(&msg).ok())
89//!     .collect::<Vec<SingleSignature>>();
90//!
91//! // Clerk can aggregate and verify signatures.
92//! let clerk = Clerk::new_clerk_from_signer(&ps[0]);
93//!
94//! // Aggregate and verify the signatures
95//! let msig = clerk.aggregate_signatures_with_type(&sigs, &msg, AggregateSignatureType::Concatenation);
96//! match msig {
97//!     Ok(aggr) => {
98//!         println!("Aggregate ok");
99//!         assert!(aggr
100//!             .verify(&msg, &clerk.compute_aggregate_verification_key(), &params)
101//!             .is_ok());
102//!     }
103//!     Err(error) => assert!(
104//!         matches!(
105//!             error.downcast_ref::<AggregationError>(),
106//!             Some(AggregationError::NotEnoughSignatures { .. })
107//!         ),
108//!         "Unexpected error: {error}"
109//!     ),
110//! }
111//! # Ok(())
112//! # }
113//! ```
114
115#[cfg(feature = "future_snark")]
116pub mod circuits;
117#[cfg(feature = "future_snark")]
118mod hash;
119mod membership_commitment;
120mod proof_system;
121mod protocol;
122mod signature_scheme;
123
124pub use proof_system::AggregateVerificationKeyForConcatenation;
125pub use protocol::{
126    AggregateSignature, AggregateSignatureError, AggregateSignatureType, AggregateVerificationKey,
127    AggregationError, Clerk, ClosedKeyRegistration, Initializer, KeyRegistration, Parameters,
128    RegisterError, RegistrationEntry, RegistrationEntryForConcatenation, SignatureError, Signer,
129    SingleSignature, SingleSignatureWithRegisteredParty, VerificationKeyForConcatenation,
130    VerificationKeyProofOfPossessionForConcatenation,
131};
132pub use signature_scheme::BlsSignatureError;
133
134use blake2::{Blake2b, digest::consts::U32};
135use digest::{Digest, FixedOutput};
136use std::fmt::Debug;
137
138#[cfg(feature = "benchmark-internals")]
139pub use signature_scheme::{
140    BlsProofOfPossession, BlsSignature, BlsSigningKey, BlsVerificationKey,
141    BlsVerificationKeyProofOfPossession,
142};
143
144#[cfg(all(feature = "benchmark-internals", feature = "future_snark"))]
145pub use signature_scheme::{SchnorrSigningKey, SchnorrVerificationKey, UniqueSchnorrSignature};
146
147#[cfg(feature = "future_snark")]
148use hash::poseidon::MidnightPoseidonDigest;
149
150#[cfg(feature = "future_snark")]
151pub use protocol::VerificationKeyForSnark;
152
153/// The quantity of stake held by a party, represented as a `u64`.
154pub type Stake = u64;
155
156/// Quorum index for signatures.
157/// An aggregate signature (`StmMultiSig`) must have at least `k` unique indices.
158pub type LotteryIndex = u64;
159
160/// Index of the signer in the key registration
161pub type SignerIndex = u64;
162
163/// Mithril-stm error type
164pub type StmError = anyhow::Error;
165
166/// Mithril-stm result type
167pub type StmResult<T> = anyhow::Result<T, StmError>;
168
169#[cfg(feature = "future_snark")]
170// TODO: remove this allow dead_code directive when function is called or future_snark is activated
171#[allow(dead_code)]
172/// Target value type used in the lottery for snark proof system
173pub type LotteryTargetValue = crate::signature_scheme::BaseFieldElement;
174
175/// Trait defining the different hash types for different proof systems.
176pub trait MembershipDigest: Clone {
177    type ConcatenationHash: Digest + FixedOutput + Clone + Debug + Send + Sync;
178    #[cfg(feature = "future_snark")]
179    type SnarkHash: Digest + FixedOutput + Clone + Debug + Send + Sync;
180}
181
182/// Default Mithril Membership Digest
183#[derive(Clone, Debug, Default)]
184pub struct MithrilMembershipDigest {}
185
186/// Default implementation of MembershipDigest for Mithril
187/// TODO: `SnarkHash` will be changed with Poseidon. For now, we use `Blake2b<U64>` (`U64` is set
188/// for having something different than the `ConcatenationHash`) as a placeholder.
189impl MembershipDigest for MithrilMembershipDigest {
190    type ConcatenationHash = Blake2b<U32>;
191    #[cfg(feature = "future_snark")]
192    type SnarkHash = MidnightPoseidonDigest;
193}