mithril_common/test_utils/
certificate_chain_builder.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
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
use crate::{
    certificate_chain::CertificateGenesisProducer,
    crypto_helper::{
        ProtocolAggregateVerificationKey, ProtocolClerk, ProtocolGenesisSigner,
        ProtocolGenesisVerifier, ProtocolParameters,
    },
    entities::{Certificate, CertificateSignature, Epoch, ProtocolMessage, ProtocolMessagePartKey},
    test_utils::{fake_data, MithrilFixture, MithrilFixtureBuilder, SignerFixture},
};

use crate::entities::CertificateMetadata;
use std::{
    cmp::min,
    collections::{BTreeSet, HashMap},
    iter::repeat,
    sync::Arc,
};

/// Genesis certificate processor function type. For tests only.
type GenesisCertificateProcessorFunc =
    dyn Fn(Certificate, &CertificateChainBuilderContext, &ProtocolGenesisSigner) -> Certificate;

/// Standard certificate processor function type. For tests only.
type StandardCertificateProcessorFunc =
    dyn Fn(Certificate, &CertificateChainBuilderContext) -> Certificate;

/// Total signers per epoch processor function type. For tests only.
type TotalSignersPerEpochProcessorFunc = dyn Fn(Epoch) -> usize;

/// Context used while building a certificate chain. For tests only.
pub struct CertificateChainBuilderContext<'a> {
    /// The index of the certificate in the chain.
    pub index_certificate: usize,
    /// The total number of certificates in the chain.
    #[allow(dead_code)]
    pub total_certificates: usize,
    /// The epoch of the certificate.
    pub epoch: Epoch,
    /// The fixture of the epoch.
    pub fixture: &'a MithrilFixture,
    /// The fixture of the next epoch.
    pub next_fixture: &'a MithrilFixture,
}

impl<'a> CertificateChainBuilderContext<'a> {
    fn new(
        index_certificate: usize,
        total_certificates: usize,
        epoch: Epoch,
        fixture: &'a MithrilFixture,
        next_fixture: &'a MithrilFixture,
    ) -> Self {
        Self {
            index_certificate,
            total_certificates,
            epoch,
            fixture,
            next_fixture,
        }
    }

    /// Computes the protocol message seed.
    pub fn compute_protocol_message_seed(&self) -> ProtocolMessage {
        let mut protocol_message = ProtocolMessage::new();
        protocol_message.set_message_part(
            ProtocolMessagePartKey::NextAggregateVerificationKey,
            self.next_fixture.compute_and_encode_avk(),
        );
        protocol_message.set_message_part(
            ProtocolMessagePartKey::NextProtocolParameters,
            self.next_fixture.protocol_parameters().compute_hash(),
        );
        protocol_message
            .set_message_part(ProtocolMessagePartKey::CurrentEpoch, self.epoch.to_string());

        protocol_message
    }

    /// Checks if the current certificate is the last one.
    pub fn is_last_certificate(&self) -> bool {
        self.index_certificate == self.total_certificates - 1
    }
}

/// Chaining method to use when building a certificate chain with the [CertificateChainBuilder]. For tests only.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum CertificateChainingMethod {
    /// `default` Chain certificates to the 'master' certificate of the epoch or if it's the 'master'
    /// certificate, chain it to the 'master' certificate of the previous epoch.
    ///
    /// The 'master' certificate of an epoch is the first certificate of the epoch.
    #[default]
    ToMasterCertificate,

    /// Chain certificates sequentially.
    Sequential,
}

