mithril-common 0.6.67

Common types, interfaces, and utilities for Mithril nodes.
Documentation
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
#[cfg(feature = "future_snark")]
use crate::crypto_helper::{
    ProtocolSignerVerificationKeyForSnark, ProtocolSignerVerificationKeySignatureForSnark,
};
use crate::{
    crypto_helper::{
        KesEvolutions, ProtocolOpCert, ProtocolSignerVerificationKeyForConcatenation,
        ProtocolSignerVerificationKeySignatureForConcatenation,
    },
    entities::{PartyId, Stake},
};
use std::fmt::{Debug, Formatter};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

/// Signer represents a signing participant in the network
#[derive(Clone, Eq, Serialize, Deserialize)]
pub struct Signer {
    /// The unique identifier of the signer
    ///
    /// Used only for testing when SPO pool id is not certified
    pub party_id: PartyId,

    /// The verification key for the Concatenation proof system
    #[serde(rename = "verification_key")]
    pub verification_key_for_concatenation: ProtocolSignerVerificationKeyForConcatenation,

    /// The KES signature over the verification key for Concatenation
    ///
    /// None is used only for testing when SPO pool id is not certified
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "verification_key_signature"
    )]
    pub verification_key_signature_for_concatenation:
        Option<ProtocolSignerVerificationKeySignatureForConcatenation>,

    /// The operational certificate of stake pool operator attached to the signer node
    ///
    /// None is used only for testing when SPO pool id is not certified
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operational_certificate: Option<ProtocolOpCert>,

    /// The number of evolutions of the KES key since the start KES period of the operational certificate at the time of signature.
    #[serde(rename = "kes_period", skip_serializing_if = "Option::is_none")]
    pub kes_evolutions: Option<KesEvolutions>,

    /// The verification key for the SNARK proof system
    #[cfg(feature = "future_snark")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub verification_key_for_snark: Option<ProtocolSignerVerificationKeyForSnark>,

    /// The KES signature over the verification key for SNARK
    #[cfg(feature = "future_snark")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub verification_key_signature_for_snark:
        Option<ProtocolSignerVerificationKeySignatureForSnark>,
}

impl PartialEq for Signer {
    fn eq(&self, other: &Self) -> bool {
        self.party_id.eq(&other.party_id)
    }
}

impl PartialOrd for Signer {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Signer {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.party_id.cmp(&other.party_id)
    }
}

impl Signer {
    /// Convert the given values to a vec of signers.
    pub fn vec_from<T: Into<Signer>>(from: Vec<T>) -> Vec<Self> {
        from.into_iter().map(|f| f.into()).collect()
    }

    /// Computes the hash of Signer
    pub fn compute_hash(&self) -> String {
        let mut hasher = Sha256::new();
        hasher.update(self.party_id.as_bytes());
        hasher.update(
            self.verification_key_for_concatenation
                .to_json_hex()
                .unwrap()
                .as_bytes(),
        );

        if let Some(verification_key_signature) = &self.verification_key_signature_for_concatenation
        {
            hasher.update(verification_key_signature.to_json_hex().unwrap().as_bytes());
        }
        if let Some(operational_certificate) = &self.operational_certificate {
            hasher.update(operational_certificate.to_json_hex().unwrap().as_bytes());
        }

        #[cfg(feature = "future_snark")]
        if let Some(verification_key_for_snark) = &self.verification_key_for_snark {
            hasher.update(verification_key_for_snark.to_json_hex().unwrap().as_bytes());
        }
        #[cfg(feature = "future_snark")]
        if let Some(verification_key_signature_for_snark) =
            &self.verification_key_signature_for_snark
        {
            hasher.update(verification_key_signature_for_snark.to_json_hex().unwrap().as_bytes());
        }

        hex::encode(hasher.finalize())
    }
}

impl Debug for Signer {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let should_be_exhaustive = f.alternate();
        let mut debug = f.debug_struct("Signer");
        debug.field("party_id", &self.party_id);

        match should_be_exhaustive {
            true => {
                debug
                    .field(
                        "verification_key_for_concatenation",
                        &format_args!("{:?}", self.verification_key_for_concatenation),
                    )
                    .field(
                        "verification_key_signature_for_concatenation",
                        &format_args!("{:?}", self.verification_key_signature_for_concatenation),
                    )
                    .field(
                        "operational_certificate",
                        &format_args!("{:?}", self.operational_certificate),
                    )
                    .field("kes_evolutions", &format_args!("{:?}", self.kes_evolutions));

                #[cfg(feature = "future_snark")]
                {
                    debug
                        .field(
                            "verification_key_for_snark",
                            &format_args!("{:?}", self.verification_key_for_snark),
                        )
                        .field(
                            "verification_key_signature_for_snark",
                            &format_args!("{:?}", self.verification_key_signature_for_snark),
                        );
                }

                debug.finish()
            }
            false => debug.finish_non_exhaustive(),
        }
    }
}

