mithril_common/test_utils/
fixture_builder.rs

1use kes_summed_ed25519::{kes::Sum6Kes, traits::KesSk, PublicKey as KesPublicKey};
2use rand_chacha::ChaCha20Rng;
3use rand_core::{RngCore, SeedableRng};
4
5use crate::{
6    crypto_helper::{
7        tests_setup, tests_setup::setup_temp_directory_for_signer, ColdKeyGenerator, OpCert,
8        ProtocolStakeDistribution, SerDeShelleyFileFormat, Sum6KesBytes,
9    },
10    entities::{PartyId, ProtocolParameters, Stake, StakeDistribution},
11    test_utils::{fake_data, mithril_fixture::MithrilFixture},
12};
13
14use super::precomputed_kes_key;
15
16/// A builder of mithril types.
17pub struct MithrilFixtureBuilder {
18    protocol_parameters: ProtocolParameters,
19    enable_signers_certification: bool,
20    number_of_signers: usize,
21    stake_distribution_generation_method: StakeDistributionGenerationMethod,
22    party_id_seed: [u8; 32],
23}
24
25impl Default for MithrilFixtureBuilder {
26    fn default() -> Self {
27        Self {
28            protocol_parameters: fake_data::protocol_parameters(),
29            enable_signers_certification: true,
30            number_of_signers: 5,
31            stake_distribution_generation_method:
32                StakeDistributionGenerationMethod::RandomDistribution {
33                    seed: [0u8; 32],
34                    min_stake: 1,
35                },
36            party_id_seed: [0u8; 32],
37        }
38    }
39}
40
41/// Methods that can be used to generate the stake distribution.
42pub enum StakeDistributionGenerationMethod {
43    /// Each party will have a random stake.
44    RandomDistribution {
45        /// The randomizer seed
46        seed: [u8; 32],
47        /// The minimum stake
48        min_stake: Stake,
49    },
50
51    /// Use a custom stake distribution
52    ///
53    /// Important: this will overwrite the number of signers set by with_signers.
54    Custom(StakeDistribution),
55
56    /// Make a stake distribution where all parties will have the given stake
57    Uniform(Stake),
58}
59
60impl MithrilFixtureBuilder {
61    /// Set the protocol_parameters.
62    pub fn with_protocol_parameters(mut self, protocol_parameters: ProtocolParameters) -> Self {
63        self.protocol_parameters = protocol_parameters;
64        self
65    }
66
67    /// Set the number of signers that will be generated.
68    pub fn with_signers(mut self, number_of_signers: usize) -> Self {
69        self.number_of_signers = number_of_signers;
70        self
71    }
72
73    /// If set the generated signers won't be certified (meaning that they won't
74    /// have a operational certificate).
75    pub fn disable_signers_certification(mut self) -> Self {
76        self.enable_signers_certification = false;
77        self
78    }
79
80    /// Set the generation method used to compute the stake distribution.
81    pub fn with_stake_distribution(
82        mut self,
83        stake_distribution_generation_method: StakeDistributionGenerationMethod,
84    ) -> Self {
85        self.stake_distribution_generation_method = stake_distribution_generation_method;
86        self
87    }
88
89    /// Set the seed used to generated the party ids
90    pub fn with_party_id_seed(mut self, seed: [u8; 32]) -> Self {
91        self.party_id_seed = seed;
92        self
93    }
94
95    /// Transform the specified parameters to a [MithrilFixture].
96    pub fn build(self) -> MithrilFixture {
97        let protocol_stake_distribution = self.generate_stake_distribution();
98        let signers = tests_setup::setup_signers_from_stake_distribution(
99            &protocol_stake_distribution,
100            &self.protocol_parameters.clone().into(),
101        );
102
103        MithrilFixture::new(
104            self.protocol_parameters,
105            signers,
106            protocol_stake_distribution,
107        )
108    }
109
110    fn generate_stake_distribution(&self) -> ProtocolStakeDistribution {
111        let signers_party_ids = self.generate_party_ids();
112
113        match &self.stake_distribution_generation_method {
114            StakeDistributionGenerationMethod::RandomDistribution { seed, min_stake } => {
115                let mut stake_rng = ChaCha20Rng::from_seed(*seed);
116
117                signers_party_ids
118                    .into_iter()
119                    .map(|party_id| {
120                        let stake = min_stake + stake_rng.next_u64() % 999;
121                        (party_id, stake)
122                    })
123                    .collect::<Vec<_>>()
124            }
125            StakeDistributionGenerationMethod::Custom(stake_distribution) => stake_distribution
126                .clone()
127                .into_iter()
128                .collect::<ProtocolStakeDistribution>(),
129            StakeDistributionGenerationMethod::Uniform(stake) => signers_party_ids
130                .into_iter()
131                .map(|party_id| (party_id, *stake))
132                .collect::<ProtocolStakeDistribution>(),
133        }
134    }
135
136    fn generate_party_ids(&self) -> Vec<PartyId> {
137        match self.stake_distribution_generation_method {
138            StakeDistributionGenerationMethod::Custom(_) => vec![],
139            _ => {
140                let signers_party_ids = (0..self.number_of_signers).map(|party_index| {
141                    if self.enable_signers_certification {
142                        self.build_party_with_operational_certificate(party_index)
143                    } else {
144                        party_index.to_string()
145                    }
146                });
147                signers_party_ids.collect::<Vec<_>>()
148            }
149        }
150    }
151
152    fn provide_kes_key(kes_key_seed: &mut [u8]) -> (Sum6KesBytes, KesPublicKey) {
153        if let Some((kes_bytes, kes_verification_key)) =
154            MithrilFixtureBuilder::cached_kes_key(kes_key_seed)
155        {
156            (kes_bytes, kes_verification_key)
157        } else {
158            println!(
159                "KES key not found in test cache, generating a new one for the seed {kes_key_seed:?}."
160            );
161            MithrilFixtureBuilder::generate_kes_key(kes_key_seed)
162        }
163    }
164
165    fn cached_kes_key(kes_key_seed: &[u8]) -> Option<(Sum6KesBytes, KesPublicKey)> {
166        precomputed_kes_key::cached_kes_key(kes_key_seed).map(
167            |(kes_bytes, kes_verification_key)| {
168                let kes_verification_key = KesPublicKey::from_bytes(&kes_verification_key).unwrap();
169                let kes_bytes = Sum6KesBytes(kes_bytes);
170
171                (kes_bytes, kes_verification_key)
172            },
173        )
174    }
175
176    fn generate_kes_key(kes_key_seed: &mut [u8]) -> (Sum6KesBytes, KesPublicKey) {
177        let mut key_buffer = [0u8; Sum6Kes::SIZE + 4];
178
179        let (kes_secret_key, kes_verification_key) = Sum6Kes::keygen(&mut key_buffer, kes_key_seed);
180        let mut kes_bytes = Sum6KesBytes([0u8; Sum6Kes::SIZE + 4]);
181        kes_bytes.0.copy_from_slice(&kes_secret_key.clone_sk());
182
183        (kes_bytes, kes_verification_key)
184    }
185
186    fn generate_cold_key_seed(&self, party_index: usize) -> Vec<u8> {
187        let mut cold_key_seed: Vec<_> = (party_index)
188            .to_le_bytes()
189            .iter()
190            .zip(self.party_id_seed)
191            .map(|(v1, v2)| v1 + v2)
192            .collect();
193        cold_key_seed.resize(32, 0);
194
195        cold_key_seed
196    }
197
198    fn build_party_with_operational_certificate(&self, party_index: usize) -> PartyId {
199        let cold_key_seed = self.generate_cold_key_seed(party_index).to_vec();
200        let mut kes_key_seed = cold_key_seed.clone();
201
202        let keypair =
203            ColdKeyGenerator::create_deterministic_keypair(cold_key_seed.try_into().unwrap());
204        let (kes_bytes, kes_verification_key) =
205            MithrilFixtureBuilder::provide_kes_key(&mut kes_key_seed);
206        let operational_certificate = OpCert::new(kes_verification_key, 0, 0, keypair);
207        let party_id = operational_certificate
208            .compute_protocol_party_id()
209            .expect("compute protocol party id should not fail");
210        let temp_dir = setup_temp_directory_for_signer(&party_id, true)
211            .expect("setup temp directory should return a value");
212        if !temp_dir.join("kes.sk").exists() {
213            kes_bytes
214                .to_file(temp_dir.join("kes.sk"))
215                .expect("KES secret key file export should not fail");
216        }
217        if !temp_dir.join("opcert.cert").exists() {
218            operational_certificate
219                .to_file(temp_dir.join("opcert.cert"))
220                .expect("operational certificate file export should not fail");
221        }
222        party_id
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use std::collections::BTreeSet;
230
231    #[test]
232    fn with_protocol_params() {
233        let protocol_parameters = ProtocolParameters::new(1, 10, 0.56);
234        let result = MithrilFixtureBuilder::default()
235            .with_protocol_parameters(protocol_parameters.clone())
236            .build();
237
238        assert_eq!(protocol_parameters, result.protocol_parameters());
239    }
240
241    #[test]
242    fn with_signers() {
243        let result = MithrilFixtureBuilder::default().with_signers(4).build();
244
245        assert_eq!(4, result.signers_with_stake().len());
246    }
247
248    #[test]
249    fn random_stake_distribution_generates_as_many_signers_as_parties() {
250        let result = MithrilFixtureBuilder::default()
251            .with_stake_distribution(StakeDistributionGenerationMethod::RandomDistribution {
252                seed: [0u8; 32],
253                min_stake: 1,
254            })
255            .with_signers(4)
256            .build();
257
258        assert_eq!(4, result.stake_distribution().len());
259    }
260
261    #[test]
262    fn uniform_stake_distribution() {
263        let expected_stake = 10;
264        let stake_distribution = MithrilFixtureBuilder::default()
265            .with_stake_distribution(StakeDistributionGenerationMethod::Uniform(expected_stake))
266            .with_signers(5)
267            .build()
268            .stake_distribution();
269
270        assert!(
271            stake_distribution
272                .iter()
273                .all(|(_, stake)| *stake == expected_stake),
274            "Generated stake distribution doesn't have uniform stakes: {stake_distribution:?}"
275        );
276    }
277
278    #[test]
279    fn each_parties_generated_with_random_stake_distribution_have_different_stakes() {
280        let result = MithrilFixtureBuilder::default()
281            .with_stake_distribution(StakeDistributionGenerationMethod::RandomDistribution {
282                seed: [0u8; 32],
283                min_stake: 1,
284            })
285            .with_signers(5)
286            .build();
287        let stakes = result.stake_distribution();
288
289        // BtreeSet dedup values
290        assert_eq!(stakes.len(), BTreeSet::from_iter(stakes.values()).len());
291    }
292
293    #[test]
294    fn dont_generate_party_ids_for_custom_stake_distribution() {
295        let stake_distribution = StakeDistribution::from_iter([("party".to_owned(), 4)]);
296        let builder = MithrilFixtureBuilder::default()
297            .with_stake_distribution(StakeDistributionGenerationMethod::Custom(
298                stake_distribution,
299            ))
300            .with_signers(5);
301
302        assert_eq!(Vec::<PartyId>::new(), builder.generate_party_ids());
303    }
304
305    #[test]
306    fn changing_party_id_seed_change_all_builded_party_ids() {
307        let first_signers = MithrilFixtureBuilder::default()
308            .with_signers(10)
309            .build()
310            .signers_with_stake();
311        let different_party_id_seed_signers = MithrilFixtureBuilder::default()
312            .with_signers(10)
313            .with_party_id_seed([1u8; 32])
314            .build()
315            .signers_with_stake();
316        let first_party_ids: Vec<&PartyId> = first_signers.iter().map(|s| &s.party_id).collect();
317
318        for party_id in different_party_id_seed_signers.iter().map(|s| &s.party_id) {
319            assert!(!first_party_ids.contains(&party_id));
320        }
321    }
322
323    /// Verify that there is a cached kes key for a number of party id.
324    /// If the cache is not up to date, the test will generate the code that can be copied/pasted into the [precomputed_kes_key] module.
325    /// The number of party id that should be in cache is defined with `precomputed_number`
326    #[test]
327    fn verify_kes_key_cache_content() {
328        // Generate code that should be in the `cached_kes_key` function of the `precomputed_kes_key.rs` file.
329        // It can be copied and pasted to update the cache.
330        fn generate_code(party_ids: &Vec<(&[u8], [u8; 612], KesPublicKey)>) -> String {
331            party_ids
332                .iter()
333                .map(|(key, i, p)| format!("{:?} => ({:?}, {:?}),", key, i, p.as_bytes()))
334                .collect::<Vec<_>>()
335                .join("\n")
336        }
337
338        let precomputed_number = 10;
339
340        let fixture = MithrilFixtureBuilder::default();
341        let cold_keys: Vec<_> = (0..precomputed_number)
342            .map(|party_index| fixture.generate_cold_key_seed(party_index))
343            .collect();
344
345        let computed_keys_key: Vec<_> = cold_keys
346            .iter()
347            .map(|cold_key| {
348                let mut kes_key_seed: Vec<u8> = cold_key.clone();
349                let (kes_bytes, kes_verification_key) =
350                    MithrilFixtureBuilder::generate_kes_key(&mut kes_key_seed);
351
352                (cold_key.as_slice(), kes_bytes.0, kes_verification_key)
353            })
354            .collect();
355
356        let cached_kes_key: Vec<_> = cold_keys
357            .iter()
358            .filter_map(|cold_key| {
359                MithrilFixtureBuilder::cached_kes_key(cold_key).map(
360                    |(kes_bytes, kes_verification_key)| {
361                        (cold_key.as_slice(), kes_bytes.0, kes_verification_key)
362                    },
363                )
364            })
365            .collect();
366
367        let expected_code = generate_code(&computed_keys_key);
368        let actual_code = generate_code(&cached_kes_key);
369
370        assert_eq!(
371            computed_keys_key, cached_kes_key,
372            "Precomputed KES keys should be:\n{expected_code}\nbut seems to be:\n{actual_code}"
373        );
374
375        let kes_key_seed = fixture.generate_cold_key_seed(precomputed_number);
376        assert!(
377            MithrilFixtureBuilder::cached_kes_key(kes_key_seed.as_slice()).is_none(),
378            "We checked precomputed KES keys up to {precomputed_number} but it seems to be more."
379        );
380    }
381}