rialo-types 0.5.0-alpha.0

Rialo Types
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Admin transaction types for privileged network operations.
//!
//! This module contains types for administrative transactions that can
//! only be submitted by authorized parties (e.g., epoch changes).
//!
//! # Generic attestation framework
//!
//! The following are re-exported from the private `attestation_framework` submodule for use
//! alongside handover, snapshot, and other admin types:
//!
//! - [`AttestableRecord`]: sealed trait for record types validators attest; each type fixes an
//!   intent prefix and a [`RecordDigest`] for signing.
//! - [`Attestation`]: one validator’s Ed25519 signature over the intent-prefixed digest
//!   (wire format does not embed the full record).
//! - [`CommitteeAttestedRecord`]: sealed extension of [`AttestableRecord`] for records that carry an
//!   epoch and block height so [`HandoverChain`] can validate committee and window (operational
//!   (operational records use their single epoch; handover records use the source epoch).
//! - [`Certificate`]: quorum aggregation over `Attestation<R>` with committee validation via the
//!   handover chain; concrete record types wire this generic in their own modules.
//! - [`CertificateAddAttestationError`]: errors from [`Certificate::add_attestation`].
//! - [`AttestationError`]: errors from [`Attestation::sign`] and
//!   [`Attestation::verify_internal_consistency`].
//! - [`Certificate`]: quorum-certified wrapper around a [`CommitteeAttestedRecord`]; validates
//!   attestations against the committee from [`HandoverChain`].
//! - [`CommitteeAttestedRecord`]: sealed extension for records that belong to a committee-governed
//!   epoch (provides `attesting_epoch()` and `attested_block_height()`).
//! - [`attestation_threshold`], [`ATTESTATION_THRESHOLD_NUMERATOR`],
//!   [`ATTESTATION_THRESHOLD_DENOMINATOR`]: rational **1/3** stake floor for attestation
//!   overlap; callers require strictly greater support than the threshold (see
//!   [`ATTESTATION_THRESHOLD_NUMERATOR`] for why this differs from consensus **2f+1** quorum).

use serde::{Deserialize, Serialize};

/// Size of a Blake3 hash in bytes.
pub const BLAKE3_HASH_SIZE: usize = 32;

/// Blake3 hash type alias (32 bytes).
pub type Blake3Hash = [u8; BLAKE3_HASH_SIZE];

/// BLS12-381 public key size in bytes.
pub const BLS12381_PUBLIC_KEY_SIZE: usize = 96;

/// Ed25519 public key size in bytes.
pub const ED25519_PUBLIC_KEY_SIZE: usize = 32;
/// Ed25519 signature size in bytes.
pub const ED25519_SIGNATURE_SIZE: usize = 64;

/// Intent prefix for ValidatorReadyMessage signatures.
/// `[scope=ValidatorReady=14, version=V0=0, app_id=Consensus=2]`
///
/// These values mirror `shared_crypto::intent::{IntentScope, IntentVersion, AppId}`
/// but are inlined to avoid pulling `shared-crypto` (and its `fastcrypto` transitive
/// dependency) into RISC-V / PDK builds where it cannot compile. A `#[cfg(test)]`
/// assertion in the test module verifies these stay in sync.
///
/// This domain separator prevents cross-domain signature replay — a signature
/// over a message in a different domain cannot be mistaken for a valid ready message.
const READY_MESSAGE_INTENT_PREFIX: [u8; 3] = [14, 0, 2];

/// Length of the intent prefix (must equal `shared_crypto::intent::INTENT_PREFIX_LENGTH`).
const INTENT_PREFIX_LEN: usize = 3;

/// Size of the signing message for ValidatorReadyMessage.
/// Format: intent_prefix (3 bytes) || current_epoch (8 bytes) || epoch_config_hash (32 bytes) = 43 bytes
///
/// STOP-THE-WORLD: Changing this constant (or the intent prefix bytes) is a
/// signature-breaking change. All validators must upgrade simultaneously.
pub const READY_MESSAGE_SIGNING_SIZE: usize = INTENT_PREFIX_LEN + 8 + BLAKE3_HASH_SIZE;