impl From<SignerWithStake> for Signer {
    fn from(other: SignerWithStake) -> Self {
        Self {
            party_id: other.party_id,
            verification_key_for_concatenation: other.verification_key_for_concatenation,
            verification_key_signature_for_concatenation: other
                .verification_key_signature_for_concatenation,
            operational_certificate: other.operational_certificate,
            kes_evolutions: other.kes_evolutions,
            #[cfg(feature = "future_snark")]
            verification_key_for_snark: other.verification_key_for_snark,
            #[cfg(feature = "future_snark")]
            verification_key_signature_for_snark: other.verification_key_signature_for_snark,
        }
    }
}

/// Signer represents a signing party in the network (including its stakes)
#[derive(Clone, Eq, Serialize, Deserialize)]
pub struct SignerWithStake {
    /// The unique identifier of the signer
    ///
    /// Used only for testing when SPO pool id is not certified
    pub party_id: PartyId,

    /// The verification key for the Concatenation proof system
    #[serde(rename = "verification_key")]
    pub verification_key_for_concatenation: ProtocolSignerVerificationKeyForConcatenation,

    /// The KES signature over the verification key for Concatenation
    ///
    /// None is used only for testing when SPO pool id is not certified
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "verification_key_signature"
    )]
    pub verification_key_signature_for_concatenation:
        Option<ProtocolSignerVerificationKeySignatureForConcatenation>,

    /// The operational certificate of stake pool operator attached to the signer node
    ///
    /// None is used only for testing when SPO pool id is not certified
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operational_certificate: Option<ProtocolOpCert>,

    /// The number of evolutions of the KES key since the start KES period of the operational certificate at the time of signature.
    #[serde(rename = "kes_period", skip_serializing_if = "Option::is_none")]
    pub kes_evolutions: Option<KesEvolutions>,

    /// The signer stake
    pub stake: Stake,

    /// The verification key for the SNARK proof system
    #[cfg(feature = "future_snark")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub verification_key_for_snark: Option<ProtocolSignerVerificationKeyForSnark>,

    /// The KES signature over the verification key for SNARK (hex encoded)
    #[cfg(feature = "future_snark")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub verification_key_signature_for_snark:
        Option<ProtocolSignerVerificationKeySignatureForSnark>,
}

impl PartialEq for SignerWithStake {
    fn eq(&self, other: &Self) -> bool {
        self.party_id.eq(&other.party_id)
    }
}

impl PartialOrd for SignerWithStake {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SignerWithStake {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.party_id.cmp(&other.party_id)
    }
}

impl SignerWithStake {
    /// Turn a [Signer] into a [SignerWithStake].
    pub fn from_signer(signer: Signer, stake: Stake) -> Self {
        Self {
            party_id: signer.party_id,
            verification_key_for_concatenation: signer.verification_key_for_concatenation,
            verification_key_signature_for_concatenation: signer
                .verification_key_signature_for_concatenation,
            operational_certificate: signer.operational_certificate,
            kes_evolutions: signer.kes_evolutions,
            stake,
            #[cfg(feature = "future_snark")]
            verification_key_for_snark: signer.verification_key_for_snark,
            #[cfg(feature = "future_snark")]
            verification_key_signature_for_snark: signer.verification_key_signature_for_snark,
        }
    }

    /// Remove SNARK-related fields for backward compatibility with older eras.
    ///
    /// This clears the SNARK verification key and its KES signature, which is needed
    /// during eras that do not support SNARK proofs (e.g. Pythagoras) to ensure
    /// consistency between the signer's initializer and the key registration entries.
    #[cfg(feature = "future_snark")]
    pub fn without_snark_fields(mut self) -> Self {
        self.verification_key_for_snark = None;
        self.verification_key_signature_for_snark = None;
        self
    }

    /// Remove SNARK-related fields from a list of signers with stake for backward compatibility.
    #[cfg(feature = "future_snark")]
    pub fn strip_snark_fields(signers: Vec<Self>) -> Vec<Self> {
        signers.into_iter().map(Self::without_snark_fields).collect()
    }

