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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! A module used to validate the Certificate Chain created by an aggregator
//!
use anyhow::{anyhow, Context};
use async_trait::async_trait;
use hex::ToHex;
use slog::{debug, Logger};
use std::sync::Arc;
use thiserror::Error;

use super::CertificateRetriever;
use crate::crypto_helper::{
    ProtocolAggregateVerificationKey, ProtocolGenesisError, ProtocolGenesisVerificationKey,
    ProtocolMultiSignature,
};
use crate::entities::{
    Certificate, CertificateSignature, ProtocolMessage, ProtocolMessagePartKey, ProtocolParameters,
};
use crate::StdResult;

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

/// [CertificateVerifier] related errors.
#[derive(Error, Debug)]
pub enum CertificateVerifierError {
    /// Error raised when the multi signatures verification fails.
    #[error("multi signature verification failed: '{0}'")]
    VerifyMultiSignature(String),

    /// Error raised when the Genesis Signature stored in a [Certificate] is invalid.
    #[error("certificate genesis error")]
    CertificateGenesis(#[from] ProtocolGenesisError),

    /// Error raised when the hash stored in a [Certificate] doesn't match a recomputed hash.
    #[error("certificate hash unmatch error")]
    CertificateHashUnmatch,

    /// Error raised when validating the certificate chain if a previous [Certificate] hash isn't
    /// equal to the current certificate `previous_hash`.
    #[error("certificate chain previous hash unmatch error")]
    CertificateChainPreviousHashUnmatch,

    /// Error raised when validating the certificate chain if the current [Certificate]
    /// `aggregate_verification_key` doesn't match the previous `aggregate_verification_key` (if
    /// the certificates are on the same epoch) or the previous `next_aggregate_verification_key`
    /// (if the certificates are on different epoch).
    #[error("certificate chain AVK unmatch error")]
    CertificateChainAVKUnmatch,

    /// Error raised when validating the certificate chain if the chain loops.
    #[error("certificate chain infinite loop error")]
    CertificateChainInfiniteLoop,

    /// Error raised when [CertificateVerifier::verify_genesis_certificate] was called with a
    /// certificate that's not a genesis certificate.
    #[error("can't validate genesis certificate: given certificate isn't a genesis certificate")]
    InvalidGenesisCertificateProvided,
}

/// CertificateVerifier is the cryptographic engine in charge of verifying multi signatures and
/// [certificates](Certificate)
#[cfg_attr(test, automock)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
pub trait CertificateVerifier: Send + Sync {
    /// Verify Genesis certificate
    async fn verify_genesis_certificate(
        &self,
        genesis_certificate: &Certificate,
        genesis_verification_key: &ProtocolGenesisVerificationKey,
    ) -> StdResult<()>;

    /// Verify if a Certificate is valid and returns the previous Certificate in the chain if exists
    /// Step 1: Check if the hash is valid (i.e. the Certificate has not been tampered by modifying its content)
    /// Step 2: Check that the multi signature is valid if it is a Standard Certificate (i.e verification of the Mithril multi signature)
    /// Step 3: Check that the aggregate verification key of the Certificate is registered in the previous Certificate in the chain
    async fn verify_certificate(
        &self,
        certificate: &Certificate,
        genesis_verification_key: &ProtocolGenesisVerificationKey,
    ) -> StdResult<Option<Certificate>>;

    /// Verify that the Certificate Chain associated to a Certificate is valid
    /// TODO: see if we can borrow the certificate instead.
    async fn verify_certificate_chain(
        &self,
        certificate: Certificate,
        genesis_verification_key: &ProtocolGenesisVerificationKey,
    ) -> StdResult<()> {
        let mut certificate = certificate;
        while let Some(previous_certificate) = self
            .verify_certificate(&certificate, genesis_verification_key)
            .await?
        {
            certificate = previous_certificate;
        }

        Ok(())
    }

    /// still a dirty hack to mock the protocol message
    /// verify that the protocol message is equal to the signed message of the certificate.
    /// TODO: Remove this method.
    fn verify_protocol_message(
        &self,
        protocol_message: &ProtocolMessage,
        certificate: &Certificate,
    ) -> bool {
        protocol_message.compute_hash() == certificate.signed_message
    }
}

/// MithrilCertificateVerifier is an implementation of the CertificateVerifier
pub struct MithrilCertificateVerifier {
    /// The logger where the logs should be written
    logger: Logger,
    certificate_retriever: Arc<dyn CertificateRetriever>,
}

impl MithrilCertificateVerifier {
    /// MithrilCertificateVerifier factory
    pub fn new(logger: Logger, certificate_retriever: Arc<dyn CertificateRetriever>) -> Self {
        debug!(logger, "New MithrilCertificateVerifier created");
        Self {
            logger,
            certificate_retriever,
        }
    }

