mithril_common/protocol/
single_signer.rs

1use crate::{
2    crypto_helper::ProtocolSigner,
3    entities::{PartyId, SingleSignatures},
4    protocol::ToMessage,
5    StdResult,
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<SingleSignatures>> {
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(SingleSignatures::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 crate::{
51        entities::ProtocolMessage, protocol::SignerBuilder, test_utils::MithrilFixtureBuilder,
52    };
53
54    #[test]
55    fn single_signer_should_be_able_to_issue_single_signature() {
56        let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
57        let signers = fixture.signers_fixture();
58        let signer = signers.first().unwrap();
59
60        let (single_signer, _) = SignerBuilder::new(
61            &fixture.signers_with_stake(),
62            &fixture.protocol_parameters(),
63        )
64        .unwrap()
65        .build_test_single_signer(
66            signer.signer_with_stake.clone(),
67            signer.kes_secret_key_path(),
68        )
69        .unwrap();
70
71        let signature = single_signer
72            .sign(&ProtocolMessage::default())
73            .expect("Single signer should be able to issue single signature");
74
75        assert!(signature.is_some());
76    }
77}