/// A builder for creating a certificate chain. For tests only.
///
/// # Simple example usage for building a fully valid certificate chain
///
/// ```
///     use mithril_common::crypto_helper::ProtocolParameters;
///     use mithril_common::test_utils::CertificateChainBuilder;
///
///     let (certificate_chain, _protocol_genesis_verifier) = CertificateChainBuilder::new()
///         .with_total_certificates(5)
///         .with_certificates_per_epoch(2)
///         .build();
///
///     assert_eq!(5, certificate_chain.len());
/// ```
///
/// # More complex example usage for building a fully valid certificate chain
///
/// ```
///     use std::cmp::min;
///     use mithril_common::crypto_helper::ProtocolParameters;
///     use mithril_common::test_utils::CertificateChainBuilder;
///
///     let (certificate_chain, _protocol_genesis_verifier) = CertificateChainBuilder::new()
///         .with_total_certificates(5)
///         .with_certificates_per_epoch(2)
///         .with_protocol_parameters(ProtocolParameters {
///             m: 100,
///             k: 5,
///             phi_f: 0.65,
///         })
///         .with_total_signers_per_epoch_processor(&|epoch| min(1 + *epoch as usize, 10))
///         .build();
///
///     assert_eq!(5, certificate_chain.len());
/// ```
///
/// # Advanced example usage for building an adversarial certificate chain
///
/// ```
///     use mithril_common::entities::Epoch;
///     use mithril_common::crypto_helper::ProtocolParameters;
///     use mithril_common::test_utils::CertificateChainBuilder;
///
///     let (certificate_chain, _protocol_genesis_verifier) = CertificateChainBuilder::new()
///         .with_total_certificates(5)
///         .with_certificates_per_epoch(2)
///         .with_standard_certificate_processor(&|certificate, context| {
///             let mut certificate = certificate;
///             // Alter the epoch of the last certificate
///             if context.is_last_certificate() {
///                 certificate.epoch = Epoch(123);
///             }
///
///             certificate
///        })
///        .build();
///
///     assert_eq!(5, certificate_chain.len());
/// ```
pub struct CertificateChainBuilder<'a> {
    total_certificates: u64,
    certificates_per_epoch: u64,
    protocol_parameters: ProtocolParameters,
    total_signers_per_epoch_processor: &'a TotalSignersPerEpochProcessorFunc,
    genesis_certificate_processor: &'a GenesisCertificateProcessorFunc,
    standard_certificate_processor: &'a StandardCertificateProcessorFunc,
    certificate_chaining_method: CertificateChainingMethod,
}

impl<'a> CertificateChainBuilder<'a> {
    /// Create a new [CertificateChainBuilder] instance.
    pub fn new() -> Self {
        let protocol_parameters = ProtocolParameters {
            m: 100,
            k: 5,
            phi_f: 0.65,
        };
        Self {
            total_certificates: 5,
            certificates_per_epoch: 1,
            protocol_parameters,
            total_signers_per_epoch_processor: &|epoch| min(2 + *epoch as usize, 5),
            genesis_certificate_processor: &|certificate, _, _| certificate,
            standard_certificate_processor: &|certificate, _| certificate,
            certificate_chaining_method: Default::default(),
        }
    }

    /// Set the total number of certificates to generate.
    pub fn with_total_certificates(mut self, total_certificates: u64) -> Self {
        self.total_certificates = total_certificates;

        self
    }

    /// Set the number of certificates per epoch.
    pub fn with_certificates_per_epoch(mut self, certificates_per_epoch: u64) -> Self {
        self.certificates_per_epoch = certificates_per_epoch;

        self
    }

    /// Set the protocol parameters.
    pub fn with_protocol_parameters(mut self, protocol_parameters: ProtocolParameters) -> Self {
        self.protocol_parameters = protocol_parameters;

        self
    }

    /// Set the total signers per epoch processor.
    pub fn with_total_signers_per_epoch_processor(
        mut self,
        total_signers_per_epoch_processor: &'a TotalSignersPerEpochProcessorFunc,
    ) -> Self {
        self.total_signers_per_epoch_processor = total_signers_per_epoch_processor;

        self
    }

    /// Set the genesis certificate processor.
    pub fn with_genesis_certificate_processor(
        mut self,
        genesis_certificate_processor: &'a GenesisCertificateProcessorFunc,
    ) -> Self {
        self.genesis_certificate_processor = genesis_certificate_processor;

        self
    }

    /// Set the standard certificate processor.
    pub fn with_standard_certificate_processor(
        mut self,
        standard_certificate_processor: &'a StandardCertificateProcessorFunc,
    ) -> Self {
        self.standard_certificate_processor = standard_certificate_processor;

        self
    }

    /// Set the chaining method to use when building the certificate chain.
    pub fn with_certificate_chaining_method(
        mut self,
        certificate_chaining_method: CertificateChainingMethod,
    ) -> Self {
        self.certificate_chaining_method = certificate_chaining_method;

        self
    }