    /// Computes the hash of SignerWithStake
    pub fn compute_hash(&self) -> String {
        let mut hasher = Sha256::new();
        hasher.update(self.party_id.as_bytes());
        hasher.update(
            self.verification_key_for_concatenation
                .to_json_hex()
                .unwrap()
                .as_bytes(),
        );

        if let Some(verification_key_signature) = &self.verification_key_signature_for_concatenation
        {
            hasher.update(verification_key_signature.to_json_hex().unwrap().as_bytes());
        }
        if let Some(operational_certificate) = &self.operational_certificate {
            hasher.update(operational_certificate.to_json_hex().unwrap().as_bytes());
        }
        hasher.update(self.stake.to_be_bytes());

        #[cfg(feature = "future_snark")]
        if let Some(verification_key_for_snark) = &self.verification_key_for_snark {
            hasher.update(verification_key_for_snark.to_json_hex().unwrap().as_bytes());
        }
        #[cfg(feature = "future_snark")]
        if let Some(verification_key_signature_for_snark) =
            &self.verification_key_signature_for_snark
        {
            hasher.update(verification_key_signature_for_snark.to_json_hex().unwrap().as_bytes());
        }

        hex::encode(hasher.finalize())
    }
}

impl Debug for SignerWithStake {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let should_be_exhaustive = f.alternate();
        let mut debug = f.debug_struct("SignerWithStake");
        debug.field("party_id", &self.party_id).field("stake", &self.stake);

