mithril_aggregator/tools/
single_signature_authenticator.rs

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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use slog::{debug, Logger};
use std::sync::Arc;

use mithril_common::entities::{SingleSignatureAuthenticationStatus, SingleSignatures};
use mithril_common::logging::LoggerExtensions;
use mithril_common::StdResult;

use crate::MultiSigner;

/// Authenticates single signatures against a signed message.
pub struct SingleSignatureAuthenticator {
    multi_signer: Arc<dyn MultiSigner>,
    logger: Logger,
}

impl SingleSignatureAuthenticator {
    /// Creates a new `SingleSignatureAuthenticator`.
    pub fn new(multi_signer: Arc<dyn MultiSigner>, logger: Logger) -> Self {
        Self {
            multi_signer,
            logger: logger.new_with_component_name::<Self>(),
        }
    }

    /// Authenticates a single signature against a signed message.
    pub async fn authenticate(
        &self,
        single_signature: &mut SingleSignatures,
        signed_message: &str,
    ) -> StdResult<()> {
        let is_authenticated = match self
            .multi_signer
            .verify_single_signature(signed_message, single_signature)
            .await
        {
            Ok(()) => {
                debug!(
                    self.logger, "Single signature party authenticated for current stake distribution";
                    "party_id" => &single_signature.party_id,
                );
                true
            }
            Err(_error) => {
                // Signers may detect epoch changes before the aggregator and send
                // new signatures using the next epoch stake distribution
                if self
                    .multi_signer
                    .verify_single_signature_for_next_stake_distribution(
                        signed_message,
                        single_signature,
                    )
                    .await
                    .is_ok()
                {
                    debug!(
                        self.logger, "Single signature party authenticated for next stake distribution";
                        "party_id" => &single_signature.party_id,
                    );
                    true
                } else {
                    debug!(
                        self.logger, "Single signature party not authenticated";
                        "party_id" => &single_signature.party_id,
                    );
                    false
                }
            }
        };

        single_signature.authentication_status = if is_authenticated {
            SingleSignatureAuthenticationStatus::Authenticated
        } else {
            SingleSignatureAuthenticationStatus::Unauthenticated
        };

        Ok(())
    }
}

#[cfg(test)]
impl SingleSignatureAuthenticator {
    pub(crate) fn new_that_authenticate_everything() -> Self {
        let mut multi_signer = crate::multi_signer::MockMultiSigner::new();
        multi_signer
            .expect_verify_single_signature()
            .returning(|_, _| Ok(()));
        multi_signer
            .expect_verify_single_signature_for_next_stake_distribution()
            .returning(|_, _| Ok(()));

        Self {
            multi_signer: Arc::new(multi_signer),
            logger: crate::test_tools::TestLogger::stdout(),
        }
    }