    /// Build the certificate chain.
    pub fn build(self) -> (Vec<Certificate>, ProtocolGenesisVerifier) {
        let (genesis_signer, genesis_verifier) = CertificateChainBuilder::setup_genesis();
        let genesis_certificate_processor = self.genesis_certificate_processor;
        let standard_certificate_processor = self.standard_certificate_processor;
        let total_certificates = self.total_certificates as usize;
        let fixtures_per_epoch = self.build_fixtures_for_epochs();
        let certificates = self.build_certificate_index_and_epoch_sequence()
            .map(|(index_certificate, epoch)| {
                let fixture = fixtures_per_epoch.get(&epoch).unwrap_or_else(|| panic!("Fixture not found at epoch {epoch:?} with {} total certificates and {} certificates per epoch", self.total_certificates, self.certificates_per_epoch));
                let next_fixture = fixtures_per_epoch.get(&epoch.next()).unwrap_or_else(|| panic!("Next fixture not found at epoch {epoch:?} with {} total certificates and {} certificates per epoch", self.total_certificates, self.certificates_per_epoch));
                let context = CertificateChainBuilderContext::new(
                    index_certificate,
                    total_certificates,
                    epoch,
                    fixture,
                    next_fixture,
                );
                match index_certificate {
                    0 => genesis_certificate_processor(
                        self.build_genesis_certificate(&context, &genesis_signer),
                        &context,
                        &genesis_signer,
                    ),
                    _ => standard_certificate_processor(
                        self.build_standard_certificate(&context),
                        &context,
                    ),
                }
            })
            .collect::<Vec<Certificate>>();
        let certificates_chained = self.compute_chained_certificates(certificates);

        (certificates_chained, genesis_verifier)
    }

    fn compute_clerk_for_signers(signers: &[SignerFixture]) -> ProtocolClerk {
        let first_signer = &signers[0].protocol_signer;

        ProtocolClerk::from_signer(first_signer)
    }

    fn compute_avk_for_signers(signers: &[SignerFixture]) -> ProtocolAggregateVerificationKey {
        let clerk = Self::compute_clerk_for_signers(signers);

        clerk.compute_avk().into()
    }

    fn setup_genesis() -> (ProtocolGenesisSigner, ProtocolGenesisVerifier) {
        let genesis_signer = ProtocolGenesisSigner::create_deterministic_genesis_signer();
        let genesis_verifier = genesis_signer.create_genesis_verifier();

        (genesis_signer, genesis_verifier)
    }

    fn build_epochs_sequence(&self) -> impl Iterator<Item = Epoch> {
        let total_certificates = self.total_certificates;
        let certificates_per_epoch = self.certificates_per_epoch;
        assert!(
            certificates_per_epoch > 0,
            "Certificates per epoch must be greater than 0"
        );
        assert!(
            total_certificates >= certificates_per_epoch,
            "Total certificates must be greater or equal to certificates per epoch"
        );
        // The total number of epochs in the sequence is the total number of standard certificates (total number of certificates minus one genesis certificate)
        // divided by the number of certificates per epoch plus two (one for the genesis epoch and one to compute the next fixtures of the last epoch)
        const TOTAL_GENESIS_CERTIFICATES: u64 = 1;
        const TOTAL_EXTRA_EPOCHS_FOR_FIXTURES_COMPUTATION: u64 = 1;
        let total_epochs_in_sequence = (total_certificates - TOTAL_GENESIS_CERTIFICATES)
            .div_ceil(certificates_per_epoch)
            + TOTAL_GENESIS_CERTIFICATES
            + TOTAL_EXTRA_EPOCHS_FOR_FIXTURES_COMPUTATION;
        (1..=total_epochs_in_sequence).map(Epoch)
    }

    fn build_certificate_index_and_epoch_sequence(&self) -> impl Iterator<Item = (usize, Epoch)> {
        let total_certificates = self.total_certificates as usize;
        let certificates_per_epoch = self.certificates_per_epoch as usize;

        self.build_epochs_sequence()
            .flat_map(move |epoch| {
                let repeat_epoch = if epoch == 1 {
                    // No need to repeat with the genesis epoch
                    1
                } else {
                    certificates_per_epoch
                };
                repeat(Epoch(*epoch)).take(repeat_epoch)
            })
            .take(total_certificates)
            .enumerate()
    }

    fn build_fixtures_for_epochs(&self) -> HashMap<Epoch, MithrilFixture> {
        self.build_epochs_sequence()
            .collect::<BTreeSet<_>>()
            .into_iter()
            .map(|epoch| {
                let total_signers = (self.total_signers_per_epoch_processor)(epoch);
                let protocol_parameters = self.protocol_parameters.to_owned().into();
                (
                    epoch,
                    MithrilFixtureBuilder::default()
                        .with_protocol_parameters(protocol_parameters)
                        .with_signers(total_signers)
                        .build(),
                )
            })
            .collect::<HashMap<_, _>>()
    }

