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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! 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, ProtocolMessagePartKey, ProtocolParameters,
};
use crate::logging::LoggerExtensions;
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]
    /// `signed_message` doesn't match the hash of the `protocol_message` of the current certificate
    #[error("certificate protocol message unmatch error")]
    CertificateProtocolMessageUnmatch,

    /// Error raised when validating the certificate chain if the current [Certificate]
    /// `aggregate_verification_key` doesn't match the signed `next_aggregate_verification_key` of the previous certificate
    /// (if the certificates are on different epoch) or the `aggregate_verification_key` of the previous certificate
    /// (if the certificates are on the same 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,

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

/// 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 Standard certificate
    async fn verify_standard_certificate(
        &self,
        certificate: &Certificate,
        previous_certificate: &Certificate,
    ) -> StdResult<()>;

    /// Verify if a Certificate is valid and returns the previous Certificate in the chain if exists
    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
    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(())
    }
}

/// MithrilCertificateVerifier is an implementation of the CertificateVerifier
pub struct MithrilCertificateVerifier {
    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: logger.new_with_component_name::<Self>(),
            certificate_retriever,
        }
    }

    async fn fetch_previous_certificate(
        &self,
        certificate: &Certificate,
    ) -> StdResult<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")
    }

    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()))
    }

    fn verify_is_not_in_infinite_loop(&self, certificate: &Certificate) -> StdResult<()> {
        if certificate.is_chaining_to_itself() {
            return Err(anyhow!(
                CertificateVerifierError::CertificateChainInfiniteLoop
            ));
        }

        Ok(())
    }

    fn verify_hash_matches_content(&self, certificate: &Certificate) -> StdResult<()> {
        if certificate.compute_hash() != certificate.hash {
            return Err(anyhow!(CertificateVerifierError::CertificateHashUnmatch));
        }

        Ok(())
    }

    fn verify_previous_hash_matches_previous_certificate_hash(
        &self,
        certificate: &Certificate,
        previous_certificate: &Certificate,
    ) -> StdResult<()> {
        if previous_certificate.hash != certificate.previous_hash {
            return Err(anyhow!(
                CertificateVerifierError::CertificateChainPreviousHashUnmatch
            ));
        }

        Ok(())
    }

    fn verify_signed_message_matches_hashed_protocol_message(
        &self,
        certificate: &Certificate,
    ) -> StdResult<()> {
        if certificate.protocol_message.compute_hash() != certificate.signed_message {
            return Err(anyhow!(
                CertificateVerifierError::CertificateProtocolMessageUnmatch
            ));
        }

        Ok(())
    }
    fn verify_aggregate_verification_key_chaining(
        &self,
        certificate: &Certificate,
        previous_certificate: &Certificate,
    ) -> StdResult<()> {
        let previous_certificate_has_same_epoch = previous_certificate.epoch == certificate.epoch;
        let certificate_has_valid_aggregate_verification_key =
            if previous_certificate_has_same_epoch {
                previous_certificate.aggregate_verification_key
                    == certificate.aggregate_verification_key
            } else {
                match &previous_certificate
                    .protocol_message
                    .get_message_part(&ProtocolMessagePartKey::NextAggregateVerificationKey)
                {
                    Some(previous_certificate_next_aggregate_verification_key) => {
                        **previous_certificate_next_aggregate_verification_key
                            == certificate
                                .aggregate_verification_key
                                .to_json_hex()
                                .with_context(|| {
                                    format!(
                                    "aggregate verification key to string conversion error for certificate: `{}`",
                                    certificate.hash
                                )
                                })?
                    }
                    None => false,
                }
            };
        if !certificate_has_valid_aggregate_verification_key {
            debug!(
                self.logger,
                "Previous certificate {:#?}", previous_certificate
            );
            return Err(anyhow!(
                CertificateVerifierError::CertificateChainAVKUnmatch
            ));
        }

        Ok(())
    }
}

