mithril_common/test/double/
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::{builder::MithrilFixtureBuilder, double::Dummy};
15
16use super::fake_keys;
17
18/// Fake network
19pub fn network() -> CardanoNetwork {
20    CardanoNetwork::TestNet(CardanoNetwork::DEVNET_MAGIC_ID)
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!("{:0>20}", beacon.immutable_file_number);
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 Snapshot
172pub fn snapshot(snapshot_id: u64) -> entities::Snapshot {
173    let digest = format!("snapshot-{snapshot_id:0>11}");
174    let mut beacon = beacon();
175    beacon.immutable_file_number += snapshot_id;
176    let certificate_hash = "123".to_string();
177    let size = snapshot_id * 100_000;
178    let ancillary_size = snapshot_id * 10_000;
179    let cardano_node_version = Version::parse("1.0.0").unwrap();
180    let locations = vec![
181        format!("http://{certificate_hash}"),
182        format!("http2://{certificate_hash}"),
183    ];
184    let ancillary_locations = vec![
185        format!("http://ancillary-{certificate_hash}"),
186        format!("http2://ancillary-{certificate_hash}"),
187    ];
188
189    entities::Snapshot {
190        digest,
191        network: network().into(),
192        beacon,
193        size,
194        ancillary_size: Some(ancillary_size),
195        locations,
196        ancillary_locations: Some(ancillary_locations),
197        compression_algorithm: CompressionAlgorithm::Gzip,
198        cardano_node_version: cardano_node_version.to_string(),
199    }
200}
201
202/// Fake Snapshots list
203pub fn snapshots(total: u64) -> Vec<entities::Snapshot> {
204    (1..total + 1).map(snapshot).collect()
205}
206
207/// Fake Mithril Stake Distribution
208pub fn mithril_stake_distribution(
209    epoch: Epoch,
210    signers_with_stake: Vec<entities::SignerWithStake>,
211) -> entities::MithrilStakeDistribution {
212    entities::MithrilStakeDistribution {
213        epoch,
214        signers_with_stake,
215        hash: format!("msd-{epoch}"),
216        protocol_parameters: protocol_parameters(),
217    }
218}
219
220/// Fake Mithril Stake Distribution list
221pub fn mithril_stake_distributions(total: u64) -> Vec<entities::MithrilStakeDistribution> {
222    let signers = signers_with_stakes(5);
223
224    (1..total + 1)
225        .map(|epoch_idx| mithril_stake_distribution(Epoch(epoch_idx), signers.clone()))
226        .collect()
227}
228
229/// Fake Cardano Transaction
230pub fn cardano_transactions_snapshot(
231    block_number: BlockNumber,
232) -> entities::CardanoTransactionsSnapshot {
233    entities::CardanoTransactionsSnapshot::new(format!("merkleroot-{block_number}"), block_number)
234}
235
236/// Fake Cardano Transactions list
237pub fn cardano_transactions_snapshots(total: u64) -> Vec<entities::CardanoTransactionsSnapshot> {
238    (1..total + 1)
239        .map(|idx| cardano_transactions_snapshot(BlockNumber(idx)))
240        .collect()
241}
242
243/// Fake Cardano Stake Distribution
244pub fn cardano_stake_distribution(epoch: Epoch) -> entities::CardanoStakeDistribution {
245    let stake_distribution = StakeDistribution::from([("pool-1".to_string(), 100)]);
246    entities::CardanoStakeDistribution {
247        hash: format!("csd-{epoch}"),
248        epoch,
249        stake_distribution,
250    }
251}
252
253/// Fake Cardano Stake Distributions list
254pub fn cardano_stake_distributions(total: u64) -> Vec<entities::CardanoStakeDistribution> {
255    (1..total + 1)
256        .map(|epoch_idx| cardano_stake_distribution(Epoch(epoch_idx)))
257        .collect()
258}
259
260/// Fake Cardano Database snapshots
261pub fn cardano_database_snapshot(
262    immutable_file_number: entities::ImmutableFileNumber,
263) -> entities::CardanoDatabaseSnapshot {
264    let merkle_root = format!("cdb-{immutable_file_number:0>16}");
265    let mut beacon = beacon();
266    beacon.immutable_file_number += immutable_file_number;
267    let total_db_size_uncompressed = immutable_file_number * 100000;
268    let cardano_node_version = Version::parse("1.0.0").unwrap();
269
270    entities::CardanoDatabaseSnapshot::new(
271        merkle_root,
272        CardanoNetwork::TestNet(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
284/// Fake Cardano Database snapshots list
285pub fn cardano_database_snapshots(total: u64) -> Vec<entities::CardanoDatabaseSnapshot> {
286    (1..total + 1).map(cardano_database_snapshot).collect()
287}
288
289/// Fake transaction hashes that have valid length & characters
290pub const fn transaction_hashes<'a>() -> [&'a str; 5] {
291    [
292        "c96809e2cecd9e27499a4379094c4e1f7b59d918c96327bd8daf1bf909dae332",
293        "5b8788784af9c414f18fc1e6161005b13b839fd91130b7c109aeba1792feb843",
294        "8b6ae44edf877ff2ac80cf067809d575ab2bad234b668f91e90decde837b154a",
295        "3f6f3c981c89097f62c9b43632875db7a52183ad3061c822d98259d18cd63dcf",
296        "f4fd91dccc25fd63f2caebab3d3452bc4b2944fcc11652214a3e8f1d32b09713",
297    ]
298}