    fn build_base_certificate(&self, context: &CertificateChainBuilderContext) -> Certificate {
        let index_certificate = context.index_certificate;
        let epoch = context.epoch;
        let certificate_hash = format!("certificate_hash-{index_certificate}");
        let avk = Self::compute_avk_for_signers(&context.fixture.signers_fixture());
        let protocol_parameters = context.fixture.protocol_parameters().to_owned();
        let base_certificate = fake_data::certificate(certificate_hash);
        let protocol_message = context.compute_protocol_message_seed();
        let signed_message = protocol_message.compute_hash();

        Certificate {
            epoch,
            aggregate_verification_key: avk.to_owned(),
            previous_hash: "".to_string(),
            protocol_message,
            signed_message,
            metadata: CertificateMetadata {
                protocol_parameters,
                ..base_certificate.metadata
            },
            ..base_certificate
        }
    }

    fn build_genesis_certificate(
        &self,
        context: &CertificateChainBuilderContext,
        genesis_signer: &ProtocolGenesisSigner,
    ) -> Certificate {
        let epoch = context.epoch;
        let certificate = self.build_base_certificate(context);
        let next_avk = Self::compute_avk_for_signers(&context.next_fixture.signers_fixture());
        let next_protocol_parameters = &context.next_fixture.protocol_parameters();
        let genesis_producer =
            CertificateGenesisProducer::new(Some(Arc::new(genesis_signer.to_owned())));
        let genesis_protocol_message = CertificateGenesisProducer::create_genesis_protocol_message(
            next_protocol_parameters,
            &next_avk,
            &epoch,
        )
        .unwrap();
        let genesis_signature = genesis_producer
            .sign_genesis_protocol_message(genesis_protocol_message)
            .unwrap();

        CertificateGenesisProducer::create_genesis_certificate(
            certificate.metadata.protocol_parameters,
            certificate.metadata.network,
            certificate.epoch,
            next_avk,
            genesis_signature,
        )
        .unwrap()
    }

    fn build_standard_certificate(&self, context: &CertificateChainBuilderContext) -> Certificate {
        let fixture = context.fixture;
        let mut certificate = self.build_base_certificate(context);
        certificate.metadata.signers = fixture.stake_distribution_parties();
        let mut protocol_message = certificate.protocol_message.clone();
        protocol_message.set_message_part(
            ProtocolMessagePartKey::SnapshotDigest,
            format!("digest-{}", context.index_certificate),
        );
        certificate.protocol_message = protocol_message;
        certificate.signed_message = certificate.protocol_message.compute_hash();
        let single_signatures = fixture
            .signers_fixture()
            .iter()
            .filter_map(|s| {
                s.protocol_signer
                    .sign(certificate.signed_message.as_bytes())
            })
            .collect::<Vec<_>>();
        let clerk = CertificateChainBuilder::compute_clerk_for_signers(&fixture.signers_fixture());
        let multi_signature = clerk
            .aggregate(&single_signatures, certificate.signed_message.as_bytes())
            .unwrap();
        certificate.signature = CertificateSignature::MultiSignature(
            certificate.signed_entity_type(),
            multi_signature.into(),
        );

        certificate
    }

    fn update_certificate_previous_hash(
        &self,
        certificate: Certificate,
        previous_certificate: Option<&Certificate>,
    ) -> Certificate {
        let mut certificate = certificate;
        certificate.previous_hash = previous_certificate
            .map(|c| c.hash.to_string())
            .unwrap_or_default();
        certificate.hash = certificate.compute_hash();

        certificate
    }