#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl CertificateVerifier for MithrilCertificateVerifier {
    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),
        }?;
        self.verify_hash_matches_content(genesis_certificate)?;
        self.verify_signed_message_matches_hashed_protocol_message(genesis_certificate)?;
        genesis_verification_key
            .verify(
                genesis_certificate.signed_message.as_bytes(),
                genesis_signature,
            )
            .with_context(|| "Certificate verifier failed verifying a genesis certificate")?;
        Ok(())
    }

    async fn verify_standard_certificate(
        &self,
        certificate: &Certificate,
        previous_certificate: &Certificate,
    ) -> StdResult<()> {
        let multi_signature = match &certificate.signature {
            CertificateSignature::MultiSignature(_, signature) => Ok(signature),
            _ => Err(CertificateVerifierError::InvalidStandardCertificateProvided),
        }?;
        self.verify_is_not_in_infinite_loop(certificate)?;
        self.verify_hash_matches_content(certificate)?;
        self.verify_signed_message_matches_hashed_protocol_message(certificate)?;
        self.verify_multi_signature(
            certificate.signed_message.as_bytes(),
            multi_signature,
            &certificate.aggregate_verification_key,
            &certificate.metadata.protocol_parameters,
        )?;
        self.verify_previous_hash_matches_previous_certificate_hash(
            certificate,
            previous_certificate,
        )?;
        self.verify_aggregate_verification_key_chaining(certificate, previous_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(),
        );

        match &certificate.signature {
            CertificateSignature::GenesisSignature(_) => {
                self.verify_genesis_certificate(certificate, genesis_verification_key)
                    .await?;

                Ok(None)
            }
            CertificateSignature::MultiSignature(_, _) => {
                let previous_certificate = self.fetch_previous_certificate(certificate).await?;
                self.verify_standard_certificate(certificate, &previous_certificate)
                    .await?;

                Ok(Some(previous_certificate))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use async_trait::async_trait;
    use mockall::mock;
    use tokio::sync::Mutex;

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

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

    macro_rules! assert_error_matches {
        ( $expected_error:path, $error:expr ) => {{
            let error = $error
                .downcast_ref::<CertificateVerifierError>()
                .expect("Can not downcast to `CertificateVerifierError`.");
            let expected_error = $expected_error;

            assert!(
                matches!(error, $expected_error),
                "unexpected error type: got {error:?}, want {expected_error:?}"
            );
        }};
    }

    mock! {
        pub CertificateRetrieverImpl { }

        #[async_trait]
        impl CertificateRetriever for CertificateRetrieverImpl {

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

    struct MockDependencyInjector {
        mock_certificate_retriever: MockCertificateRetrieverImpl,
    }

    impl MockDependencyInjector {
        fn new() -> MockDependencyInjector {
            MockDependencyInjector {
                mock_certificate_retriever: MockCertificateRetrieverImpl::new(),
            }
        }

        fn build_certificate_verifier(self) -> MithrilCertificateVerifier {
            MithrilCertificateVerifier::new(
                TestLogger::stdout(),
                Arc::new(self.mock_certificate_retriever),
            )
        }
    }

    #[test]
    fn verify_multi_signature_success() {
        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(
            TestLogger::stdout(),
            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 verify_genesis_certificate_success() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let genesis_certificate = fake_certificates.last().unwrap().clone();

        let verify = verifier
            .verify_genesis_certificate(
                &genesis_certificate,
                &genesis_verifier.to_verification_key(),
            )
            .await;

        verify.expect("verify_genesis_certificate should not fail");
    }

    #[tokio::test]
    async fn verify_genesis_certificate_fails_if_is_not_genesis() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let standard_certificate = fake_certificates[0].clone();
        let mut genesis_certificate = fake_certificates.last().unwrap().clone();
        genesis_certificate.signature = standard_certificate.signature.clone();
        genesis_certificate.hash = genesis_certificate.compute_hash();

        let error = verifier
            .verify_genesis_certificate(
                &genesis_certificate,
                &genesis_verifier.to_verification_key(),
            )
            .await
            .expect_err("verify_genesis_certificate should fail");

        assert_error_matches!(
            CertificateVerifierError::InvalidGenesisCertificateProvided,
            error
        )
    }

    #[tokio::test]
    async fn verify_genesis_certificate_fails_if_hash_unmatch() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let mut genesis_certificate = fake_certificates.last().unwrap().clone();
        genesis_certificate.hash = "another-hash".to_string();

        let error = verifier
            .verify_genesis_certificate(
                &genesis_certificate,
                &genesis_verifier.to_verification_key(),
            )
            .await
            .expect_err("verify_genesis_certificate should fail");

        assert_error_matches!(CertificateVerifierError::CertificateHashUnmatch, error)
    }

    #[tokio::test]
    async fn verify_genesis_certificate_fails_if_protocol_message_unmatch() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let mut genesis_certificate = fake_certificates.last().unwrap().clone();
        genesis_certificate.protocol_message.set_message_part(
            ProtocolMessagePartKey::CurrentEpoch,
            "another-value".to_string(),
        );
        genesis_certificate.hash = genesis_certificate.compute_hash();

        let error = verifier
            .verify_genesis_certificate(
                &genesis_certificate,
                &genesis_verifier.to_verification_key(),
            )
            .await
            .expect_err("verify_genesis_certificate should fail");

        assert_error_matches!(
            CertificateVerifierError::CertificateProtocolMessageUnmatch,
            error
        )
    }

    #[tokio::test]
    async fn verify_standard_certificate_success_with_different_epochs_as_previous() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let certificate = fake_certificates[0].clone();
        let previous_certificate = fake_certificates[1].clone();

        let verify = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await;

        verify.expect("verify_standard_certificate should not fail");
    }

    #[tokio::test]
    async fn verify_standard_certificate_success_with_same_epoch_as_previous() {
        let (total_certificates, certificates_per_epoch) = (5, 2);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let certificate = fake_certificates[0].clone();
        let previous_certificate = fake_certificates[1].clone();

        let verify = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await;

        verify.expect("verify_standard_certificate should not fail");
    }

    #[tokio::test]
    async fn verify_standard_certificate_fails_if_is_not_genesis() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let genesis_certificate = fake_certificates.last().unwrap().clone();
        let mut standard_certificate = fake_certificates[0].clone();
        standard_certificate.signature = genesis_certificate.signature.clone();
        standard_certificate.hash = standard_certificate.compute_hash();
        let standard_previous_certificate = fake_certificates[1].clone();

        let error = verifier
            .verify_standard_certificate(&standard_certificate, &standard_previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(
            CertificateVerifierError::InvalidStandardCertificateProvided,
            error
        )
    }

    #[tokio::test]
    async fn verify_standard_certificate_fails_if_infinite_loop() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let mut certificate = fake_certificates[0].clone();
        certificate.previous_hash = certificate.hash.clone();
        let previous_certificate = fake_certificates[1].clone();

        let error = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(
            CertificateVerifierError::CertificateChainInfiniteLoop,
            error
        )
    }

    #[tokio::test]
    async fn verify_standard_certificate_fails_if_hash_unmatch() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let mut certificate = fake_certificates[0].clone();
        certificate.hash = "another-hash".to_string();
        let previous_certificate = fake_certificates[1].clone();

        let error = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(CertificateVerifierError::CertificateHashUnmatch, error)
    }

    #[tokio::test]
    async fn verify_standard_certificate_fails_if_protocol_message_unmatch() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let mut certificate = fake_certificates[0].clone();
        certificate.protocol_message.set_message_part(
            ProtocolMessagePartKey::CurrentEpoch,
            "another-value".to_string(),
        );
        certificate.hash = certificate.compute_hash();
        let previous_certificate = fake_certificates[1].clone();

        let error = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(
            CertificateVerifierError::CertificateProtocolMessageUnmatch,
            error
        )
    }

    #[tokio::test]
    async fn verify_standard_certificate_fails_if_certificate_previous_hash_unmatch() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let certificate = fake_certificates[0].clone();
        let mut previous_certificate = fake_certificates[1].clone();
        previous_certificate.previous_hash = "another-hash".to_string();
        previous_certificate.hash = previous_certificate.compute_hash();

        let error = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(
            CertificateVerifierError::CertificateChainPreviousHashUnmatch,
            error
        )
    }

    #[tokio::test]
    async fn verify_standard_certificate_fails_if_certificate_chain_avk_unmatch() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let verifier = MockDependencyInjector::new().build_certificate_verifier();
        let mut certificate = fake_certificates[0].clone();
        let mut previous_certificate = fake_certificates[1].clone();
        previous_certificate.protocol_message.set_message_part(
            ProtocolMessagePartKey::NextAggregateVerificationKey,
            "another-avk".to_string(),
        );
        previous_certificate.hash = previous_certificate.compute_hash();
        certificate
            .previous_hash
            .clone_from(&previous_certificate.hash);
        certificate.hash = certificate.compute_hash();

        let error = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(CertificateVerifierError::CertificateChainAVKUnmatch, error)
    }

    #[tokio::test]
    async fn verify_certificate_ko_certificate_hash_not_matching() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, _) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let mut certificate = fake_certificates[0].clone();
        certificate.hash = "another-hash".to_string();
        let previous_certificate = fake_certificates[1].clone();
        let mock_container = MockDependencyInjector::new();
        let verifier = mock_container.build_certificate_verifier();

        let error = verifier
            .verify_standard_certificate(&certificate, &previous_certificate)
            .await
            .expect_err("verify_standard_certificate should fail");

        assert_error_matches!(CertificateVerifierError::CertificateHashUnmatch, error)
    }

    #[tokio::test]
    async fn verify_certificate_success_when_certificate_is_genesis_and_valid() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let genesis_certificate = fake_certificates.last().unwrap().clone();
        let mock_container = MockDependencyInjector::new();
        let verifier = mock_container.build_certificate_verifier();

        let verify = verifier
            .verify_certificate(
                &genesis_certificate,
                &genesis_verifier.to_verification_key(),
            )
            .await;

        verify.expect("verify_certificate should not fail");
    }

    #[tokio::test]
    async fn verify_certificate_success_when_certificate_is_standard_and_valid() {
        let (total_certificates, certificates_per_epoch) = (5, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let certificate = fake_certificates[0].clone();
        let previous_certificate = fake_certificates[1].clone();
        let mut mock_container = MockDependencyInjector::new();
        mock_container
            .mock_certificate_retriever
            .expect_get_certificate_details()
            .returning(move |_| Ok(previous_certificate.clone()))
            .times(1);
        let verifier = mock_container.build_certificate_verifier();

        let verify = verifier
            .verify_certificate(&certificate, &genesis_verifier.to_verification_key())
            .await;

        verify.expect("verify_certificate should not fail");
    }

    #[tokio::test]
    async fn verify_certificate_chain_verifies_all_chained_certificates() {
        struct CertificateVerifierTest {
            certificates_unverified: Mutex<HashMap<String, Certificate>>,
        }

        impl CertificateVerifierTest {
            fn from_certificates(certificates: &[Certificate]) -> Self {
                Self {
                    certificates_unverified: Mutex::new(HashMap::from_iter(
                        certificates
                            .iter()
                            .map(|c| (c.hash.to_owned(), c.to_owned())),
                    )),
                }
            }

            async fn has_unverified_certificates(&self) -> bool {
                !self.certificates_unverified.lock().await.is_empty()
            }
        }

        #[async_trait]
        impl CertificateVerifier for CertificateVerifierTest {
            async fn verify_genesis_certificate(
                &self,
                _genesis_certificate: &Certificate,
                _genesis_verification_key: &ProtocolGenesisVerificationKey,
            ) -> StdResult<()> {
                unimplemented!()
            }

            async fn verify_standard_certificate(
                &self,
                _certificate: &Certificate,
                _previous_certificate: &Certificate,
            ) -> StdResult<()> {
                unimplemented!()
            }

            async fn verify_certificate(
                &self,
                certificate: &Certificate,
                _genesis_verification_key: &ProtocolGenesisVerificationKey,
            ) -> StdResult<Option<Certificate>> {
                let mut certificates_unverified = self.certificates_unverified.lock().await;
                let _verified_certificate = (*certificates_unverified).remove(&certificate.hash);
                let previous_certificate = (*certificates_unverified)
                    .get(&certificate.previous_hash)
                    .cloned();

                Ok(previous_certificate)
            }
        }

        let (total_certificates, certificates_per_epoch) = (10, 1);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let fake_certificate_to_verify = fake_certificates[0].clone();
        let verifier = CertificateVerifierTest::from_certificates(&fake_certificates);
        assert!(verifier.has_unverified_certificates().await);

        let verify = verifier
            .verify_certificate_chain(
                fake_certificate_to_verify,
                &genesis_verifier.to_verification_key(),
            )
            .await;

        verify.expect("verify_certificate_chain should not fail");
        assert!(!verifier.has_unverified_certificates().await);
    }

    #[tokio::test]
    async fn verify_certificate_chain_success_when_chain_is_valid() {
        let (total_certificates, certificates_per_epoch) = (7, 2);
        let (fake_certificates, genesis_verifier) =
            setup_certificate_chain(total_certificates, certificates_per_epoch);
        let certificate_retriever =
            FakeCertificaterRetriever::from_certificates(&fake_certificates);
        let verifier =
            MithrilCertificateVerifier::new(TestLogger::stdout(), Arc::new(certificate_retriever));
        let certificate_to_verify = fake_certificates[0].clone();

        let verify = verifier
            .verify_certificate_chain(
                certificate_to_verify,
                &genesis_verifier.to_verification_key(),
            )
            .await;
        verify.expect("verify_certificate_chain should not fail");
    }

    #[tokio::test]
    async fn verify_certificate_chain_fails_when_chain_is_tampered() {
        let (total_certificates, certificates_per_epoch) = (7, 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].signed_message = "tampered-message".to_string();
        let certificate_retriever =
            FakeCertificaterRetriever::from_certificates(&fake_certificates);
        let verifier =
            MithrilCertificateVerifier::new(TestLogger::stdout(), Arc::new(certificate_retriever));
        let certificate_to_verify = fake_certificates[0].clone();

        let error = verifier
            .verify_certificate_chain(
                certificate_to_verify,
                &genesis_verifier.to_verification_key(),
            )
            .await
            .expect_err("verify_certificate_chain should fail");

        assert_error_matches!(CertificateVerifierError::CertificateHashUnmatch, error)
    }
}