#[macro_use]
mod attestation_framework;
pub mod epoch;
mod epoch_complete;
mod handover;
pub(crate) mod headers;
mod ordered_block;
mod snapshot;
/// Test-only helpers (key generation, snapshot/handover fixtures). Compiled for
/// this crate's unit tests and for dependents that enable the `testing` feature
/// (e.g. consensus parity tests).
#[cfg(any(test, feature = "testing"))]
pub mod test_helpers;
mod write_set;

// Documented under [`crate::admin`] → “Generic attestation framework”.
pub use attestation_framework::{
    attestation_threshold, validate_attestation_consistency, AttestableRecord, Attestation,
    AttestationError, Certificate, CertificateAddAttestationError,
    CertificateAttestationConsistencyError, CommitteeAttestedRecord, RecordDigest,
    ATTESTATION_THRESHOLD_DENOMINATOR, ATTESTATION_THRESHOLD_NUMERATOR,
};
pub use epoch::*;
pub use epoch_complete::{EpochCompleteMessage, EPOCH_COMPLETE_SIGNING_SIZE};
pub use handover::{
    HandoverAttestation, HandoverAttestationRoutingError, HandoverCertificate,
    HandoverCertificateAddAttestationError, HandoverChain, HandoverChainError, HandoverRecord,
};
pub use ordered_block::{
    OrderedBlockAttestation, OrderedBlockCertificate, OrderedBlockCertificateAddAttestationError,
    OrderedBlockRecord,
};
pub use snapshot::{
    SnapshotAttestation, SnapshotAttestationSubmission, SnapshotAttestationSubmissionError,
    SnapshotCertificate, SnapshotCertificateAddAttestationError, SnapshotRecord,
};
pub use write_set::{
    WriteSetAttestation, WriteSetCertificate, WriteSetCertificateAddAttestationError,
    WriteSetRecord,
};

/// Wrapper for admin transactions that go through consensus.
///
/// Admin transactions are privileged operations that are processed
/// separately from regular user transactions and REX updates.
///
/// BlockPool-generated artifacts ([`SynthesizedAdmin::Handover`], [`SynthesizedAdmin::SnapshotCertificate`])
/// are not part of this wire type; they appear on executable blocks as [`ExecutableAdmin::Synthesized`].
///
/// # BCS compatibility
///
/// Variants are ordinal-encoded by BCS. **Never reorder or insert variants
/// in the middle** — only append new variants at the end. Each variant's
/// ordinal is part of the wire format.
///
/// Removing variants from this enum changes BCS ordinals for all later variants; treat
/// `AdminTransaction` wire bytes as versioned with the codebase that produced them.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum AdminTransaction {
    /// Initiates an epoch change with the specified configuration.
    EpochChange(Box<EpochChangeConfig>),

    /// A ready message from a validator signaling readiness for an epoch change.
    ///
    /// This is sent by validators in the current or new epoch after they see
    /// an `EpochChange` transaction. Validators must collect a quorum of these
    /// ready messages before the epoch transition can complete.
    Ready(Box<ValidatorReadyMessage>),

    /// A snapshot attestation submission from a validator.
    ///
    /// Bundles a `SnapshotRecord` with the validator's signed attestation.
    /// When f+1 validators submit attestations for the same record, the
    /// snapshot becomes certified and can be used for recovery.
    SnapshotAttestationSubmission(Box<SnapshotAttestationSubmission>),

    /// A unified epoch-complete attestation from a validator.
    ///
    /// Submitted after observing both a handover and a snapshot for the same
    /// epoch transition. Aggregated by BlockPool toward attestation threshold.
    EpochComplete(Box<EpochCompleteMessage>),
}

/// Admin payloads produced by BlockPool (not consensus [`AdminTransaction`] wire variants).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum SynthesizedAdmin {
    /// Handover record for an epoch transition.
    Handover(Box<HandoverRecord>),

    /// Quorum-certified snapshot.
    SnapshotCertificate(Box<SnapshotCertificate>),
}

/// Admin payload on an executable block: consensus [`AdminTransaction`] or [`SynthesizedAdmin`].
///
/// Epoch changes on committed blocks use **only** [`AdminTransaction::EpochChange`] inside [`ExecutableAdmin::Transaction`].
/// Execution forwards every row to the node after a block runs.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum ExecutableAdmin {
    /// Carried from consensus / mempool as `ConsensusMessage::AdminTransaction`.
    Transaction(AdminTransaction),
    /// Produced by BlockPool ([`SynthesizedAdmin`]).
    Synthesized(SynthesizedAdmin),
}