    fn fetch_previous_certificate_from_chain<'b>(
        &self,
        certificate: &Certificate,
        certificates_chained: &'b [Certificate],
    ) -> Option<&'b Certificate> {
        match self.certificate_chaining_method {
            CertificateChainingMethod::ToMasterCertificate => {
                let is_certificate_first_of_epoch = certificates_chained
                    .last()
                    .map(|c| c.epoch != certificate.epoch)
                    .unwrap_or(true);

                certificates_chained
                    .iter()
                    .rev()
                    .filter(|c| {
                        if is_certificate_first_of_epoch {
                            // The previous certificate of the first certificate of an epoch
                            // is the first certificate of the previous epoch
                            c.epoch == certificate.epoch.previous().unwrap()
                        } else {
                            // The previous certificate of not the first certificate of an epoch
                            // is the first certificate of the epoch
                            c.epoch == certificate.epoch
                        }
                    })
                    .last()
            }
            CertificateChainingMethod::Sequential => certificates_chained.last(),
        }
    }

    // Returns the chained certificates in reverse order
    // The latest certificate of the chain is the first in the vector
    fn compute_chained_certificates(&self, certificates: Vec<Certificate>) -> Vec<Certificate> {
        let mut certificates_chained: Vec<Certificate> =
            certificates
                .into_iter()
                .fold(Vec::new(), |mut certificates_chained, certificate| {
                    let previous_certificate_maybe = self
                        .fetch_previous_certificate_from_chain(&certificate, &certificates_chained);
                    let certificate = self
                        .update_certificate_previous_hash(certificate, previous_certificate_maybe);
                    certificates_chained.push(certificate);

                    certificates_chained
                });
        certificates_chained.reverse();

        certificates_chained
    }
}

