mithril-common 0.7.14

Common types, interfaces, and utilities for Mithril nodes.
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
//! A module used to create a Genesis Certificate
//!
use chrono::prelude::*;
#[cfg(feature = "future_snark")]
use slog::warn;
use slog::{Logger, o};

#[cfg(feature = "future_snark")]
use crate::crypto_helper::{GenesisSchnorrSignature, ProtocolAggregateVerificationKeyForSnark};
use crate::{
    StdResult,
    crypto_helper::{
        GenesisEd25519Signature, PROTOCOL_VERSION, ProtocolAggregateVerificationKey, ProtocolKey,
    },
    entities::{
        Certificate, CertificateMetadata, CertificateSignature, Epoch, ProtocolMessage,
        ProtocolMessagePartKey, ProtocolParameters, SupportedEra,
    },
};

/// CertificateGenesisProducer is in charge of producing a Genesis Certificate
#[derive(Debug)]
pub struct CertificateGenesisProducer {
    logger: Logger,
}

impl Default for CertificateGenesisProducer {
    fn default() -> Self {
        Self::new()
    }
}

impl CertificateGenesisProducer {
    /// CertificateGenesisProducer factory
    pub fn new() -> Self {
        Self {
            logger: Logger::root(slog::Discard, o!()),
        }
    }

    /// Set the [Logger] to use.
    pub fn with_logger(mut self, logger: Logger) -> Self {
        self.logger = logger;
        self
    }

    /// Create the Genesis protocol message
    pub fn create_genesis_protocol_message(
        &self,
        genesis_protocol_parameters: &ProtocolParameters,
        genesis_avk: &ProtocolAggregateVerificationKey,
        genesis_epoch: &Epoch,
        mithril_era: SupportedEra,
    ) -> StdResult<ProtocolMessage> {
        let genesis_aggregate_verification_key_for_concatenation =
            ProtocolKey::new(genesis_avk.to_concatenation_aggregate_verification_key().to_owned());
        let genesis_concatenation_avk =
            genesis_aggregate_verification_key_for_concatenation.to_json_hex()?;
        let mut protocol_message = match mithril_era {
            SupportedEra::Pythagoras => ProtocolMessage::new(),
            #[cfg(feature = "future_snark")]
            SupportedEra::Lagrange => ProtocolMessage::new_rigid(),
            #[cfg(not(feature = "future_snark"))]
            SupportedEra::Lagrange => ProtocolMessage::new(),
        };
        protocol_message.set_message_part(
            ProtocolMessagePartKey::NextAggregateVerificationKey,
            genesis_concatenation_avk,
        );

        if mithril_era != SupportedEra::Pythagoras {
            #[cfg(feature = "future_snark")]
            match genesis_avk.to_snark_aggregate_verification_key() {
                Some(snark_avk) => {
                    let genesis_snark_avk: ProtocolAggregateVerificationKeyForSnark =
                        ProtocolKey::new(snark_avk.to_owned());
                    protocol_message.set_message_part(
                        ProtocolMessagePartKey::NextSnarkAggregateVerificationKey,
                        genesis_snark_avk.to_bytes_hex()?,
                    );
                }
                None => {
                    warn!(
                        self.logger,
                        "SNARK aggregate verification key is unavailable, genesis certificate will not include SNARK AVK"
                    );
                }
            }
        }

        protocol_message.set_message_part(
            ProtocolMessagePartKey::NextProtocolParameters,
            genesis_protocol_parameters.compute_hash(),
        );
        protocol_message.set_message_part(
            ProtocolMessagePartKey::CurrentEpoch,
            genesis_epoch.to_string(),
        );

        #[cfg(feature = "future_snark")]
        protocol_message.check_rigid_integrity()?;

        Ok(protocol_message)
    }

    /// Assemble a legacy (Pythagoras) Genesis Certificate from an Ed25519 genesis signature.
    ///
    /// Signing is performed upstream by [`GenesisSigner`][crate::crypto_helper::GenesisSigner];
    /// this only builds the certificate body.
    pub fn create_legacy_genesis_certificate<T: Into<String>>(
        &self,
        protocol_parameters: ProtocolParameters,
        network: T,
        epoch: Epoch,
        genesis_avk: ProtocolAggregateVerificationKey,
        genesis_signature: GenesisEd25519Signature,
        mithril_era: SupportedEra,
    ) -> StdResult<Certificate> {
        self.create_genesis_certificate_internal(
            protocol_parameters,
            network,
            epoch,
            genesis_avk,
            CertificateSignature::GenesisSignature(genesis_signature),
            mithril_era,
        )
    }

    /// Assemble a dual (Lagrange) Genesis Certificate from the Ed25519 and Schnorr genesis
    /// signatures.
    ///
    /// Signing is performed upstream by [`GenesisSigner`][crate::crypto_helper::GenesisSigner];
    /// this only builds the certificate body.
    #[cfg(feature = "future_snark")]
    #[allow(clippy::too_many_arguments)]
    pub fn create_genesis_certificate<T: Into<String>>(
        &self,
        protocol_parameters: ProtocolParameters,
        network: T,
        epoch: Epoch,
        genesis_avk: ProtocolAggregateVerificationKey,
        genesis_signature: GenesisEd25519Signature,
        genesis_signature_snark: GenesisSchnorrSignature,
        mithril_era: SupportedEra,
    ) -> StdResult<Certificate> {
        self.create_genesis_certificate_internal(
            protocol_parameters,
            network,
            epoch,
            genesis_avk,
            CertificateSignature::GenesisDualSignature(genesis_signature, genesis_signature_snark),
            mithril_era,
        )
    }