    /// Verify a multi signature
    fn verify_multi_signature(
        &self,
        message: &[u8],
        multi_signature: &ProtocolMultiSignature,
        aggregate_verification_key: &ProtocolAggregateVerificationKey,
        protocol_parameters: &ProtocolParameters,
    ) -> Result<(), CertificateVerifierError> {
        debug!(
            self.logger,
            "Verify multi signature for {:?}",
            message.encode_hex::<String>()
        );

        multi_signature
            .verify(
                message,
                aggregate_verification_key,
                &protocol_parameters.to_owned().into(),
            )
            .map_err(|e| CertificateVerifierError::VerifyMultiSignature(e.to_string()))
    }

    /// Verify Standard certificate
    async fn verify_standard_certificate(
        &self,
        certificate: &Certificate,
        signature: &ProtocolMultiSignature,
    ) -> StdResult<Option<Certificate>> {
        self.verify_multi_signature(
            certificate.signed_message.as_bytes(),
            signature,
            &certificate.aggregate_verification_key,
            &certificate.metadata.protocol_parameters,
        )?;
        let previous_certificate = self
            .certificate_retriever
            .get_certificate_details(&certificate.previous_hash)
            .await
            .map_err(|e| anyhow!(e))
            .with_context(|| "Can not retrieve previous certificate during verification")?;

        if previous_certificate.hash != certificate.previous_hash {
            return Err(anyhow!(
                CertificateVerifierError::CertificateChainPreviousHashUnmatch
            ));
        }

        let current_certificate_avk: String = certificate
            .aggregate_verification_key
            .to_json_hex()
            .with_context(|| {
                format!(
                    "avk to string conversion error for certificate: `{}`",
                    certificate.hash
                )
            })?;

        let previous_certificate_avk: String = previous_certificate
            .aggregate_verification_key
            .to_json_hex()
            .with_context(|| {
                format!(
                    "avk to string conversion error for previous certificate: `{}`",
                    certificate.hash
                )
            })?;

        let valid_certificate_has_different_epoch_as_previous =
            |next_aggregate_verification_key: &str| -> bool {
                next_aggregate_verification_key == current_certificate_avk
                    && previous_certificate.epoch != certificate.epoch
            };
        let valid_certificate_has_same_epoch_as_previous = || -> bool {
            previous_certificate_avk == current_certificate_avk
                && previous_certificate.epoch == certificate.epoch
        };

        match previous_certificate
            .protocol_message
            .get_message_part(&ProtocolMessagePartKey::NextAggregateVerificationKey)
        {
            Some(next_aggregate_verification_key)
                if valid_certificate_has_different_epoch_as_previous(
                    next_aggregate_verification_key,
                ) =>
            {
                Ok(Some(previous_certificate.to_owned()))
            }
            Some(_) if valid_certificate_has_same_epoch_as_previous() => {
                Ok(Some(previous_certificate.to_owned()))
            }
            None => Ok(None),
            _ => {
                debug!(
                    self.logger,
                    "Previous certificate {:#?}", previous_certificate
                );
                Err(anyhow!(
                    CertificateVerifierError::CertificateChainAVKUnmatch
                ))
            }
        }
    }
}

#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl CertificateVerifier for MithrilCertificateVerifier {
    /// Verify Genesis certificate
    async fn verify_genesis_certificate(
        &self,
        genesis_certificate: &Certificate,
        genesis_verification_key: &ProtocolGenesisVerificationKey,
    ) -> StdResult<()> {
        let genesis_signature = match &genesis_certificate.signature {
            CertificateSignature::GenesisSignature(signature) => Ok(signature),
            _ => Err(CertificateVerifierError::InvalidGenesisCertificateProvided),
        }?;

        genesis_verification_key
            .verify(
                genesis_certificate.signed_message.as_bytes(),
                genesis_signature,
            )
            .with_context(|| "Certificate verifier failed verifying a genesis certificate")?;

        Ok(())
    }