        match should_be_exhaustive {
            true => {
                debug
                    .field(
                        "verification_key_for_concatenation",
                        &format_args!("{:?}", self.verification_key_for_concatenation),
                    )
                    .field(
                        "verification_key_signature_for_concatenation",
                        &format_args!("{:?}", self.verification_key_signature_for_concatenation),
                    )
                    .field(
                        "operational_certificate",
                        &format_args!("{:?}", self.operational_certificate),
                    )
                    .field("kes_evolutions", &format_args!("{:?}", self.kes_evolutions));

                #[cfg(feature = "future_snark")]
                {
                    debug
                        .field(
                            "verification_key_for_snark",
                            &format_args!("{:?}", self.verification_key_for_snark),
                        )
                        .field(
                            "verification_key_signature_for_snark",
                            &format_args!("{:?}", self.verification_key_signature_for_snark),
                        );
                }

                debug.finish()
            }
            false => debug.finish_non_exhaustive(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::test::{builder::MithrilFixtureBuilder, double::fake_keys};

    use super::*;

    #[test]
    fn test_stake_signers_from_into() {
        let verification_key = MithrilFixtureBuilder::default()
            .with_signers(1)
            .build()
            .signers_with_stake()[0]
            .verification_key_for_concatenation;
        let signer_expected = Signer {
            party_id: "1".to_string(),
            verification_key_for_concatenation: verification_key,
            verification_key_signature_for_concatenation: None,
            operational_certificate: None,
            kes_evolutions: None,
            #[cfg(feature = "future_snark")]
            verification_key_for_snark: None,
            #[cfg(feature = "future_snark")]
            verification_key_signature_for_snark: None,
        };
        let signer_with_stake = SignerWithStake {
            party_id: "1".to_string(),
            verification_key_for_concatenation: verification_key,
            verification_key_signature_for_concatenation: None,
            operational_certificate: None,
            kes_evolutions: None,
            stake: 100,
            #[cfg(feature = "future_snark")]
            verification_key_for_snark: None,
            #[cfg(feature = "future_snark")]
            verification_key_signature_for_snark: None,
        };

        let signer_into: Signer = signer_with_stake.into();
        assert_eq!(signer_expected, signer_into);
    }

    #[test]
    fn test_signer_compute_hash() {
        const HASH_EXPECTED: &str =
            "02778791113dcd8647b019366e223bfe3aa8a054fa6d9d1918b6b669de485f1c";

        let build_signer = |party_id: &str, key_index: usize| Signer {
            party_id: party_id.to_string(),
            verification_key_for_concatenation: fake_keys::signer_verification_key()[key_index]
                .try_into()
                .unwrap(),
            verification_key_signature_for_concatenation: None,
            operational_certificate: None,
            kes_evolutions: None,
            #[cfg(feature = "future_snark")]
            verification_key_for_snark: None,
            #[cfg(feature = "future_snark")]
            verification_key_signature_for_snark: None,
        };

        assert_eq!(HASH_EXPECTED, build_signer("1", 3).compute_hash());
        assert_ne!(HASH_EXPECTED, build_signer("0", 3).compute_hash());
        assert_ne!(HASH_EXPECTED, build_signer("1", 0).compute_hash());
    }

    #[test]
    fn test_signer_with_stake_compute_hash() {
        #[cfg(not(feature = "future_snark"))]
        const EXPECTED_HASH: &str =
            "9a832baccd04aabfc419f57319e3831a1655a95bf3bf5ed96a1167d1e81b5085";
        #[cfg(feature = "future_snark")]
        const EXPECTED_HASH: &str =
            "6158c4f514b1e15dc745845dac9014e710ee6b2f0c5b2b1023d5207cf6b75db9";
        let signers = MithrilFixtureBuilder::default()
            .with_signers(2)
            .build()
            .signers_with_stake();
        let signer = signers[0].clone();

        assert_eq!(EXPECTED_HASH, signer.compute_hash());

        {
            let mut signer_different_party_id = signer.clone();
            signer_different_party_id.party_id = "whatever".to_string();

            assert_ne!(EXPECTED_HASH, signer_different_party_id.compute_hash());
        }
        {
            let mut signer_different_verification_key = signer.clone();
            signer_different_verification_key.verification_key_for_concatenation =
                signers[1].verification_key_for_concatenation;

            assert_ne!(
                EXPECTED_HASH,
                signer_different_verification_key.compute_hash()
            );
        }
        {
            let mut signer_different_stake = signer.clone();
            signer_different_stake.stake += 20;

            assert_ne!(EXPECTED_HASH, signer_different_stake.compute_hash());
        }

        #[cfg(feature = "future_snark")]
        {
            let mut signer_different_verification_key_for_snark = signer.clone();
            signer_different_verification_key_for_snark.verification_key_for_snark =
                signers[1].verification_key_for_snark;

            assert_ne!(
                EXPECTED_HASH,
                signer_different_verification_key_for_snark.compute_hash()
            );
        }

        #[cfg(feature = "future_snark")]
        {
            let mut signer_different_verification_key_signature_for_snark = signer.clone();
            signer_different_verification_key_signature_for_snark
                .verification_key_signature_for_snark =
                signers[1].verification_key_signature_for_snark;

            assert_ne!(
                EXPECTED_HASH,
                signer_different_verification_key_signature_for_snark.compute_hash()
            );
        }
    }

    #[cfg(feature = "future_snark")]
    mod strip_snark_fields {
        use super::*;

        #[test]
        fn snark_fields_are_cleared_by_without_snark_fields() {
            let signers = MithrilFixtureBuilder::default()
                .with_signers(1)
                .build()
                .signers_with_stake();
            let signer = signers[0].clone();
            assert!(signer.verification_key_for_snark.is_some());
            assert!(signer.verification_key_signature_for_snark.is_some());

            let stripped = signer.without_snark_fields();

            assert!(stripped.verification_key_for_snark.is_none());
            assert!(stripped.verification_key_signature_for_snark.is_none());
        }

        #[test]
        fn without_snark_fields_preserves_non_snark_data() {
            let signers = MithrilFixtureBuilder::default()
                .with_signers(1)
                .build()
                .signers_with_stake();
            let signer = signers[0].clone();

            let stripped = signer.clone().without_snark_fields();

            assert_eq!(signer.party_id, stripped.party_id);
            assert_eq!(
                signer.verification_key_for_concatenation,
                stripped.verification_key_for_concatenation
            );
            assert_eq!(signer.stake, stripped.stake);
        }

        #[test]
        fn without_snark_fields_preserves_none_values() {
            let signers = MithrilFixtureBuilder::default()
                .with_signers(1)
                .build()
                .signers_with_stake();
            let mut signer = signers[0].clone();
            signer.verification_key_for_snark = None;
            signer.verification_key_signature_for_snark = None;

            let stripped = signer.without_snark_fields();

            assert!(stripped.verification_key_for_snark.is_none());
            assert!(stripped.verification_key_signature_for_snark.is_none());
        }

        #[test]
        fn strip_snark_fields_clears_all_entries() {
            let signers = MithrilFixtureBuilder::default()
                .with_signers(3)
                .build()
                .signers_with_stake();
            assert!(signers.iter().all(|s| s.verification_key_for_snark.is_some()));

            let stripped = SignerWithStake::strip_snark_fields(signers);

            assert!(stripped.iter().all(|s| s.verification_key_for_snark.is_none()));
            assert!(
                stripped
                    .iter()
                    .all(|s| s.verification_key_signature_for_snark.is_none())
            );
        }

        #[test]
        fn strip_snark_fields_handles_empty_list() {
            let stripped = SignerWithStake::strip_snark_fields(vec![]);
            assert!(stripped.is_empty());
        }
    }
}