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
//! Fake data builders for testing.

use chrono::{DateTime, Utc};
use semver::Version;

use crate::crypto_helper::{self, ProtocolMultiSignature};
use crate::entities::{
    self, BlockNumber, CertificateMetadata, CertificateSignature, CompressionAlgorithm, Epoch,
    LotteryIndex, ProtocolMessage, ProtocolMessagePartKey, SignedEntityType, SingleSignatures,
    SlotNumber, StakeDistribution, StakeDistributionParty,
};
use crate::test_utils::MithrilFixtureBuilder;

use super::fake_keys;

/// Fake network
pub fn network() -> crate::CardanoNetwork {
    crate::CardanoNetwork::DevNet(10)
}

/// Fake Beacon
pub fn beacon() -> entities::CardanoDbBeacon {
    let time_point = entities::TimePoint::dummy();
    entities::CardanoDbBeacon::new(*time_point.epoch, time_point.immutable_file_number)
}

/// Fake ChainPoint
pub fn chain_point() -> entities::ChainPoint {
    entities::ChainPoint {
        slot_number: SlotNumber(500),
        block_number: BlockNumber(42),
        block_hash: "1b69b3202fbe500".to_string(),
    }
}

/// Fake ProtocolParameters
pub fn protocol_parameters() -> entities::ProtocolParameters {
    let k = 5;
    let m = 100;
    let phi_f = 0.65;
    entities::ProtocolParameters::new(k, m, phi_f)
}

cfg_random! {
    /// Fake ProtocolInitializer
    pub fn protocol_initializer<S: Into<String>>(
        seed: S,
        stake: entities::Stake,
    ) -> crypto_helper::ProtocolInitializer {
        use rand_chacha::ChaCha20Rng;
        use rand_core::SeedableRng;

        let protocol_parameters = protocol_parameters();
        let seed: [u8; 32] = format!("{:<032}", seed.into()).as_bytes()[..32]
            .try_into()
            .unwrap();
        let mut rng = ChaCha20Rng::from_seed(seed);
        let kes_secret_key_path: Option<std::path::PathBuf> = None;
        let kes_period = Some(0);

        crypto_helper::ProtocolInitializer::setup(
            protocol_parameters.into(),
            kes_secret_key_path,
            kes_period,
            stake,
            &mut rng,
        ).unwrap()
    }
}

/// Fake CertificatePending
pub fn certificate_pending() -> entities::CertificatePending {
    // Epoch
    let epoch = beacon().epoch;

    // Signed entity type
    let signed_entity_type = SignedEntityType::dummy();

    // Protocol parameters
    let next_protocol_parameters = protocol_parameters();
    let protocol_parameters = protocol_parameters();

    // Signers
    let signers = signers(5);
    let current_signers = signers[1..3].to_vec();
    let next_signers = signers[2..5].to_vec();

    // Certificate pending
    entities::CertificatePending::new(
        epoch,
        signed_entity_type,
        protocol_parameters,
        next_protocol_parameters,
        current_signers,
        next_signers,
    )
}

/// Fake Genesis Certificate
pub fn genesis_certificate<T: Into<String>>(certificate_hash: T) -> entities::Certificate {
    let multi_signature = fake_keys::genesis_signature()[1].to_string();

    entities::Certificate {
        previous_hash: String::new(),
        signature: CertificateSignature::GenesisSignature(multi_signature.try_into().unwrap()),
        ..certificate(certificate_hash)
    }
}

/// Fake Certificate
pub fn certificate<T: Into<String>>(certificate_hash: T) -> entities::Certificate {
    let hash = certificate_hash.into();

    // Beacon
    let beacon = beacon();

    // Protocol parameters
    let protocol_parameters = protocol_parameters();

    // Signers with stakes
    let signers: Vec<StakeDistributionParty> = signers_with_stakes(5)
        .into_iter()
        .map(|s| s.into())
        .collect();

    // Certificate metadata
    let protocol_version = crypto_helper::PROTOCOL_VERSION.to_string();
    let initiated_at = DateTime::parse_from_rfc3339("2006-01-02T15:04:05Z")
        .unwrap()
        .with_timezone(&Utc);
    let sealed_at = DateTime::parse_from_rfc3339("2006-01-02T15:04:05Z")
        .unwrap()
        .with_timezone(&Utc);
    let metadata = CertificateMetadata::new(
        network(),
        protocol_version,
        protocol_parameters,
        initiated_at,
        sealed_at,
        signers,
    );

    // Protocol message
    let next_aggregate_verification_key = fake_keys::aggregate_verification_key()[2].to_owned();
    let mut protocol_message = ProtocolMessage::new();
    let snapshot_digest = format!("1{}", beacon.immutable_file_number).repeat(20);
    protocol_message.set_message_part(ProtocolMessagePartKey::SnapshotDigest, snapshot_digest);
    protocol_message.set_message_part(
        ProtocolMessagePartKey::NextAggregateVerificationKey,
        next_aggregate_verification_key,
    );

    // Certificate
    let previous_hash = format!("{hash}0");
    let aggregate_verification_key = fake_keys::aggregate_verification_key()[1]
        .try_into()
        .unwrap();
    let multi_signature: ProtocolMultiSignature =
        fake_keys::multi_signature()[0].try_into().unwrap();

    entities::Certificate {
        hash,
        previous_hash,
        epoch: beacon.epoch,
        metadata,
        protocol_message,
        signed_message: "".to_string(),
        aggregate_verification_key,
        signature: CertificateSignature::MultiSignature(
            SignedEntityType::CardanoImmutableFilesFull(beacon),
            multi_signature,
        ),
    }
}

