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
use anyhow::{anyhow, Context};
use hex::ToHex;
use slog_scope::{info, trace, warn};
use std::path::PathBuf;
use thiserror::Error;

use mithril_common::crypto_helper::{KESPeriod, ProtocolInitializer};
use mithril_common::entities::{
    PartyId, ProtocolMessage, ProtocolParameters, SignerWithStake, SingleSignatures, Stake,
};
use mithril_common::protocol::SignerBuilder;
use mithril_common::{StdError, StdResult};

#[cfg(test)]
use mockall::automock;

/// This is responsible of creating new instances of ProtocolInitializer.
pub struct MithrilProtocolInitializerBuilder {}

impl MithrilProtocolInitializerBuilder {
    /// Create a ProtocolInitializer instance.
    pub fn build(
        stake: &Stake,
        protocol_parameters: &ProtocolParameters,
        kes_secret_key_path: Option<PathBuf>,
        kes_period: Option<KESPeriod>,
    ) -> StdResult<ProtocolInitializer> {
        let mut rng = rand_core::OsRng;
        let protocol_initializer = ProtocolInitializer::setup(
            protocol_parameters.to_owned().into(),
            kes_secret_key_path,
            kes_period,
            stake.to_owned(),
            &mut rng,
        )?;

        Ok(protocol_initializer)
    }
}

/// The SingleSigner is the structure responsible of issuing SingleSignatures.
#[cfg_attr(test, automock)]
pub trait SingleSigner: Sync + Send {
    /// Computes single signatures
    fn compute_single_signatures(
        &self,
        protocol_message: &ProtocolMessage,
        signers_with_stake: &[SignerWithStake],
        protocol_initializer: &ProtocolInitializer,
    ) -> StdResult<Option<SingleSignatures>>;

    /// Compute aggregate verification key from stake distribution
    fn compute_aggregate_verification_key(
        &self,
        signers_with_stake: &[SignerWithStake],
        protocol_initializer: &ProtocolInitializer,
    ) -> StdResult<Option<String>>;

    /// Get party id
    fn get_party_id(&self) -> PartyId;
}

/// SingleSigner error structure.
#[derive(Error, Debug)]
pub enum SingleSignerError {
    /// Cryptographic Signer creation error.
    #[error("the protocol signer creation failed")]
    ProtocolSignerCreationFailure(#[source] StdError),

    /// Signature Error
    #[error("Signature Error")]
    SignatureFailed(#[source] StdError),

    /// Avk computation Error
    #[error("Aggregate verification key computation Error")]
    AggregateVerificationKeyComputationFailed(#[source] StdError),
}

/// Implementation of the SingleSigner.
pub struct MithrilSingleSigner {
    party_id: PartyId,
}

impl MithrilSingleSigner {
    /// Create a new instance of the MithrilSingleSigner.
    pub fn new(party_id: PartyId) -> Self {
        Self { party_id }
    }
}

impl SingleSigner for MithrilSingleSigner {
    fn compute_single_signatures(
        &self,
        protocol_message: &ProtocolMessage,
        signers_with_stake: &[SignerWithStake],
        protocol_initializer: &ProtocolInitializer,
    ) -> StdResult<Option<SingleSignatures>> {
        let builder = SignerBuilder::new(
            signers_with_stake,
            &protocol_initializer.get_protocol_parameters().into(),
        )
        .with_context(|| "Mithril Single Signer can not build signer")
        .map_err(|e| SingleSignerError::ProtocolSignerCreationFailure(anyhow!(e)))?;
        info!("Signing protocol message"; "protocol_message" =>  #?protocol_message, "signed message" => protocol_message.compute_hash().encode_hex::<String>());
        let signatures = builder
            .restore_signer_from_initializer(self.party_id.clone(), protocol_initializer.clone())
            .with_context(|| {
                format!(
                    "Mithril Single Signer can not restore signer with party_id: '{}'",
                    self.party_id.clone()
                )
            })
            .map_err(|e| SingleSignerError::ProtocolSignerCreationFailure(anyhow!(e)))?
            .sign(protocol_message)
            .with_context(|| {
                format!(
                    "Mithril Single Signer can not sign protocol_message: '{:?}'",
                    protocol_message
                )
            })
            .map_err(SingleSignerError::SignatureFailed)?;

        match &signatures {
            Some(signature) => {
                trace!(
                    "Party #{}: lottery #{:?} won",
                    signature.party_id,
                    &signature.won_indexes
                );
            }
            None => {
                warn!("no signature computed, all lotteries were lost");
            }
        };

        Ok(signatures)
    }

    /// Compute aggregate verification key from stake distribution
    fn compute_aggregate_verification_key(
        &self,
        signers_with_stake: &[SignerWithStake],
        protocol_initializer: &ProtocolInitializer,
    ) -> StdResult<Option<String>> {
        let signer_builder = SignerBuilder::new(
            signers_with_stake,
            &protocol_initializer.get_protocol_parameters().into(),
        )
        .with_context(|| "Mithril Single Signer can not compute aggregate verification key")
        .map_err(SingleSignerError::AggregateVerificationKeyComputationFailed)?;

        let encoded_avk = signer_builder
            .compute_aggregate_verification_key()
            .to_json_hex()
            .with_context(|| {
                "Mithril Single Signer can not serialize aggregate verification key"
            })?;

        Ok(Some(encoded_avk))
    }

    /// Get party id
    fn get_party_id(&self) -> PartyId {
        self.party_id.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use mithril_common::{
        crypto_helper::ProtocolClerk, entities::ProtocolMessagePartKey,
        test_utils::MithrilFixtureBuilder,
    };

    #[test]
    fn compute_single_signature_success() {
        let snapshot_digest = "digest".to_string();
        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let signers_with_stake = fixture.signers_with_stake();
        let current_signer = &fixture.signers_fixture()[0];
        let single_signer = MithrilSingleSigner::new(current_signer.party_id());
        let clerk = ProtocolClerk::from_signer(&current_signer.protocol_signer);
        let avk = clerk.compute_avk();
        let mut protocol_message = ProtocolMessage::new();
        protocol_message.set_message_part(ProtocolMessagePartKey::SnapshotDigest, snapshot_digest);
        let expected_message = protocol_message.compute_hash().as_bytes().to_vec();

        let sign_result = single_signer
            .compute_single_signatures(
                &protocol_message,
                &signers_with_stake,
                &current_signer.protocol_initializer,
            )
            .expect("single signer should not fail")
            .expect("single signer should produce a signature here");

        let decoded_sig = sign_result.to_protocol_signature();
        assert!(
            decoded_sig
                .verify(
                    &fixture.protocol_parameters().into(),
                    &current_signer.protocol_signer.verification_key(),
                    &current_signer.protocol_signer.get_stake(),
                    &avk,
                    &expected_message
                )
                .is_ok(),
            "produced single signature should be valid"
        );
    }

    #[test]
    fn compute_aggregate_verification_key_success() {
        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let signers_with_stake = fixture.signers_with_stake();
        let current_signer = &fixture.signers_fixture()[0];
        let single_signer =
            MithrilSingleSigner::new(current_signer.signer_with_stake.party_id.to_owned());

        single_signer
            .compute_aggregate_verification_key(
                &signers_with_stake,
                &current_signer.protocol_initializer,
            )
            .expect("compute aggregate verification signature should not fail")
            .expect("aggregate verification signature should not be empty");
    }
}