#[cfg(test)]
mod tests {
    use rialo_s_pubkey::Pubkey;

    use super::{
        test_helpers::{test_keys::*, test_records::*},
        *,
    };

    /// Deterministic seeds for `create_test_keys` (`StdRng::seed_from_u64`); each test uses
    /// `KEYGEN_SEED_BASE + n` with a unique `n` so keys do not collide across tests.
    const KEYGEN_SEED_BASE: u64 = 42;

    #[test]
    fn test_epoch_change_config_serialization() {
        let (authority_key, protocol_key, network_key) = create_test_keys(KEYGEN_SEED_BASE);
        let config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![ValidatorInfo {
                stake: 1000,
                consensus_address: "/ip4/127.0.0.1/udp/10100".parse().unwrap(),
                state_sync_address: "/ip4/127.0.0.1/udp/20100".parse().unwrap(),
                hostname: "validator-0".to_string(),
                authority_key,
                protocol_key,
                network_key,
                signing_key: Pubkey::new_unique(),
            }],
            consensus_config: None,
        };

        let serialized = serde_json::to_string(&config).expect("serialization should succeed");
        let deserialized: EpochChangeConfig =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        assert_eq!(deserialized.current_epoch, config.current_epoch);
        assert_eq!(deserialized.new_epoch, config.new_epoch);
        assert_eq!(deserialized.validators.len(), 1);
        assert_eq!(deserialized.validators[0].stake, 1000);
    }

    fn create_test_epoch_complete_message(
        seed: u64,
    ) -> (EpochCompleteMessage, crate::ProtocolKeyPair) {
        let (authority_key, protocol_keypair, _) = create_test_keys_with_keypair(seed);
        let handover_record = create_test_handover_record(100, 0, 1, [0u8; 32]);
        let snapshot_record = create_test_snapshot_record(100, 1);
        let msg = EpochCompleteMessage::sign(
            &handover_record,
            &snapshot_record,
            &protocol_keypair,
            &authority_key,
        )
        .expect("EpochCompleteMessage::sign() should succeed");
        (msg, protocol_keypair)
    }

    #[test]
    fn test_admin_transaction_serialization() {
        let config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(4),
            new_epoch: EpochIdentifier::new(5),
            validators: vec![],
            consensus_config: Some(EpochConsensusConfig {
                num_leaders_per_round: Some(2),
                ..Default::default()
            }),
        };

        let admin_tx = AdminTransaction::EpochChange(Box::new(config));
        let serialized = serde_json::to_string(&admin_tx).expect("serialization should succeed");
        let deserialized: AdminTransaction =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        match deserialized {
            AdminTransaction::EpochChange(cfg) => {
                assert_eq!(cfg.new_epoch, EpochIdentifier::new(5));
                assert!(cfg.consensus_config.is_some());
            }
            _ => panic!("Expected EpochChange"),
        }
    }

    #[test]
    fn test_validator_ready_message_serialization() {
        let (authority_key, protocol_key, _) = create_test_keys(KEYGEN_SEED_BASE + 1);
        let epoch_config_hash = [0xABu8; BLAKE3_HASH_SIZE];
        let ready_msg = ValidatorReadyMessage {
            current_epoch: EpochIdentifier::new(0),
            epoch_config_hash,
            authority_key: authority_key.clone(),
            protocol_key: protocol_key.clone(),
            signature: [2u8; ED25519_SIGNATURE_SIZE],
        };

        let serialized = serde_json::to_string(&ready_msg).expect("serialization should succeed");
        let deserialized: ValidatorReadyMessage =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        assert_eq!(deserialized.current_epoch, EpochIdentifier::new(0));
        assert_eq!(deserialized.epoch_config_hash, epoch_config_hash);
        assert_eq!(deserialized.authority_key, authority_key);
        assert_eq!(deserialized.protocol_key, protocol_key);
        assert_eq!(deserialized.signature, ready_msg.signature);
    }

    /// Verifies `message_bytes()` on a struct delegates to `signing_message()`.
    #[test]
    fn test_validator_ready_message_bytes_delegates_to_signing_message() {
        let (authority_key, protocol_key, _) = create_test_keys(KEYGEN_SEED_BASE + 2);
        let epoch_config_hash = [0xABu8; BLAKE3_HASH_SIZE];
        let ready_msg = ValidatorReadyMessage {
            current_epoch: EpochIdentifier::new(5),
            epoch_config_hash,
            authority_key,
            protocol_key,
            signature: [2u8; ED25519_SIGNATURE_SIZE],
        };

        assert_eq!(
            ready_msg.message_bytes(),
            ValidatorReadyMessage::signing_message(EpochIdentifier::new(5), &epoch_config_hash)
        );
    }

    /// Verifies the exact wire format of the signing message with the intent prefix.
    /// The signing message is: intent_prefix (3 bytes) || current_epoch (8 bytes LE) || epoch_config_hash (32 bytes) = 43 bytes.
    #[test]
    fn test_ready_message_signing_message_wire_format() {
        let epoch = EpochIdentifier::new(42);
        let epoch_config_hash = [0xBBu8; BLAKE3_HASH_SIZE];

        let msg = ValidatorReadyMessage::signing_message(epoch, &epoch_config_hash);

        // Total size: 3 (intent) + 8 (epoch) + 32 (hash) = 43
        assert_eq!(msg.len(), 43);

        // First 3 bytes: intent prefix [scope=ValidatorReady=14, version=V0=0, app_id=Consensus=2]
        assert_eq!(msg[0..3], [14, 0, 2]);

        // Bytes 3..11: current_epoch as little-endian u64
        assert_eq!(msg[3..11], 42u64.to_le_bytes());

        // Bytes 11..43: epoch_config_hash
        assert_eq!(msg[11..43], epoch_config_hash);

        // Different inputs produce different messages
        let msg2 =
            ValidatorReadyMessage::signing_message(EpochIdentifier::new(0), &epoch_config_hash);
        assert_ne!(msg, msg2);
        // But the intent prefix is always the same
        assert_eq!(msg2[0..3], [14, 0, 2]);
    }

    /// Guards against the inlined intent constants drifting from `shared-crypto`.
    #[test]
    fn test_ready_message_intent_prefix_matches_shared_crypto() {
        use shared_crypto::intent::{AppId, IntentScope, IntentVersion, INTENT_PREFIX_LENGTH};

        assert_eq!(
            super::READY_MESSAGE_INTENT_PREFIX,
            [
                IntentScope::ValidatorReady as u8,
                IntentVersion::V0 as u8,
                AppId::Consensus as u8,
            ],
            "READY_MESSAGE_INTENT_PREFIX is out of sync with shared-crypto enums"
        );
        assert_eq!(
            super::INTENT_PREFIX_LEN,
            INTENT_PREFIX_LENGTH,
            "INTENT_PREFIX_LEN is out of sync with shared_crypto::intent::INTENT_PREFIX_LENGTH"
        );
    }

    #[test]
    fn test_admin_transaction_ready_serialization() {
        let (authority_key, protocol_key, _) = create_test_keys(KEYGEN_SEED_BASE + 3);
        let epoch_config_hash = [0xABu8; BLAKE3_HASH_SIZE];
        let ready_msg = ValidatorReadyMessage {
            current_epoch: EpochIdentifier::new(0),
            epoch_config_hash,
            authority_key,
            protocol_key,
            signature: [2u8; ED25519_SIGNATURE_SIZE],
        };

        let admin_tx = AdminTransaction::Ready(Box::new(ready_msg));
        let serialized = serde_json::to_string(&admin_tx).expect("serialization should succeed");
        let deserialized: AdminTransaction =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        match deserialized {
            AdminTransaction::Ready(msg) => {
                assert_eq!(msg.current_epoch, EpochIdentifier::new(0));
                assert_eq!(msg.epoch_config_hash, epoch_config_hash);
            }
            _ => panic!("Expected Ready"),
        }
    }

    #[test]
    fn test_synthesized_admin_handover_serialization() {
        let epoch_config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![],
            consensus_config: None,
        };

        let record = HandoverRecord::new(
            100,
            EpochIdentifier::new(0),
            EpochIdentifier::new(1),
            epoch_config,
            [0u8; BLAKE3_HASH_SIZE],
        );

        let inner = SynthesizedAdmin::Handover(Box::new(record));
        let serialized = serde_json::to_string(&inner).expect("serialization should succeed");
        let deserialized: SynthesizedAdmin =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        match deserialized {
            SynthesizedAdmin::Handover(r) => {
                assert_eq!(r.block_index(), 100);
                assert_eq!(r.source_epoch(), EpochIdentifier::new(0));
                assert_eq!(r.dest_epoch(), EpochIdentifier::new(1));
            }
            _ => panic!("Expected Handover"),
        }
    }

    #[test]
    fn test_epoch_change_config_deterministic_hash() {
        let (authority_key, protocol_key, network_key) = create_test_keys(KEYGEN_SEED_BASE + 4);
        let config1 = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![ValidatorInfo {
                stake: 1000,
                consensus_address: "/ip4/127.0.0.1/udp/10100".parse().unwrap(),
                state_sync_address: "/ip4/127.0.0.1/udp/20100".parse().unwrap(),
                hostname: "validator-0".to_string(),
                authority_key: authority_key.clone(),
                protocol_key: protocol_key.clone(),
                network_key: network_key.clone(),
                signing_key: Pubkey::new_from_array([3u8; 32]),
            }],
            consensus_config: None,
        };

        // Same config should produce same hash
        let config2 = config1.clone();
        assert_eq!(config1.deterministic_hash(), config2.deterministic_hash());

        // Different new_epoch should produce different hash
        let config3 = EpochChangeConfig {
            new_epoch: EpochIdentifier::new(2),
            ..config1.clone()
        };
        assert_ne!(config1.deterministic_hash(), config3.deterministic_hash());

        // Different validators should produce different hash
        let config4 = EpochChangeConfig {
            validators: vec![ValidatorInfo {
                stake: 2000, // Different stake
                consensus_address: "/ip4/127.0.0.1/udp/10100".parse().unwrap(),
                state_sync_address: "/ip4/127.0.0.1/udp/20100".parse().unwrap(),
                hostname: "validator-0".to_string(),
                authority_key,
                protocol_key,
                network_key,
                signing_key: Pubkey::new_from_array([3u8; 32]),
            }],
            ..config1.clone()
        };
        assert_ne!(config1.deterministic_hash(), config4.deterministic_hash());

        // Adding consensus config should produce different hash
        let config5 = EpochChangeConfig {
            consensus_config: Some(EpochConsensusConfig {
                num_leaders_per_round: Some(2),
                ..Default::default()
            }),
            ..config1.clone()
        };
        assert_ne!(config1.deterministic_hash(), config5.deterministic_hash());
    }

    /// Regression test: `deterministic_hash()` must use canonical wire-format bytes
    /// (`Multiaddr::to_vec()`) for address fields, not the display string (`to_string()`).
    /// This test manually recomputes the expected hash using wire-format bytes and pins it,
    /// so any accidental revert to string-based hashing will be caught.
    #[test]
    fn test_deterministic_hash_uses_canonical_multiaddr_wire_format() {
        let (authority_key, protocol_key, network_key) = create_test_keys(KEYGEN_SEED_BASE + 5);
        let config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![ValidatorInfo {
                stake: 1000,
                consensus_address: "/ip4/127.0.0.1/udp/10100".parse().unwrap(),
                state_sync_address: "/ip4/127.0.0.1/udp/20100".parse().unwrap(),
                hostname: "validator-0".to_string(),
                authority_key: authority_key.clone(),
                protocol_key: protocol_key.clone(),
                network_key: network_key.clone(),
                signing_key: Pubkey::new_from_array([3u8; 32]),
            }],
            consensus_config: None,
        };

        // Manually compute the expected hash using canonical wire-format bytes for addresses.
        let mut hasher = blake3::Hasher::new();
        hasher.update(&0u64.to_le_bytes()); // current_epoch
        hasher.update(&1u64.to_le_bytes()); // new_epoch
        hasher.update(&1u64.to_le_bytes()); // validators.len()

        hasher.update(&1000u64.to_le_bytes()); // stake

        // Addresses: canonical wire-format bytes via to_vec()
        let consensus_addr: crate::multiaddr::Multiaddr =
            "/ip4/127.0.0.1/udp/10100".parse().unwrap();
        let consensus_wire = consensus_addr.to_vec();
        hasher.update(&(consensus_wire.len() as u64).to_le_bytes());
        hasher.update(&consensus_wire);

        let state_sync_addr: crate::multiaddr::Multiaddr =
            "/ip4/127.0.0.1/udp/20100".parse().unwrap();
        let state_sync_wire = state_sync_addr.to_vec();
        hasher.update(&(state_sync_wire.len() as u64).to_le_bytes());
        hasher.update(&state_sync_wire);

        // hostname
        let hostname = "validator-0";
        hasher.update(&(hostname.len() as u64).to_le_bytes());
        hasher.update(hostname.as_bytes());

        // keys
        hasher.update(&authority_key.to_bytes());
        hasher.update(&protocol_key.to_bytes());
        hasher.update(&network_key.to_bytes());
        hasher.update(Pubkey::new_from_array([3u8; 32]).as_ref());

        // consensus_config absent
        hasher.update(&[0u8]);

        let expected_hash = *hasher.finalize().as_bytes();
        assert_eq!(
            config.deterministic_hash(),
            expected_hash,
            "deterministic_hash() must use Multiaddr::to_vec() canonical wire-format bytes, \
             not to_string() display representation"
        );

        // Hash must be stable across invocations
        assert_eq!(config.deterministic_hash(), config.deterministic_hash());
    }

    /// Demonstrates that Multiaddr wire-format bytes differ from the display string bytes.
    /// This is the root cause that the canonical encoding fix addresses.
    #[test]
    fn test_multiaddr_to_string_differs_from_to_vec() {
        let addr: crate::multiaddr::Multiaddr = "/ip4/127.0.0.1/udp/10100".parse().unwrap();

        let string_bytes = addr.to_string().into_bytes();
        let wire_bytes = addr.to_vec();

        assert_ne!(
            string_bytes, wire_bytes,
            "to_string() bytes and to_vec() wire-format bytes must differ — \
             using the wrong one for hashing would silently break consensus"
        );
    }

    #[test]
    fn test_admin_transaction_snapshot_attestation_submission_serialization() {
        let record = create_test_snapshot_record(999, 1);
        let (authority_key, protocol_keypair, _) = create_test_keys_with_keypair(62);

        let attestation =
            Attestation::<SnapshotRecord>::sign(&record, &protocol_keypair, &authority_key)
                .expect("sign() should succeed");

        let submission = SnapshotAttestationSubmission::new(record.clone(), attestation);

        let admin_tx =
            AdminTransaction::SnapshotAttestationSubmission(Box::new(submission.clone()));
        let serialized = serde_json::to_string(&admin_tx).expect("serialization should succeed");
        let deserialized: AdminTransaction =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        match deserialized {
            AdminTransaction::SnapshotAttestationSubmission(sub) => {
                assert_eq!(sub.snapshot_record(), &record);
                assert!(sub.validate_digest_consistency().is_ok());
            }
            _ => panic!("Expected SnapshotAttestationSubmission"),
        }
    }

    #[test]
    fn test_admin_transaction_epoch_complete_serialization_roundtrip() {
        let (msg, _) = create_test_epoch_complete_message(5010);

        let admin_tx = AdminTransaction::EpochComplete(Box::new(msg.clone()));
        let serialized = serde_json::to_string(&admin_tx).expect("serialization should succeed");
        let deserialized: AdminTransaction =
            serde_json::from_str(&serialized).expect("deserialization should succeed");

        match deserialized {
            AdminTransaction::EpochComplete(deserialized_msg) => {
                assert_eq!(*deserialized_msg, msg);
                assert!(deserialized_msg.validate_internal_consistency().is_ok());
            }
            _ => panic!("Expected EpochComplete variant"),
        }
    }

    #[test]
    fn test_admin_transaction_epoch_change_and_synthesized_admin_handover_json_roundtrip() {
        let config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![],
            consensus_config: None,
        };
        let epoch_change = AdminTransaction::EpochChange(Box::new(config));
        let serialized =
            serde_json::to_string(&epoch_change).expect("serialization should succeed");
        let deserialized: AdminTransaction =
            serde_json::from_str(&serialized).expect("deserialization should succeed");
        assert!(matches!(deserialized, AdminTransaction::EpochChange(_)));

        let handover_record = create_test_handover_record(1, 0, 1, [0u8; 32]);
        let handover = SynthesizedAdmin::Handover(Box::new(handover_record));
        let serialized = serde_json::to_string(&handover).expect("serialization should succeed");
        let deserialized: SynthesizedAdmin =
            serde_json::from_str(&serialized).expect("deserialization should succeed");
        assert!(matches!(deserialized, SynthesizedAdmin::Handover(_)));
    }

    #[test]
    fn test_admin_transaction_epoch_change_bcs_roundtrip() {
        let config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(4),
            new_epoch: EpochIdentifier::new(5),
            validators: vec![],
            consensus_config: Some(EpochConsensusConfig {
                num_leaders_per_round: Some(2),
                ..Default::default()
            }),
        };

        let admin_tx = AdminTransaction::EpochChange(Box::new(config));
        let bytes = bcs::to_bytes(&admin_tx).expect("BCS serialization should succeed");
        let deserialized: AdminTransaction =
            bcs::from_bytes(&bytes).expect("BCS deserialization should succeed");

        match deserialized {
            AdminTransaction::EpochChange(cfg) => {
                assert_eq!(cfg.new_epoch, EpochIdentifier::new(5));
            }
            _ => panic!("Expected EpochChange"),
        }
    }

    #[test]
    fn test_synthesized_admin_handover_bcs_roundtrip() {
        let epoch_config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![],
            consensus_config: None,
        };

        let record = HandoverRecord::new(
            100,
            EpochIdentifier::new(0),
            EpochIdentifier::new(1),
            epoch_config,
            [0u8; BLAKE3_HASH_SIZE],
        );

        let inner = SynthesizedAdmin::Handover(Box::new(record));
        let bytes = bcs::to_bytes(&inner).expect("BCS serialization should succeed");
        let deserialized: SynthesizedAdmin =
            bcs::from_bytes(&bytes).expect("BCS deserialization should succeed");

        match deserialized {
            SynthesizedAdmin::Handover(r) => {
                assert_eq!(r.block_index(), 100);
                assert_eq!(r.dest_epoch(), EpochIdentifier::new(1));
            }
            _ => panic!("Expected Handover"),
        }
    }

    #[test]
    fn test_admin_transaction_snapshot_attestation_submission_bcs_roundtrip() {
        let record = create_test_snapshot_record(500, 2);
        let (authority_key, protocol_keypair, _) = create_test_keys_with_keypair(700);

        let attestation =
            Attestation::<SnapshotRecord>::sign(&record, &protocol_keypair, &authority_key)
                .expect("sign() should succeed");

        let submission = SnapshotAttestationSubmission::new(record.clone(), attestation);

        let admin_tx = AdminTransaction::SnapshotAttestationSubmission(Box::new(submission));
        let bytes = bcs::to_bytes(&admin_tx).expect("BCS serialization should succeed");
        let deserialized: AdminTransaction =
            bcs::from_bytes(&bytes).expect("BCS deserialization should succeed");

        match deserialized {
            AdminTransaction::SnapshotAttestationSubmission(sub) => {
                assert_eq!(sub.snapshot_record(), &record);
                assert!(sub.validate_digest_consistency().is_ok());
            }
            _ => panic!("Expected SnapshotAttestationSubmission"),
        }
    }

    #[test]
    fn test_synthesized_admin_snapshot_certificate_bcs_roundtrip() {
        let record = create_test_snapshot_record(200, 3);
        let cert = SnapshotCertificate::new(record.clone());

        let inner = SynthesizedAdmin::SnapshotCertificate(Box::new(cert));
        let bytes = bcs::to_bytes(&inner).expect("BCS serialization should succeed");
        let deserialized: SynthesizedAdmin =
            bcs::from_bytes(&bytes).expect("BCS deserialization should succeed");

        match deserialized {
            SynthesizedAdmin::SnapshotCertificate(c) => {
                assert_eq!(c.snapshot_record(), &record);
            }
            _ => panic!("Expected SnapshotCertificate"),
        }
    }

    #[test]
    fn test_admin_transaction_epoch_complete_bcs_roundtrip() {
        let (msg, _) = create_test_epoch_complete_message(5030);

        let admin_tx = AdminTransaction::EpochComplete(Box::new(msg.clone()));
        let bytes = bcs::to_bytes(&admin_tx).expect("BCS serialization should succeed");
        let deserialized: AdminTransaction =
            bcs::from_bytes(&bytes).expect("BCS deserialization should succeed");

        match deserialized {
            AdminTransaction::EpochComplete(deserialized_msg) => {
                assert_eq!(*deserialized_msg, msg);
            }
            _ => panic!("Expected EpochComplete"),
        }
    }
}