impl Default for CertificateChainBuilder<'_> {
    fn default() -> Self {
        Self::new()
    }
}

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

    use super::*;

    fn build_epoch_numbers_sequence(
        total_certificates: u64,
        certificates_per_epoch: u64,
    ) -> Vec<u64> {
        CertificateChainBuilder::default()
            .with_total_certificates(total_certificates)
            .with_certificates_per_epoch(certificates_per_epoch)
            .build_epochs_sequence()
            .map(|epoch| *epoch)
            .collect::<Vec<_>>()
    }

    fn build_certificate_index_and_epoch_numbers_sequence(
        total_certificates: u64,
        certificates_per_epoch: u64,
    ) -> Vec<(usize, u64)> {
        CertificateChainBuilder::default()
            .with_total_certificates(total_certificates)
            .with_certificates_per_epoch(certificates_per_epoch)
            .build_certificate_index_and_epoch_sequence()
            .map(|(certificate_index, epoch)| (certificate_index, *epoch))
            .collect::<Vec<_>>()
    }

    fn build_epoch_numbers_sequence_in_certificate_chain(
        total_certificates: u64,
        certificates_per_epoch: u64,
    ) -> Vec<u64> {
        build_certificate_index_and_epoch_numbers_sequence(
            total_certificates,
            certificates_per_epoch,
        )
        .iter()
        .map(|(_certificate_index, epoch)| *epoch)
        .collect::<Vec<_>>()
    }

    fn build_certificate_chain(
        total_certificates: u64,
        certificates_per_epoch: u64,
    ) -> Vec<Certificate> {
        let (certificate_chain, _) = CertificateChainBuilder::default()
            .with_total_certificates(total_certificates)
            .with_certificates_per_epoch(certificates_per_epoch)
            .build();

        certificate_chain
    }

    #[test]
    fn certificate_chain_builder_context_computes_correct_protocol_message_seed() {
        let protocol_parameters = ProtocolParameters {
            m: 123,
            k: 45,
            phi_f: 0.67,
        };
        let next_protocol_parameters = ProtocolParameters {
            m: 100,
            k: 10,
            phi_f: 0.10,
        };
        let fixture = MithrilFixtureBuilder::default()
            .with_protocol_parameters(protocol_parameters.into())
            .with_signers(2)
            .build();
        let next_fixture = MithrilFixtureBuilder::default()
            .with_protocol_parameters(next_protocol_parameters.into())
            .with_signers(3)
            .build();
        let context = CertificateChainBuilderContext {
            index_certificate: 2,
            total_certificates: 5,
            epoch: Epoch(1),
            fixture: &fixture,
            next_fixture: &next_fixture,
        };
        let expected_next_avk_part_value = next_fixture.compute_and_encode_avk();
        let expected_next_protocol_parameters_part_value =
            next_fixture.protocol_parameters().compute_hash();

        let expected_current_epoch_part_value = context.epoch.to_string();

        let protocol_message = context.compute_protocol_message_seed();

        let mut expected_protocol_message = ProtocolMessage::new();
        expected_protocol_message.set_message_part(
            ProtocolMessagePartKey::NextAggregateVerificationKey,
            expected_next_avk_part_value,
        );
        expected_protocol_message.set_message_part(
            ProtocolMessagePartKey::NextProtocolParameters,
            expected_next_protocol_parameters_part_value,
        );
        expected_protocol_message.set_message_part(
            ProtocolMessagePartKey::CurrentEpoch,
            expected_current_epoch_part_value,
        );

        assert_eq!(expected_protocol_message, protocol_message);
    }

    #[test]
    fn certificate_chain_builder_context_checks_correctly_if_certificate_is_last() {
        let fixture = MithrilFixtureBuilder::default().with_signers(2).build();
        let context = CertificateChainBuilderContext {
            index_certificate: 4,
            total_certificates: 5,
            epoch: Epoch(1),
            fixture: &fixture,
            next_fixture: &fixture,
        };

        assert!(context.is_last_certificate());
    }

    #[test]
    fn builds_certificate_chain_with_correct_length() {
        assert_eq!(4, build_certificate_chain(4, 1).len());
        assert_eq!(4, build_certificate_chain(4, 2).len());
        assert_eq!(4, build_certificate_chain(4, 3).len());
        assert_eq!(4, build_certificate_chain(4, 4).len());
        assert_eq!(5, build_certificate_chain(5, 1).len());
        assert_eq!(5, build_certificate_chain(5, 2).len());
        assert_eq!(5, build_certificate_chain(5, 3).len());
        assert_eq!(7, build_certificate_chain(7, 3).len());
        assert_eq!(15, build_certificate_chain(15, 3).len());
    }

    #[test]
    fn builds_valid_epochs_sequence() {
        assert_eq!(vec![1, 2, 3, 4], build_epoch_numbers_sequence(3, 1));
        assert_eq!(vec![1, 2, 3, 4], build_epoch_numbers_sequence(4, 2));
        assert_eq!(vec![1, 2, 3, 4], build_epoch_numbers_sequence(5, 2));
        assert_eq!(vec![1, 2, 3, 4], build_epoch_numbers_sequence(7, 3),);
        assert_eq!(
            vec![1, 2, 3, 4, 5, 6, 7],
            build_epoch_numbers_sequence(15, 3),
        );
    }

    #[test]
    fn builds_valid_certificate_index_and_epoch_numbers_sequence() {
        assert_eq!(
            vec![1, 2, 3],
            build_epoch_numbers_sequence_in_certificate_chain(3, 1)
        );
        assert_eq!(
            vec![1, 2, 2, 3],
            build_epoch_numbers_sequence_in_certificate_chain(4, 2)
        );
        assert_eq!(
            vec![1, 2, 2, 3, 3],
            build_epoch_numbers_sequence_in_certificate_chain(5, 2)
        );
        assert_eq!(
            vec![1, 2, 2, 2, 3, 3, 3],
            build_epoch_numbers_sequence_in_certificate_chain(7, 3),
        );
        assert_eq!(
            vec![1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6],
            build_epoch_numbers_sequence_in_certificate_chain(15, 3),
        );
    }

    #[test]
    #[should_panic]
    fn panics_building_invalid_epochs_sequence_no_certificates_per_epoch() {
        build_epoch_numbers_sequence(3, 0);
    }

    #[test]
    #[should_panic]
    fn panics_building_invalid_epochs_sequence_less_total_certificates_than_certificates_per_epoch()
    {
        build_epoch_numbers_sequence(3, 5);
    }

    #[test]
    fn builds_valid_fixtures_per_epochs() {
        let expected_total_signers = (1..=6).collect::<Vec<_>>();
        let certificate_chain_builder = CertificateChainBuilder::default()
            .with_total_certificates(5)
            .with_certificates_per_epoch(1)
            .with_total_signers_per_epoch_processor(&|epoch| *epoch as usize);

        let epoch_fixtures =
            BTreeMap::from_iter(certificate_chain_builder.build_fixtures_for_epochs());

        let total_signers = epoch_fixtures
            .into_values()
            .map(|fixture| fixture.signers().len())
            .collect::<Vec<_>>();
        assert_eq!(expected_total_signers, total_signers);
    }

    #[test]
    fn builds_valid_genesis_certificate() {
        let expected_protocol_parameters = ProtocolParameters {
            m: 123,
            k: 45,
            phi_f: 0.67,
        };
        let fixture = MithrilFixtureBuilder::default()
            .with_protocol_parameters(expected_protocol_parameters.into())
            .with_signers(2)
            .build();
        let next_fixture = MithrilFixtureBuilder::default()
            .with_protocol_parameters(expected_protocol_parameters.into())
            .with_signers(3)
            .build();
        let context = CertificateChainBuilderContext {
            index_certificate: 0,
            total_certificates: 5,
            epoch: Epoch(1),
            fixture: &fixture,
            next_fixture: &next_fixture,
        };
        let expected_protocol_message = context.compute_protocol_message_seed();
        let expected_signed_message = expected_protocol_message.compute_hash();
        let (protocol_genesis_signer, _) = CertificateChainBuilder::setup_genesis();

        let genesis_certificate = CertificateChainBuilder::default()
            .with_protocol_parameters(expected_protocol_parameters)
            .build_genesis_certificate(&context, &protocol_genesis_signer);

        assert!(genesis_certificate.is_genesis());
        assert_eq!(Epoch(1), genesis_certificate.epoch);
        assert_eq!(
            expected_protocol_parameters,
            genesis_certificate.metadata.protocol_parameters.into()
        );
        assert_eq!(0, genesis_certificate.metadata.signers.len());
        assert_eq!(
            expected_protocol_message,
            genesis_certificate.protocol_message
        );
        assert_eq!(expected_signed_message, genesis_certificate.signed_message);
    }

    #[test]
    fn builds_valid_standard_certificate() {
        let expected_protocol_parameters = ProtocolParameters {
            m: 123,
            k: 45,
            phi_f: 0.67,
        };
        let fixture = MithrilFixtureBuilder::default()
            .with_protocol_parameters(expected_protocol_parameters.into())
            .with_signers(2)
            .build();
        let next_fixture = MithrilFixtureBuilder::default()
            .with_protocol_parameters(expected_protocol_parameters.into())
            .with_signers(3)
            .build();
        let avk = fixture.compute_and_encode_avk();
        let context = CertificateChainBuilderContext {
            index_certificate: 2,
            total_certificates: 5,
            epoch: Epoch(1),
            fixture: &fixture,
            next_fixture: &next_fixture,
        };
        let mut expected_protocol_message = context.compute_protocol_message_seed();
        expected_protocol_message.set_message_part(
            ProtocolMessagePartKey::SnapshotDigest,
            format!("digest-{}", context.index_certificate),
        );
        let expected_signed_message = expected_protocol_message.compute_hash();

        let standard_certificate = CertificateChainBuilder::default()
            .with_protocol_parameters(expected_protocol_parameters)
            .build_standard_certificate(&context);

        assert!(!standard_certificate.is_genesis());
        assert_eq!(Epoch(1), standard_certificate.epoch);
        assert_eq!(
            expected_protocol_parameters,
            standard_certificate.metadata.protocol_parameters.into()
        );
        assert_eq!(2, standard_certificate.metadata.signers.len());
        assert_eq!(
            expected_protocol_message,
            standard_certificate.protocol_message
        );
        assert_eq!(expected_signed_message, standard_certificate.signed_message);
        assert_eq!(
            avk,
            standard_certificate
                .aggregate_verification_key
                .to_json_hex()
                .unwrap()
        );
    }

    #[test]
    fn builds_certificate_chain_chained_by_default_to_master_certificates() {
        fn create_fake_certificate(epoch: Epoch, index_in_epoch: u64) -> Certificate {
            Certificate {
                epoch,
                signed_message: format!("certificate-{}-{index_in_epoch}", *epoch),
                ..fake_data::certificate("cert-fake".to_string())
            }
        }

        let certificates = vec![
            create_fake_certificate(Epoch(1), 1),
            create_fake_certificate(Epoch(2), 1),
            create_fake_certificate(Epoch(2), 2),
            create_fake_certificate(Epoch(3), 1),
            create_fake_certificate(Epoch(4), 1),
            create_fake_certificate(Epoch(4), 2),
            create_fake_certificate(Epoch(4), 3),
        ];

        let mut certificates_chained =
            CertificateChainBuilder::default().compute_chained_certificates(certificates);
        certificates_chained.reverse();

        let certificate_chained_1_1 = &certificates_chained[0];
        let certificate_chained_2_1 = &certificates_chained[1];
        let certificate_chained_2_2 = &certificates_chained[2];
        let certificate_chained_3_1 = &certificates_chained[3];
        let certificate_chained_4_1 = &certificates_chained[4];
        let certificate_chained_4_2 = &certificates_chained[5];
        let certificate_chained_4_3 = &certificates_chained[6];
        assert_eq!("", certificate_chained_1_1.previous_hash);
        assert_eq!(
            certificate_chained_2_1.previous_hash,
            certificate_chained_1_1.hash
        );
        assert_eq!(
            certificate_chained_2_2.previous_hash,
            certificate_chained_2_1.hash
        );
        assert_eq!(
            certificate_chained_3_1.previous_hash,
            certificate_chained_2_1.hash
        );
        assert_eq!(
            certificate_chained_4_1.previous_hash,
            certificate_chained_3_1.hash
        );
        assert_eq!(
            certificate_chained_4_2.previous_hash,
            certificate_chained_4_1.hash
        );
        assert_eq!(
            certificate_chained_4_3.previous_hash,
            certificate_chained_4_1.hash
        );
    }

    #[test]
    fn builds_certificate_chain_chained_sequentially() {
        fn create_fake_certificate(epoch: Epoch, index_in_epoch: u64) -> Certificate {
            Certificate {
                epoch,
                signed_message: format!("certificate-{}-{index_in_epoch}", *epoch),
                ..fake_data::certificate("cert-fake".to_string())
            }
        }

        let certificates = vec![
            create_fake_certificate(Epoch(1), 1),
            create_fake_certificate(Epoch(2), 1),
            create_fake_certificate(Epoch(2), 2),
            create_fake_certificate(Epoch(3), 1),
            create_fake_certificate(Epoch(4), 1),
            create_fake_certificate(Epoch(4), 2),
            create_fake_certificate(Epoch(4), 3),
        ];

        let mut certificates_chained = CertificateChainBuilder::default()
            .with_certificate_chaining_method(CertificateChainingMethod::Sequential)
            .compute_chained_certificates(certificates);
        certificates_chained.reverse();

        let certificate_chained_1_1 = &certificates_chained[0];
        let certificate_chained_2_1 = &certificates_chained[1];
        let certificate_chained_2_2 = &certificates_chained[2];
        let certificate_chained_3_1 = &certificates_chained[3];
        let certificate_chained_4_1 = &certificates_chained[4];
        let certificate_chained_4_2 = &certificates_chained[5];
        let certificate_chained_4_3 = &certificates_chained[6];
        assert_eq!("", certificate_chained_1_1.previous_hash);
        assert_eq!(
            certificate_chained_2_1.previous_hash,
            certificate_chained_1_1.hash
        );
        assert_eq!(
            certificate_chained_2_2.previous_hash,
            certificate_chained_2_1.hash
        );
        assert_eq!(
            certificate_chained_3_1.previous_hash,
            certificate_chained_2_2.hash
        );
        assert_eq!(
            certificate_chained_4_1.previous_hash,
            certificate_chained_3_1.hash
        );
        assert_eq!(
            certificate_chained_4_2.previous_hash,
            certificate_chained_4_1.hash
        );
        assert_eq!(
            certificate_chained_4_3.previous_hash,
            certificate_chained_4_2.hash
        );
    }

    #[test]
    fn builds_certificate_chain_with_alteration_on_genesis_certificate() {
        let (certificates, _) = CertificateChainBuilder::new()
            .with_total_certificates(5)
            .with_genesis_certificate_processor(&|certificate, _, _| {
                let mut certificate = certificate;
                certificate.signed_message = "altered_msg".to_string();

                certificate
            })
            .build();

        assert_eq!(
            "altered_msg".to_string(),
            certificates.last().unwrap().signed_message
        );
    }

    #[test]
    fn builds_certificate_chain_with_alteration_on_standard_certificates() {
        let total_certificates = 5;
        let expected_signed_messages = (1..total_certificates)
            .rev()
            .map(|i| format!("altered-msg-{}", i))
            .collect::<Vec<_>>();

        let (certificates, _) = CertificateChainBuilder::new()
            .with_total_certificates(total_certificates)
            .with_standard_certificate_processor(&|certificate, context| {
                let mut certificate = certificate;
                certificate.signed_message = format!("altered-msg-{}", context.index_certificate);

                certificate
            })
            .build();

        let signed_message = certificates
            .into_iter()
            .take(total_certificates as usize - 1)
            .map(|certificate| certificate.signed_message)
            .collect::<Vec<_>>();
        assert_eq!(expected_signed_messages, signed_message);
    }
}