    /// Verify a certificate
    async fn verify_certificate(
        &self,
        certificate: &Certificate,
        genesis_verification_key: &ProtocolGenesisVerificationKey,
    ) -> StdResult<Option<Certificate>> {
        debug!(
            self.logger,
            "Verifying certificate";
            "certificate_hash" => &certificate.hash,
            "certificate_previous_hash" => &certificate.previous_hash,
            "certificate_epoch" => ?certificate.epoch,
            "certificate_signed_entity_type" => ?certificate.signed_entity_type(),
        );

        certificate
            .hash
            .eq(&certificate.compute_hash())
            .then(|| certificate.hash.clone())
            .ok_or(CertificateVerifierError::CertificateHashUnmatch)?;

        if certificate.is_chaining_to_itself() {
            Err(anyhow!(
                CertificateVerifierError::CertificateChainInfiniteLoop
            ))
        } else {
            match &certificate.signature {
                CertificateSignature::GenesisSignature(_signature) => {
                    self.verify_genesis_certificate(certificate, genesis_verification_key)
                        .await?;
                    Ok(None)
                }
                CertificateSignature::MultiSignature(_, signature) => {
                    self.verify_standard_certificate(certificate, signature)
                        .await
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use async_trait::async_trait;
    use mockall::mock;
    use slog_scope;

    use super::CertificateRetriever;
    use super::*;

    use crate::certificate_chain::CertificateRetrieverError;
    use crate::crypto_helper::{tests_setup::*, ProtocolClerk};
    use crate::test_utils::MithrilFixtureBuilder;

    mock! {
        pub CertificateRetrieverImpl { }

        #[async_trait]
        impl CertificateRetriever for CertificateRetrieverImpl {

            async fn get_certificate_details(
                &self,
                certificate_hash: &str,
            ) -> Result<Certificate, CertificateRetrieverError>;
        }
    }

    #[test]
    fn test_verify_multi_signature_ok() {
        let protocol_parameters = setup_protocol_parameters();
        let fixture = MithrilFixtureBuilder::default()
            .with_signers(5)
            .with_protocol_parameters(protocol_parameters.into())
            .build();
        let signers = fixture.signers_fixture();
        let message_hash = setup_message().compute_hash().as_bytes().to_vec();

        let single_signatures = signers
            .iter()
            .filter_map(|s| s.protocol_signer.sign(&message_hash))
            .collect::<Vec<_>>();

        let first_signer = &signers[0].protocol_signer;
        let clerk = ProtocolClerk::from_signer(first_signer);
        let aggregate_verification_key = clerk.compute_avk().into();
        let multi_signature = clerk
            .aggregate(&single_signatures, &message_hash)
            .unwrap()
            .into();

        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(MockCertificateRetrieverImpl::new()),
        );
        let message_tampered = message_hash[1..].to_vec();
        assert!(
            verifier
                .verify_multi_signature(
                    &message_tampered,
                    &multi_signature,
                    &aggregate_verification_key,
                    &fixture.protocol_parameters(),
                )
                .is_err(),
            "multi signature verification should have failed"
        );
        verifier
            .verify_multi_signature(
                &message_hash,
                &multi_signature,
                &aggregate_verification_key,
                &fixture.protocol_parameters(),
            )
            .expect("multi signature verification should have succeeded");
    }

    #[tokio::test]
    async fn test_verify_certificate_ok_different_epochs() {
        let total_certificates = 5;
        let certificates_per_epoch = 1;
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let fake_certificate1 = fake_certificates[0].clone();
        let fake_certificate2 = fake_certificates[1].clone();
        let mut mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        mock_certificate_retriever
            .expect_get_certificate_details()
            .returning(move |_| Ok(fake_certificate2.clone()))
            .times(1);
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let verify = verifier
            .verify_certificate(&fake_certificate1, &genesis_verifier.to_verification_key())
            .await;
        verify.expect("unexpected error");
    }

    #[tokio::test]
    async fn test_verify_certificate_ok_same_epoch() {
        let total_certificates = 5;
        let certificates_per_epoch = 2;
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let fake_certificate1 = fake_certificates[0].clone();
        let fake_certificate2 = fake_certificates[1].clone();
        let mut mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        mock_certificate_retriever
            .expect_get_certificate_details()
            .returning(move |_| Ok(fake_certificate2.clone()))
            .times(1);
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let verify = verifier
            .verify_certificate(&fake_certificate1, &genesis_verifier.to_verification_key())
            .await;
        verify.expect("unexpected error");
    }

    #[tokio::test]
    async fn test_verify_certificate_ko_certificate_chain_previous_hash_unmatch() {
        let total_certificates = 5;
        let certificates_per_epoch = 1;
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let fake_certificate1 = fake_certificates[0].clone();
        let mut fake_certificate2 = fake_certificates[1].clone();
        fake_certificate2.previous_hash = "another-hash".to_string();
        fake_certificate2.hash = fake_certificate2.compute_hash();
        let mut mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        mock_certificate_retriever
            .expect_get_certificate_details()
            .returning(move |_| Ok(fake_certificate2.clone()))
            .times(1);
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let error = verifier
            .verify_certificate(&fake_certificate1, &genesis_verifier.to_verification_key())
            .await
            .expect_err("verify_certificate_chain should fail");
        let error = error
            .downcast_ref::<CertificateVerifierError>()
            .expect("Can not downcast to `CertificateVerifierError`.");

        assert!(
            matches!(
                error,
                CertificateVerifierError::CertificateChainPreviousHashUnmatch
            ),
            "unexpected error type: {error:?}"
        );
    }

    #[tokio::test]
    async fn test_verify_certificate_ko_certificate_chain_avk_unmatch() {
        let total_certificates = 5;
        let certificates_per_epoch = 1;
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let mut fake_certificate1 = fake_certificates[0].clone();
        let mut fake_certificate2 = fake_certificates[1].clone();
        fake_certificate2.protocol_message.set_message_part(
            ProtocolMessagePartKey::NextAggregateVerificationKey,
            "another-avk".to_string(),
        );
        fake_certificate2.hash = fake_certificate2.compute_hash();
        fake_certificate1
            .previous_hash
            .clone_from(&fake_certificate2.hash);
        fake_certificate1.hash = fake_certificate1.compute_hash();
        let mut mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        mock_certificate_retriever
            .expect_get_certificate_details()
            .returning(move |_| Ok(fake_certificate2.clone()))
            .times(1);
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let error = verifier
            .verify_certificate(&fake_certificate1, &genesis_verifier.to_verification_key())
            .await
            .expect_err("verify_certificate_chain should fail");
        let error = error
            .downcast_ref::<CertificateVerifierError>()
            .expect("Can not downcast to `CertificateVerifierError`.");

        assert!(
            matches!(error, CertificateVerifierError::CertificateChainAVKUnmatch),
            "unexpected error type: {error:?}"
        );
    }

    #[tokio::test]
    async fn test_verify_certificate_ko_certificate_hash_not_matching() {
        let total_certificates = 5;
        let certificates_per_epoch = 1;
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let mut fake_certificate1 = fake_certificates[0].clone();
        fake_certificate1.hash = "another-hash".to_string();
        let mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let error = verifier
            .verify_certificate(&fake_certificate1, &genesis_verifier.to_verification_key())
            .await
            .expect_err("verify_certificate_chain should fail");
        let error = error
            .downcast_ref::<CertificateVerifierError>()
            .expect("Can not downcast to `CertificateVerifierError`.");

        assert!(
            matches!(error, CertificateVerifierError::CertificateHashUnmatch),
            "unexpected error type: {error:?}"
        );
    }

    #[tokio::test]
    async fn test_verify_certificate_chain_ok() {
        let total_certificates = 15;
        let certificates_per_epoch = 2;
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let mut mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        let certificate_to_verify = fake_certificates[0].clone();
        for fake_certificate in fake_certificates.into_iter().skip(1) {
            mock_certificate_retriever
                .expect_get_certificate_details()
                .returning(move |_| Ok(fake_certificate.clone()))
                .times(1);
        }
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let verify = verifier
            .verify_certificate_chain(
                certificate_to_verify,
                &genesis_verifier.to_verification_key(),
            )
            .await;
        verify.expect("unexpected error");
    }

    #[tokio::test]
    async fn test_verify_certificate_chain_ko() {
        let total_certificates = 15;
        let certificates_per_epoch = 2;
        let (mut fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let index_certificate_fail = (total_certificates / 2) as usize;
        fake_certificates[index_certificate_fail].hash = "tampered-hash".to_string();
        let mut mock_certificate_retriever = MockCertificateRetrieverImpl::new();
        let certificate_to_verify = fake_certificates[0].clone();
        for fake_certificate in fake_certificates
            .into_iter()
            .skip(1)
            .take(index_certificate_fail)
        {
            mock_certificate_retriever
                .expect_get_certificate_details()
                .returning(move |_| Ok(fake_certificate.clone()))
                .times(1);
        }
        let verifier = MithrilCertificateVerifier::new(
            slog_scope::logger(),
            Arc::new(mock_certificate_retriever),
        );
        let error = verifier
            .verify_certificate_chain(
                certificate_to_verify,
                &genesis_verifier.to_verification_key(),
            )
            .await
            .expect_err("verify_certificate_chain should fail");
        let error = error
            .downcast_ref::<CertificateVerifierError>()
            .expect("Can not downcast to `CertificateVerifierError`.");

        assert!(
            matches!(
                error,
                CertificateVerifierError::CertificateChainPreviousHashUnmatch
            ),
            "unexpected error type: {error:?}"
        );
    }
}