mithril_common/protocol/
multi_signer.rs

1use anyhow::{Context, anyhow};
2use mithril_stm::Parameters;
3
4use crate::{
5    StdResult,
6    crypto_helper::{
7        ProtocolAggregateVerificationKey, ProtocolAggregationError, ProtocolClerk,
8        ProtocolMultiSignature,
9    },
10    entities::SingleSignature,
11    protocol::ToMessage,
12};
13
14/// MultiSigner is the cryptographic engine in charge of producing multi-signatures from individual signatures
15pub struct MultiSigner {
16    protocol_clerk: ProtocolClerk,
17    protocol_parameters: Parameters,
18}
19
20impl MultiSigner {
21    pub(super) fn new(protocol_clerk: ProtocolClerk, protocol_parameters: Parameters) -> Self {
22        Self {
23            protocol_clerk,
24            protocol_parameters,
25        }
26    }
27
28    /// Aggregate the given single signatures into a multi-signature
29    pub fn aggregate_single_signatures<T: ToMessage>(
30        &self,
31        single_signatures: &[SingleSignature],
32        message: &T,
33    ) -> Result<ProtocolMultiSignature, ProtocolAggregationError> {
34        let protocol_signatures: Vec<_> = single_signatures
35            .iter()
36            .map(|single_signature| single_signature.to_protocol_signature())
37            .collect();
38
39        self.protocol_clerk
40            .aggregate(&protocol_signatures, message.to_message().as_bytes())
41            .map(|multi_sig| multi_sig.into())
42    }
43
44    /// Compute aggregate verification key from stake distribution
45    pub fn compute_aggregate_verification_key(&self) -> ProtocolAggregateVerificationKey {
46        self.protocol_clerk.compute_avk().into()
47    }
48
49    /// Verify a single signature
50    pub fn verify_single_signature<T: ToMessage>(
51        &self,
52        message: &T,
53        single_signature: &SingleSignature,
54    ) -> StdResult<()> {
55        let protocol_signature = single_signature.to_protocol_signature();
56
57        let avk = self.compute_aggregate_verification_key();
58
59        // If there is no reg_party, then we simply received a signature from a non-registered
60        // party, and we can ignore the request.
61        let (vk, stake) = self
62            .protocol_clerk
63            .get_reg_party(&protocol_signature.signer_index)
64            .ok_or_else(|| {
65                anyhow!(format!(
66                    "Unregistered party: '{}'",
67                    single_signature.party_id
68                ))
69            })?;
70
71        protocol_signature
72            .verify(
73                &self.protocol_parameters,
74                &vk,
75                &stake,
76                &avk,
77                message.to_message().as_bytes(),
78            )
79            .with_context(|| {
80                format!(
81                    "Invalid signature for party: '{}'",
82                    single_signature.party_id
83                )
84            })?;
85
86        Ok(())
87    }
88}
89
90#[cfg(test)]
91mod test {
92    use mithril_stm::StmSignatureError;
93
94    use crate::{
95        entities::{ProtocolMessage, ProtocolMessagePartKey, ProtocolParameters},
96        protocol::SignerBuilder,
97        test_utils::fake_keys,
98        test_utils::{MithrilFixture, MithrilFixtureBuilder, StakeDistributionGenerationMethod},
99    };
100
101    use super::*;
102
103    fn build_multi_signer(fixture: &MithrilFixture) -> MultiSigner {
104        SignerBuilder::new(
105            &fixture.signers_with_stake(),
106            &fixture.protocol_parameters(),
107        )
108        .unwrap()
109        .build_multi_signer()
110    }
111
112    #[test]
113    fn cant_aggregate_if_signatures_list_empty() {
114        let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
115        let multi_signer = build_multi_signer(&fixture);
116        let message = ProtocolMessage::default();
117
118        let error = multi_signer.aggregate_single_signatures(&[], &message).expect_err(
119            "Multi-signature should not be created with an empty single signatures list",
120        );
121
122        assert!(
123            matches!(error, ProtocolAggregationError::NotEnoughSignatures(_, _)),
124            "Expected ProtocolAggregationError::NotEnoughSignatures, got: {error:?}"
125        )
126    }
127
128    #[test]
129    fn can_aggregate_if_valid_signatures_and_quorum_reached() {
130        let fixture = MithrilFixtureBuilder::default().with_signers(10).build();
131        let multi_signer = build_multi_signer(&fixture);
132        let message = ProtocolMessage::default();
133        let signatures: Vec<SingleSignature> = fixture
134            .signers_fixture()
135            .iter()
136            .map(|s| s.sign(&message).unwrap())
137            .collect();
138
139        multi_signer
140            .aggregate_single_signatures(&signatures, &message)
141            .expect("Multi-signature should be created");
142    }
143
144    #[test]
145    fn can_aggregate_even_with_one_invalid_signature_if_the_other_are_enough_for_the_quorum() {
146        let fixture = MithrilFixtureBuilder::default()
147            .with_signers(10)
148            .with_stake_distribution(StakeDistributionGenerationMethod::Uniform(20))
149            .with_protocol_parameters(ProtocolParameters::new(6, 200, 1.0))
150            .build();
151        let multi_signer = build_multi_signer(&fixture);
152        let message = ProtocolMessage::default();
153        let mut signatures: Vec<SingleSignature> = fixture
154            .signers_fixture()
155            .iter()
156            .map(|s| s.sign(&message).unwrap())
157            .collect();
158        signatures[4].signature = fake_keys::single_signature()[3].try_into().unwrap();
159
160        multi_signer
161            .aggregate_single_signatures(&signatures, &message)
162            .expect("Multi-signature should be created even with one invalid signature");
163    }
164
165    #[test]
166    fn verify_single_signature_fail_if_signature_signer_isnt_in_the_registered_parties() {
167        let multi_signer = build_multi_signer(
168            &MithrilFixtureBuilder::default()
169                .with_signers(1)
170                .with_stake_distribution(StakeDistributionGenerationMethod::RandomDistribution {
171                    seed: [3u8; 32],
172                    min_stake: 1,
173                })
174                .build(),
175        );
176        let fixture = MithrilFixtureBuilder::default().with_signers(1).build();
177        let message = ProtocolMessage::default();
178        let single_signature = fixture.signers_fixture().last().unwrap().sign(&message).unwrap();
179
180        // Will fail because the single signature was issued by a signer from a stake distribution
181        // that is not the one used by the multi-signer.
182        let error = multi_signer
183            .verify_single_signature(&message, &single_signature)
184            .expect_err(
185                "Verify single signature should fail if the signer isn't in the registered parties",
186            );
187
188        match error.downcast_ref::<StmSignatureError>() {
189            Some(StmSignatureError::SignatureInvalid(_)) => (),
190            _ => panic!("Expected an SignatureInvalid error, got: {error:?}"),
191        }
192    }
193
194    #[test]
195    fn verify_single_signature_fail_if_signature_signed_message_isnt_the_given_one() {
196        let fixture = MithrilFixtureBuilder::default().with_signers(1).build();
197        let multi_signer = build_multi_signer(&fixture);
198        let mut signed_message = ProtocolMessage::default();
199        signed_message.set_message_part(
200            ProtocolMessagePartKey::SnapshotDigest,
201            "a_digest".to_string(),
202        );
203        let single_signature = fixture
204            .signers_fixture()
205            .first()
206            .unwrap()
207            .sign(&signed_message)
208            .unwrap();
209
210        let error = multi_signer
211            .verify_single_signature(&ProtocolMessage::default(), &single_signature)
212            .expect_err("Verify single signature should fail");
213
214        match error.downcast_ref::<StmSignatureError>() {
215            Some(StmSignatureError::SignatureInvalid(_)) => (),
216            _ => panic!("Expected an SignatureInvalid error, got: {error:?}"),
217        }
218    }
219
220    #[test]
221    fn can_verify_valid_single_signature() {
222        let fixture = MithrilFixtureBuilder::default().with_signers(1).build();
223        let multi_signer = build_multi_signer(&fixture);
224        let message = ProtocolMessage::default();
225        let single_signature = fixture.signers_fixture().first().unwrap().sign(&message).unwrap();
226
227        multi_signer
228            .verify_single_signature(&message, &single_signature)
229            .expect("Verify single signature should succeed");
230    }
231}