    pub(crate) fn new_that_reject_everything() -> Self {
        let mut multi_signer = crate::multi_signer::MockMultiSigner::new();
        multi_signer
            .expect_verify_single_signature()
            .returning(|_, _| Err(anyhow::anyhow!("error")));
        multi_signer
            .expect_verify_single_signature_for_next_stake_distribution()
            .returning(|_, _| Err(anyhow::anyhow!("error")));

        Self {
            multi_signer: Arc::new(multi_signer),
            logger: crate::test_tools::TestLogger::stdout(),
        }
    }
}

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

    use crate::multi_signer::MockMultiSigner;
    use crate::test_tools::TestLogger;

    use super::*;

    fn mock_multi_signer(
        multi_signer_mock_config: impl FnOnce(&mut MockMultiSigner),
    ) -> Arc<MockMultiSigner> {
        let mut multi_signer = MockMultiSigner::new();
        multi_signer_mock_config(&mut multi_signer);
        Arc::new(multi_signer)
    }

    #[tokio::test]
    async fn single_signature_against_valid_signed_message_for_current_stake_distribution_is_authenticated(
    ) {
        let signed_message = "signed_message".to_string();
        let mut single_signature = SingleSignatures {
            authentication_status: SingleSignatureAuthenticationStatus::Unauthenticated,
            ..SingleSignatures::fake("party_id", &signed_message)
        };

        let authenticator = SingleSignatureAuthenticator::new(
            mock_multi_signer(|mock_config| {
                mock_config
                    .expect_verify_single_signature()
                    .returning(|_, _| Ok(()));
            }),
            TestLogger::stdout(),
        );

        authenticator
            .authenticate(&mut single_signature, &signed_message)
            .await
            .unwrap();

        assert_eq!(
            single_signature.authentication_status,
            SingleSignatureAuthenticationStatus::Authenticated
        );
    }

    #[tokio::test]
    async fn single_signature_against_valid_signed_message_for_next_stake_distribution_is_authenticated(
    ) {
        let signed_message = "signed_message".to_string();
        let mut single_signature = SingleSignatures {
            authentication_status: SingleSignatureAuthenticationStatus::Unauthenticated,
            ..SingleSignatures::fake("party_id", &signed_message)
        };

        let authenticator = SingleSignatureAuthenticator::new(
            mock_multi_signer(|mock_config| {
                mock_config
                    .expect_verify_single_signature()
                    .returning(|_, _| Err(anyhow!("error")));
                mock_config
                    .expect_verify_single_signature_for_next_stake_distribution()
                    .returning(|_, _| Ok(()));
            }),
            TestLogger::stdout(),
        );

        authenticator
            .authenticate(&mut single_signature, &signed_message)
            .await
            .unwrap();

        assert_eq!(
            single_signature.authentication_status,
            SingleSignatureAuthenticationStatus::Authenticated
        );
    }

    #[tokio::test]
    async fn single_signature_against_invalid_signed_message_for_current_and_next_stake_distribution_is_not_authenticated(
    ) {
        let signed_message = "signed_message".to_string();
        let mut single_signature = SingleSignatures {
            authentication_status: SingleSignatureAuthenticationStatus::Unauthenticated,
            ..SingleSignatures::fake("party_id", &signed_message)
        };

        let authenticator = SingleSignatureAuthenticator::new(
            mock_multi_signer(|mock_config| {
                mock_config
                    .expect_verify_single_signature()
                    .returning(|_, _| Err(anyhow!("verify_single_signature error")));
                mock_config
                    .expect_verify_single_signature_for_next_stake_distribution()
                    .returning(|_, _| {
                        Err(anyhow!(
                            "verify_single_signature_for_next_stake_distribution error"
                        ))
                    });
            }),
            TestLogger::stdout(),
        );

        authenticator
            .authenticate(&mut single_signature, &signed_message)
            .await
            .unwrap();

        assert_eq!(
            single_signature.authentication_status,
            SingleSignatureAuthenticationStatus::Unauthenticated
        );
    }

    #[tokio::test]
    async fn single_signature_previously_authenticated_but_fail_new_authentication_is_now_unauthenticated(
    ) {
        let signed_message = "signed_message".to_string();
        let mut single_signature = SingleSignatures {
            authentication_status: SingleSignatureAuthenticationStatus::Authenticated,
            ..SingleSignatures::fake("party_id", &signed_message)
        };

        let authenticator = SingleSignatureAuthenticator::new(
            mock_multi_signer(|mock_config| {
                mock_config
                    .expect_verify_single_signature()
                    .returning(|_, _| Err(anyhow!("verify_single_signature error")));
                mock_config
                    .expect_verify_single_signature_for_next_stake_distribution()
                    .returning(|_, _| {
                        Err(anyhow!(
                            "verify_single_signature_for_next_stake_distribution error"
                        ))
                    });
            }),
            TestLogger::stdout(),
        );

        authenticator
            .authenticate(&mut single_signature, &signed_message)
            .await
            .unwrap();

        assert_eq!(
            single_signature.authentication_status,
            SingleSignatureAuthenticationStatus::Unauthenticated
        );
    }
}