    /// Assemble a Genesis Certificate body around an already-produced genesis signature.
    ///
    /// Private so the public entry points ([Self::create_legacy_genesis_certificate],
    /// [Self::create_genesis_certificate]) own the signature shape, making a multi-signature
    /// genesis certificate unrepresentable.
    fn create_genesis_certificate_internal<T: Into<String>>(
        &self,
        protocol_parameters: ProtocolParameters,
        network: T,
        epoch: Epoch,
        genesis_avk: ProtocolAggregateVerificationKey,
        signature: CertificateSignature,
        mithril_era: SupportedEra,
    ) -> StdResult<Certificate> {
        let metadata = CertificateMetadata::new(
            network,
            PROTOCOL_VERSION.to_string(),
            protocol_parameters.clone(),
            Utc::now(),
            Utc::now(),
            vec![],
        );
        let genesis_protocol_message = self.create_genesis_protocol_message(
            &protocol_parameters,
            &genesis_avk,
            &epoch,
            mithril_era,
        )?;
        Certificate::try_new(
            "".to_string(),
            epoch,
            metadata,
            genesis_protocol_message,
            genesis_avk,
            signature,
            None,
            None,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::entities::ProtocolMessagePartKey;
    use crate::test::TestLogger;
    use crate::test::builder::MithrilFixtureBuilder;
    #[cfg(feature = "future_snark")]
    use crate::test::double::fake_keys;

    #[test]
    fn genesis_protocol_message_has_expected_keys_and_values() {
        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let genesis_protocol_parameters = fixture.protocol_parameters();
        let genesis_avk = fixture.compute_aggregate_verification_key();
        let genesis_epoch = Epoch(123);
        let genesis_producer = CertificateGenesisProducer::new().with_logger(TestLogger::stdout());
        let protocol_message = genesis_producer
            .create_genesis_protocol_message(
                &genesis_protocol_parameters,
                &genesis_avk,
                &genesis_epoch,
                SupportedEra::Pythagoras,
            )
            .unwrap();

        let expected_genesis_avk_value =
            fixture.compute_and_encode_concatenation_aggregate_verification_key();
        assert_eq!(
            protocol_message
                .get_message_part(&ProtocolMessagePartKey::NextAggregateVerificationKey),
            Some(&expected_genesis_avk_value)
        );

        let expected_genesis_protocol_parameters_value = genesis_protocol_parameters.compute_hash();
        assert_eq!(
            protocol_message.get_message_part(&ProtocolMessagePartKey::NextProtocolParameters),
            Some(&expected_genesis_protocol_parameters_value)
        );

        let expected_genesis_epoch = genesis_epoch.to_string();
        assert_eq!(
            protocol_message.get_message_part(&ProtocolMessagePartKey::CurrentEpoch),
            Some(&expected_genesis_epoch)
        );
    }

    #[cfg(feature = "future_snark")]
    #[test]
    fn genesis_protocol_message_includes_snark_aggregate_verification_key() {
        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let genesis_protocol_parameters = fixture.protocol_parameters();
        let genesis_avk = fixture.compute_aggregate_verification_key();
        let genesis_epoch = Epoch(123);
        let genesis_producer = CertificateGenesisProducer::new().with_logger(TestLogger::stdout());
        let protocol_message = genesis_producer
            .create_genesis_protocol_message(
                &genesis_protocol_parameters,
                &genesis_avk,
                &genesis_epoch,
                SupportedEra::Lagrange,
            )
            .unwrap();

        let expected_snark_avk_value = fixture
            .compute_and_encode_snark_aggregate_verification_key()
            .expect("SNARK AVK should be available");
        assert_eq!(
            protocol_message
                .get_message_part(&ProtocolMessagePartKey::NextSnarkAggregateVerificationKey),
            Some(&expected_snark_avk_value)
        );
    }

    #[cfg(feature = "future_snark")]
    mod era_dispatched_genesis_certificate {
        use crate::crypto_helper::{
            GenesisBundleError, GenesisEd25519Signer, GenesisSchnorrVerifier, GenesisSigner,
            PREIMAGE_SIZE, ProtocolAggregateVerificationKeyForConcatenation, sha256_digest,
        };
        use crate::entities::RigidProtocolMessageIntegrityError;

        use super::*;

        #[test]
        fn pythagoras_creates_a_single_signature_variant() {
            let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
            let genesis_signer = GenesisSigner::create_deterministic_signer();
            let producer = CertificateGenesisProducer::new().with_logger(TestLogger::stdout());
            let protocol_message = producer
                .create_genesis_protocol_message(
                    &fixture.protocol_parameters(),
                    &fixture.compute_aggregate_verification_key(),
                    &Epoch(1),
                    SupportedEra::Pythagoras,
                )
                .unwrap();
            let signature = genesis_signer
                .sign_deterministic(&protocol_message, SupportedEra::Pythagoras)
                .unwrap();

            let certificate = producer
                .create_genesis_certificate_internal(
                    fixture.protocol_parameters(),
                    "testnet",
                    Epoch(1),
                    fixture.compute_aggregate_verification_key(),
                    signature,
                    SupportedEra::Pythagoras,
                )
                .unwrap();

            assert!(matches!(
                certificate.signature,
                CertificateSignature::GenesisSignature(_)
            ));
        }

        #[test]
        fn lagrange_genesis_rejects_an_aggregate_verification_key_without_its_snark_half() {
            let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
            let producer = CertificateGenesisProducer::new().with_logger(TestLogger::stdout());
            let aggregate_verification_key_without_snark = ProtocolAggregateVerificationKey::new(
                ProtocolAggregateVerificationKeyForConcatenation::try_from(
                    fake_keys::aggregate_verification_key_for_concatenation()[0],
                )
                .unwrap()
                .into(),
                None,
            );

            let error = producer
                .create_genesis_protocol_message(
                    &fixture.protocol_parameters(),
                    &aggregate_verification_key_without_snark,
                    &Epoch(1),
                    SupportedEra::Lagrange,
                )
                .expect_err(
                    "Lagrange genesis must reject an aggregate verification key without its SNARK half",
                );

            assert!(matches!(
                error.downcast_ref::<RigidProtocolMessageIntegrityError>(),
                Some(RigidProtocolMessageIntegrityError::MissingNextSnarkAggregateVerificationKey)
            ));
        }

        #[test]
        fn lagrange_creates_a_dual_signature_variant() {
            let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
            let genesis_signer = GenesisSigner::create_deterministic_signer();
            let producer = CertificateGenesisProducer::new().with_logger(TestLogger::stdout());
            let protocol_message = producer
                .create_genesis_protocol_message(
                    &fixture.protocol_parameters(),
                    &fixture.compute_aggregate_verification_key(),
                    &Epoch(1),
                    SupportedEra::Lagrange,
                )
                .unwrap();
            let signature = genesis_signer
                .sign_deterministic(&protocol_message, SupportedEra::Lagrange)
                .unwrap();

            let certificate = producer
                .create_genesis_certificate_internal(
                    fixture.protocol_parameters(),
                    "testnet",
                    Epoch(1),
                    fixture.compute_aggregate_verification_key(),
                    signature,
                    SupportedEra::Lagrange,
                )
                .unwrap();

            let (genesis_ed25519_signature, genesis_schnorr_signature) = match certificate.signature
            {
                CertificateSignature::GenesisDualSignature(ed25519, schnorr) => (ed25519, schnorr),
                other => panic!("expected GenesisDualSignature, got {other:?}"),
            };

            let verifier = GenesisSchnorrVerifier::from_verification_key(
                genesis_signer.schnorr.as_ref().unwrap().verification_key(),
            );
            let preimage = certificate.protocol_message.rigid_preimage();
            assert_eq!(preimage.len(), PREIMAGE_SIZE);
            let digest = sha256_digest(&preimage);
            verifier.verify(&digest, &genesis_schnorr_signature).expect(
                "Schnorr signature produced by the dual-genesis path must verify against the same digest",
            );
            genesis_signer
                .ed25519
                .create_verifier()
                .verify(
                    certificate.signed_message.as_bytes(),
                    &genesis_ed25519_signature,
                )
                .expect("Ed25519 signature must verify against the legacy signed_message bytes");
        }

        #[test]
        fn preimage_size_constant_matches_rigid_protocol_message_preimage_length() {
            let mut rigid = ProtocolMessage::new_rigid();
            rigid.set_message_part(ProtocolMessagePartKey::CurrentEpoch, "1".to_string());

            assert_eq!(
                rigid.rigid_preimage().len(),
                PREIMAGE_SIZE,
                "Rigid protocol-message preimage length must match the PREIMAGE_SIZE constant \
                 pinned by the IVC gadget; any drift here is the regression the signer's \
                 preimage-size guard exists to catch"
            );
        }

        #[test]
        fn lagrange_fails_without_a_schnorr_signer() {
            let fixture = MithrilFixtureBuilder::default().with_signers(3).build();
            let genesis_signer =
                GenesisSigner::from_ed25519(GenesisEd25519Signer::create_deterministic_signer());
            let producer = CertificateGenesisProducer::new().with_logger(TestLogger::stdout());
            let protocol_message = producer
                .create_genesis_protocol_message(
                    &fixture.protocol_parameters(),
                    &fixture.compute_aggregate_verification_key(),
                    &Epoch(1),
                    SupportedEra::Lagrange,
                )
                .unwrap();

            let error = genesis_signer
                .sign_deterministic(&protocol_message, SupportedEra::Lagrange)
                .unwrap_err();

            assert!(matches!(
                error.downcast_ref::<GenesisBundleError>(),
                Some(GenesisBundleError::LegacySigningKey)
            ));
        }
    }
}