mithril_common/test_utils/
fake_data.rs

1//! Fake data builders for testing.
2
3use chrono::{DateTime, Utc};
4use semver::Version;
5
6use crate::CardanoNetwork;
7use crate::crypto_helper::{self, ProtocolMultiSignature};
8use crate::entities::{
9    self, AncillaryLocations, BlockNumber, CardanoDatabaseSnapshotArtifactData,
10    CertificateMetadata, CertificateSignature, CompressionAlgorithm, DigestsLocations, Epoch,
11    ImmutablesLocations, LotteryIndex, ProtocolMessage, ProtocolMessagePartKey, SignedEntityType,
12    SingleSignature, SlotNumber, StakeDistribution, StakeDistributionParty,
13};
14use crate::test_utils::MithrilFixtureBuilder;
15
16use super::fake_keys;
17
18/// Fake network
19pub fn network() -> crate::CardanoNetwork {
20    crate::CardanoNetwork::DevNet(10)
21}
22
23/// Fake Beacon
24pub fn beacon() -> entities::CardanoDbBeacon {
25    let time_point = entities::TimePoint::dummy();
26    entities::CardanoDbBeacon::new(*time_point.epoch, time_point.immutable_file_number)
27}
28
29/// Fake Epoch
30pub fn epoch() -> Epoch {
31    let time_point = entities::TimePoint::dummy();
32    time_point.epoch
33}
34
35/// Fake ChainPoint
36pub fn chain_point() -> entities::ChainPoint {
37    entities::ChainPoint {
38        slot_number: SlotNumber(500),
39        block_number: BlockNumber(42),
40        block_hash: "1b69b3202fbe500".to_string(),
41    }
42}
43
44/// Fake ProtocolParameters
45pub fn protocol_parameters() -> entities::ProtocolParameters {
46    let k = 5;
47    let m = 100;
48    let phi_f = 0.65;
49    entities::ProtocolParameters::new(k, m, phi_f)
50}
51
52/// Fake ProtocolInitializer
53pub fn protocol_initializer<S: Into<String>>(
54    seed: S,
55    stake: entities::Stake,
56) -> crypto_helper::ProtocolInitializer {
57    use rand_chacha::ChaCha20Rng;
58    use rand_core::SeedableRng;
59
60    let protocol_parameters = protocol_parameters();
61    let seed: [u8; 32] = format!("{:<032}", seed.into()).as_bytes()[..32].try_into().unwrap();
62    let mut rng = ChaCha20Rng::from_seed(seed);
63    let kes_period = Some(0);
64    crypto_helper::ProtocolInitializer::setup(
65        protocol_parameters.into(),
66        None,
67        kes_period,
68        stake,
69        &mut rng,
70    )
71    .unwrap()
72}
73
74/// Fake Genesis Certificate
75pub fn genesis_certificate<T: Into<String>>(certificate_hash: T) -> entities::Certificate {
76    let multi_signature = fake_keys::genesis_signature()[1].to_string();
77
78    entities::Certificate {
79        previous_hash: String::new(),
80        signature: CertificateSignature::GenesisSignature(multi_signature.try_into().unwrap()),
81        ..certificate(certificate_hash)
82    }
83}
84
85/// Fake Certificate
86pub fn certificate<T: Into<String>>(certificate_hash: T) -> entities::Certificate {
87    let hash = certificate_hash.into();
88
89    // Beacon
90    let beacon = beacon();
91
92    // Protocol parameters
93    let protocol_parameters = protocol_parameters();
94
95    // Signers with stakes
96    let signers: Vec<StakeDistributionParty> =
97        signers_with_stakes(5).into_iter().map(|s| s.into()).collect();
98
99    // Certificate metadata
100    let protocol_version = crypto_helper::PROTOCOL_VERSION.to_string();
101    let initiated_at = DateTime::parse_from_rfc3339("2006-01-02T15:04:05Z")
102        .unwrap()
103        .with_timezone(&Utc);
104    let sealed_at = DateTime::parse_from_rfc3339("2006-01-02T15:04:05Z")
105        .unwrap()
106        .with_timezone(&Utc);
107    let metadata = CertificateMetadata::new(
108        network(),
109        protocol_version,
110        protocol_parameters,
111        initiated_at,
112        sealed_at,
113        signers,
114    );
115
116    // Protocol message
117    let next_aggregate_verification_key = fake_keys::aggregate_verification_key()[2].to_owned();
118    let mut protocol_message = ProtocolMessage::new();
119    let snapshot_digest = format!("1{}", beacon.immutable_file_number).repeat(20);
120    protocol_message.set_message_part(ProtocolMessagePartKey::SnapshotDigest, snapshot_digest);
121    protocol_message.set_message_part(
122        ProtocolMessagePartKey::NextAggregateVerificationKey,
123        next_aggregate_verification_key,
124    );
125
126    // Certificate
127    let previous_hash = format!("{hash}0");
128    let aggregate_verification_key = fake_keys::aggregate_verification_key()[1].try_into().unwrap();
129    let multi_signature: ProtocolMultiSignature =
130        fake_keys::multi_signature()[0].try_into().unwrap();
131
132    entities::Certificate {
133        hash,
134        previous_hash,
135        epoch: beacon.epoch,
136        metadata,
137        protocol_message,
138        signed_message: "".to_string(),
139        aggregate_verification_key,
140        signature: CertificateSignature::MultiSignature(
141            SignedEntityType::CardanoImmutableFilesFull(beacon),
142            multi_signature,
143        ),
144    }
145}
146
147/// Fake SignersWithStake
148pub fn signers_with_stakes(total: usize) -> Vec<entities::SignerWithStake> {
149    MithrilFixtureBuilder::default()
150        .with_signers(total)
151        .build()
152        .signers_with_stake()
153}
154
155/// Fake Signers
156pub fn signers(total: usize) -> Vec<entities::Signer> {
157    signers_with_stakes(total)
158        .into_iter()
159        .map(|signer| signer.into())
160        .collect::<Vec<entities::Signer>>()
161}
162
163/// Fake SingleSignature
164pub fn single_signature(won_indexes: Vec<LotteryIndex>) -> SingleSignature {
165    let party_id = "party_id".to_string();
166    let signature = fake_keys::single_signature()[0].try_into().unwrap();
167
168    SingleSignature::new(party_id, signature, won_indexes)
169}
170
171/// Fake Snapshots
172pub fn snapshots(total: u64) -> Vec<entities::Snapshot> {
173    (1..total + 1)
174        .map(|snapshot_id| {
175            let digest = format!("1{snapshot_id}").repeat(20);
176            let mut beacon = beacon();
177            beacon.immutable_file_number += snapshot_id;
178            let certificate_hash = "123".to_string();
179            let size = snapshot_id * 100_000;
180            let ancillary_size = snapshot_id * 10_000;
181            let cardano_node_version = Version::parse("1.0.0").unwrap();
182            let locations = vec![
183                format!("http://{certificate_hash}"),
184                format!("http2://{certificate_hash}"),
185            ];
186            let ancillary_locations = vec![
187                format!("http://ancillary-{certificate_hash}"),
188                format!("http2://ancillary-{certificate_hash}"),
189            ];
190
191            entities::Snapshot {
192                digest,
193                network: network().into(),
194                beacon,
195                size,
196                ancillary_size: Some(ancillary_size),
197                locations,
198                ancillary_locations: Some(ancillary_locations),
199                compression_algorithm: CompressionAlgorithm::Gzip,
200                cardano_node_version: cardano_node_version.to_string(),
201            }
202        })
203        .collect::<Vec<entities::Snapshot>>()
204}
205
206/// Fake Mithril Stake Distribution
207pub fn mithril_stake_distributions(total: u64) -> Vec<entities::MithrilStakeDistribution> {
208    let signers = signers_with_stakes(5);
209
210    (1..total + 1)
211        .map(|epoch_idx| entities::MithrilStakeDistribution {
212            epoch: Epoch(epoch_idx),
213            signers_with_stake: signers.clone(),
214            hash: format!("hash-epoch-{epoch_idx}"),
215            protocol_parameters: protocol_parameters(),
216        })
217        .collect::<Vec<entities::MithrilStakeDistribution>>()
218}
219
220/// Fake Cardano Transactions
221pub fn cardano_transactions_snapshot(total: u64) -> Vec<entities::CardanoTransactionsSnapshot> {
222    (1..total + 1)
223        .map(|idx| {
224            entities::CardanoTransactionsSnapshot::new(
225                format!("merkleroot-{idx}"),
226                BlockNumber(idx),
227            )
228        })
229        .collect()
230}
231
232/// Fake transaction hashes that have valid length & characters
233pub const fn transaction_hashes<'a>() -> [&'a str; 5] {
234    [
235        "c96809e2cecd9e27499a4379094c4e1f7b59d918c96327bd8daf1bf909dae332",
236        "5b8788784af9c414f18fc1e6161005b13b839fd91130b7c109aeba1792feb843",
237        "8b6ae44edf877ff2ac80cf067809d575ab2bad234b668f91e90decde837b154a",
238        "3f6f3c981c89097f62c9b43632875db7a52183ad3061c822d98259d18cd63dcf",
239        "f4fd91dccc25fd63f2caebab3d3452bc4b2944fcc11652214a3e8f1d32b09713",
240    ]
241}
242
243/// Fake Cardano Stake Distributions
244pub fn cardano_stake_distributions(total: u64) -> Vec<entities::CardanoStakeDistribution> {
245    (1..total + 1)
246        .map(|epoch_idx| cardano_stake_distribution(Epoch(epoch_idx)))
247        .collect::<Vec<entities::CardanoStakeDistribution>>()
248}
249
250/// Fake Cardano Stake Distribution
251pub fn cardano_stake_distribution(epoch: Epoch) -> entities::CardanoStakeDistribution {
252    let stake_distribution = StakeDistribution::from([("pool-1".to_string(), 100)]);
253    entities::CardanoStakeDistribution {
254        hash: format!("hash-epoch-{epoch}"),
255        epoch,
256        stake_distribution,
257    }
258}
259
260/// Fake Cardano Database snapshots
261pub fn cardano_database_snapshots(total: u64) -> Vec<entities::CardanoDatabaseSnapshot> {
262    (1..total + 1)
263        .map(|cardano_database_id| {
264            let merkle_root = format!("1{cardano_database_id}").repeat(20);
265            let mut beacon = beacon();
266            beacon.immutable_file_number += cardano_database_id;
267            let total_db_size_uncompressed = cardano_database_id * 100000;
268            let cardano_node_version = Version::parse("1.0.0").unwrap();
269
270            entities::CardanoDatabaseSnapshot::new(
271                merkle_root,
272                CardanoNetwork::DevNet(63),
273                beacon,
274                CardanoDatabaseSnapshotArtifactData {
275                    total_db_size_uncompressed,
276                    digests: DigestsLocations::default(),
277                    immutables: ImmutablesLocations::default(),
278                    ancillary: AncillaryLocations::default(),
279                },
280                &cardano_node_version,
281            )
282        })
283        .collect::<Vec<entities::CardanoDatabaseSnapshot>>()
284}