mithril_common/protocol/
single_signer.rs

1use crate::{
2    StdResult,
3    crypto_helper::ProtocolSigner,
4    entities::{PartyId, SingleSignature},
5    protocol::ToMessage,
6};
7
8/// The SingleSigner is the structure responsible for issuing SingleSignatures.
9#[cfg_attr(test, derive(Debug))]
10pub struct SingleSigner {
11    party_id: PartyId,
12    protocol_signer: ProtocolSigner,
13}
14
15impl SingleSigner {
16    pub(super) fn new(party_id: PartyId, protocol_signer: ProtocolSigner) -> Self {
17        Self {
18            party_id,
19            protocol_signer,
20        }
21    }
22
23    /// Issue a single signature for the given message.
24    ///
25    /// If no lottery are won None will be returned.
26    pub fn sign<T: ToMessage>(&self, message: &T) -> StdResult<Option<SingleSignature>> {
27        let signed_message = message.to_message();
28        match self.protocol_signer.sign(signed_message.as_bytes()) {
29            Some(signature) => {
30                let won_indexes = signature.indexes.clone();
31
32                Ok(Some(SingleSignature::new(
33                    self.party_id.to_owned(),
34                    signature.into(),
35                    won_indexes,
36                )))
37            }
38            None => Ok(None),
39        }
40    }
41
42    /// Return the partyId associated with this Signer.
43    pub fn get_party_id(&self) -> PartyId {
44        self.party_id.clone()
45    }
46}
47
48#[cfg(test)]
49mod test {
50    use std::sync::Arc;
51
52    use crate::{
53        crypto_helper::{KesSigner, KesSignerStandard},
54        entities::ProtocolMessage,
55        protocol::SignerBuilder,
56        test_utils::MithrilFixtureBuilder,
57    };
58
59    #[test]
60    fn single_signer_should_be_able_to_issue_single_signature() {
61        let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
62        let signers = fixture.signers_fixture();
63        let signer = signers.first().unwrap();
64        let kes_signer = Some(Arc::new(KesSignerStandard::new(
65            signer.kes_secret_key_path().unwrap().to_path_buf(),
66            signer.operational_certificate_path().unwrap().to_path_buf(),
67        )) as Arc<dyn KesSigner>);
68
69        let (single_signer, _) = SignerBuilder::new(
70            &fixture.signers_with_stake(),
71            &fixture.protocol_parameters(),
72        )
73        .unwrap()
74        .build_test_single_signer(signer.signer_with_stake.clone(), kes_signer)
75        .unwrap();
76
77        let signature = single_signer
78            .sign(&ProtocolMessage::default())
79            .expect("Single signer should be able to issue single signature");
80
81        assert!(signature.is_some());
82    }
83}