/// Fake SignersWithStake
pub fn signers_with_stakes(total: usize) -> Vec<entities::SignerWithStake> {
    MithrilFixtureBuilder::default()
        .with_signers(total)
        .build()
        .signers_with_stake()
}

/// Fake Signers
pub fn signers(total: usize) -> Vec<entities::Signer> {
    signers_with_stakes(total)
        .into_iter()
        .map(|signer| signer.into())
        .collect::<Vec<entities::Signer>>()
}

/// Fake SingleSignatures
pub fn single_signatures(won_indexes: Vec<LotteryIndex>) -> SingleSignatures {
    let party_id = "party_id".to_string();
    let signature = fake_keys::single_signature()[0].try_into().unwrap();

    SingleSignatures::new(party_id, signature, won_indexes)
}

/// Fake Snapshots
pub fn snapshots(total: u64) -> Vec<entities::Snapshot> {
    (1..total + 1)
        .map(|snapshot_id| {
            let digest = format!("1{snapshot_id}").repeat(20);
            let mut beacon = beacon();
            beacon.immutable_file_number += snapshot_id;
            let certificate_hash = "123".to_string();
            let size = snapshot_id * 100000;
            let cardano_node_version = Version::parse("1.0.0").unwrap();
            let mut locations = Vec::new();
            locations.push(format!("http://{certificate_hash}"));
            locations.push(format!("http2://{certificate_hash}"));

            entities::Snapshot::new(
                digest,
                network(),
                beacon,
                size,
                locations,
                CompressionAlgorithm::Gzip,
                &cardano_node_version,
            )
        })
        .collect::<Vec<entities::Snapshot>>()
}

/// Fake Mithril Stake Distribution
pub fn mithril_stake_distributions(total: u64) -> Vec<entities::MithrilStakeDistribution> {
    let signers = signers_with_stakes(5);

    (1..total + 1)
        .map(|epoch_idx| entities::MithrilStakeDistribution {
            epoch: Epoch(epoch_idx),
            signers_with_stake: signers.clone(),
            hash: format!("hash-epoch-{epoch_idx}"),
            protocol_parameters: protocol_parameters(),
        })
        .collect::<Vec<entities::MithrilStakeDistribution>>()
}

/// Fake Cardano Transactions
pub fn cardano_transactions_snapshot(total: u64) -> Vec<entities::CardanoTransactionsSnapshot> {
    (1..total + 1)
        .map(|idx| {
            entities::CardanoTransactionsSnapshot::new(
                format!("merkleroot-{idx}"),
                BlockNumber(idx),
            )
        })
        .collect()
}

/// Fake transaction hashes that have valid length & characters
pub const fn transaction_hashes<'a>() -> [&'a str; 5] {
    [
        "c96809e2cecd9e27499a4379094c4e1f7b59d918c96327bd8daf1bf909dae332",
        "5b8788784af9c414f18fc1e6161005b13b839fd91130b7c109aeba1792feb843",
        "8b6ae44edf877ff2ac80cf067809d575ab2bad234b668f91e90decde837b154a",
        "3f6f3c981c89097f62c9b43632875db7a52183ad3061c822d98259d18cd63dcf",
        "f4fd91dccc25fd63f2caebab3d3452bc4b2944fcc11652214a3e8f1d32b09713",
    ]
}

/// Fake Cardano Stake Distributions
pub fn cardano_stake_distributions(total: u64) -> Vec<entities::CardanoStakeDistribution> {
    (1..total + 1)
        .map(|epoch_idx| cardano_stake_distribution(Epoch(epoch_idx)))
        .collect::<Vec<entities::CardanoStakeDistribution>>()
}

/// Fake Cardano Stake Distribution
pub fn cardano_stake_distribution(epoch: Epoch) -> entities::CardanoStakeDistribution {
    let stake_distribution = StakeDistribution::from([("pool-1".to_string(), 100)]);
    entities::CardanoStakeDistribution {
        hash: format!("hash-epoch-{epoch}"),
        epoch,
        stake_distribution,
    }
}