rialo-types 0.2.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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
// 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).

use rialo_s_pubkey::Pubkey;
use serde::{Deserialize, Serialize};

use crate::{
    consensus_crypto::{AuthorityPublicKey, NetworkPublicKey, ProtocolPublicKey},
    Multiaddr,
};

/// 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];

/// An identifier for an epoch.
///
/// This is a newtype wrapper around `u64` to provide type safety when working
/// with epoch numbers, preventing accidental mixing with other numeric types.
#[derive(
    Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
#[repr(transparent)]
pub struct EpochIdentifier(u64);

impl EpochIdentifier {
    /// Creates a new epoch identifier from a `u64`.
    pub const fn new(epoch: u64) -> Self {
        Self(epoch)
    }

    /// Returns the epoch as a `u64`.
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    /// Returns the bytes of the epoch in little-endian order.
    pub const fn to_le_bytes(self) -> [u8; 8] {
        self.0.to_le_bytes()
    }
}

impl From<u64> for EpochIdentifier {
    fn from(epoch: u64) -> Self {
        Self(epoch)
    }
}

impl From<EpochIdentifier> for u64 {
    fn from(epoch: EpochIdentifier) -> Self {
        epoch.0
    }
}

impl std::fmt::Display for EpochIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// 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;

/// Configuration for a new epoch's validator set and consensus parameters.
///
/// This is submitted via the `submitEpochChange` RPC endpoint to initiate
/// an epoch transition. The configuration specifies the complete set of
/// validators for the new epoch along with their networking information.
///
/// Note: If a validator is staying across epochs, it must run two consensus
/// protocols simultaneously, so the network ports for the new epoch must be
/// different from the old epoch's ports.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct EpochChangeConfig {
    /// The current epoch number (the epoch being transitioned from).
    /// This must match the actual current epoch when the transaction is processed.
    /// TODO: Instead of using a number for the current epoch we should use the hash of the certificate for the epoch - <https://linear.app/subzero-labs/issue/SUB-1505/create-a-chain-of-governance-tx>
    pub current_epoch: EpochIdentifier,

    /// The epoch number being transitioned to.
    /// This must be greater than `current_epoch`.
    pub new_epoch: EpochIdentifier,

    /// The validators participating in the new epoch.
    /// Each validator entry contains their stake, network addresses, and keys.
    pub validators: Vec<ValidatorInfo>,

    /// Optional consensus configuration overrides for the new epoch.
    /// If not provided, the current epoch's configuration will be used.
    pub consensus_config: Option<EpochConsensusConfig>,
}

impl EpochChangeConfig {
    /// Computes a deterministic Blake3 hash of this epoch change configuration.
    ///
    /// The hash is computed by serializing the configuration in a canonical format:
    /// - current_epoch (8 bytes LE)
    /// - new_epoch (8 bytes LE)
    /// - number of validators (8 bytes LE)
    /// - for each validator (in order):
    ///   - stake (8 bytes LE)
    ///   - consensus_address (length-prefixed bytes)
    ///   - state_sync_address (length-prefixed bytes)
    ///   - hostname (length-prefixed bytes)
    ///   - authority_key (96 bytes)
    ///   - protocol_key (32 bytes)
    ///   - network_key (32 bytes)
    ///   - signing_key (32 bytes)
    /// - consensus_config presence flag (1 byte: 0 or 1)
    /// - if consensus_config is present:
    ///   - each optional field with presence flag and value
    ///
    /// This produces a stable hash that uniquely identifies the configuration.
    pub fn deterministic_hash(&self) -> [u8; BLAKE3_HASH_SIZE] {
        let mut hasher = blake3::Hasher::new();

        // Hash epoch numbers
        hasher.update(&self.current_epoch.to_le_bytes());
        hasher.update(&self.new_epoch.to_le_bytes());

        // Hash validators count and each validator
        hasher.update(&(self.validators.len() as u64).to_le_bytes());
        for validator in &self.validators {
            hasher.update(&validator.stake.to_le_bytes());

            // Hash addresses as length-prefixed bytes
            let consensus_addr_bytes = validator.consensus_address.to_string();
            hasher.update(&(consensus_addr_bytes.len() as u64).to_le_bytes());
            hasher.update(consensus_addr_bytes.as_bytes());

            let state_sync_addr_bytes = validator.state_sync_address.to_string();
            hasher.update(&(state_sync_addr_bytes.len() as u64).to_le_bytes());
            hasher.update(state_sync_addr_bytes.as_bytes());

            // Hash hostname
            hasher.update(&(validator.hostname.len() as u64).to_le_bytes());
            hasher.update(validator.hostname.as_bytes());

            // Hash keys
            hasher.update(&validator.authority_key.to_bytes());
            hasher.update(&validator.protocol_key.to_bytes());
            hasher.update(&validator.network_key.to_bytes());
            hasher.update(validator.signing_key.as_ref());
        }

        // Hash consensus config
        match &self.consensus_config {
            Some(config) => {
                hasher.update(&[1u8]); // Present flag

                // Hash each optional field with presence flag
                Self::hash_optional_usize(&mut hasher, config.num_leaders_per_round);
                Self::hash_optional_u64(&mut hasher, config.max_transactions_in_block_bytes);
                Self::hash_optional_u64(&mut hasher, config.max_num_transactions_in_block);
                Self::hash_optional_u64(&mut hasher, config.max_transaction_size_bytes);
                Self::hash_optional_u32(&mut hasher, config.gc_depth);
                Self::hash_optional_bool(&mut hasher, config.zstd_compression);
            }
            None => {
                hasher.update(&[0u8]); // Absent flag
            }
        }

        *hasher.finalize().as_bytes()
    }

    fn hash_optional_usize(hasher: &mut blake3::Hasher, value: Option<usize>) {
        match value {
            Some(v) => {
                hasher.update(&[1u8]);
                hasher.update(&(v as u64).to_le_bytes());
            }
            None => {
                hasher.update(&[0u8]);
            }
        }
    }

    fn hash_optional_u64(hasher: &mut blake3::Hasher, value: Option<u64>) {
        match value {
            Some(v) => {
                hasher.update(&[1u8]);
                hasher.update(&v.to_le_bytes());
            }
            None => {
                hasher.update(&[0u8]);
            }
        }
    }

    fn hash_optional_u32(hasher: &mut blake3::Hasher, value: Option<u32>) {
        match value {
            Some(v) => {
                hasher.update(&[1u8]);
                hasher.update(&v.to_le_bytes());
            }
            None => {
                hasher.update(&[0u8]);
            }
        }
    }

    fn hash_optional_bool(hasher: &mut blake3::Hasher, value: Option<bool>) {
        match value {
            Some(v) => {
                hasher.update(&[1u8]);
                hasher.update(&[v as u8]);
            }
            None => {
                hasher.update(&[0u8]);
            }
        }
    }
}

/// Information about a validator in the new epoch.
///
/// Contains all the necessary information to identify and communicate
/// with a validator in the consensus protocol.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ValidatorInfo {
    /// Voting power/stake of the validator.
    pub stake: u64,

    /// Network address for consensus protocol communication.
    /// Format: multiaddr (e.g., "/ip4/127.0.0.1/udp/10100")
    pub consensus_address: Multiaddr,

    /// Network address for state sync communication.
    /// Format: multiaddr (e.g., "/ip4/127.0.0.1/udp/20100")
    pub state_sync_address: Multiaddr,

    /// Human-readable hostname for metrics and logging.
    pub hostname: String,

    /// The validator's BLS12-381 public key for authority identity.
    pub authority_key: AuthorityPublicKey,

    /// The validator's Ed25519 public key for verifying blocks.
    pub protocol_key: ProtocolPublicKey,

    /// The validator's Ed25519 public key for TLS and network identity.
    pub network_key: NetworkPublicKey,

    /// The validator's public key for signing transactions.
    pub signing_key: Pubkey,
}

/// Consensus configuration parameters that can be adjusted per-epoch.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct EpochConsensusConfig {
    /// Number of leaders per round for Mysticeti commits.
    pub num_leaders_per_round: Option<usize>,

    /// Maximum size of transactions included in a consensus block (bytes).
    pub max_transactions_in_block_bytes: Option<u64>,

    /// Maximum number of transactions included in a consensus block.
    pub max_num_transactions_in_block: Option<u64>,

    /// Maximum serialized transaction size (bytes).
    pub max_transaction_size_bytes: Option<u64>,

    /// Garbage collection depth for consensus.
    pub gc_depth: Option<u32>,

    /// Enable zstd compression for consensus network.
    pub zstd_compression: Option<bool>,
}

/// Size of the signing message for ValidatorReadyMessage.
/// Format: current_epoch (8 bytes) || epoch_config_hash (32 bytes) = 40 bytes
pub const READY_MESSAGE_SIGNING_SIZE: usize = 8 + BLAKE3_HASH_SIZE;

/// A ready message sent by a validator to signal readiness for an epoch change.
///
/// This message is broadcast by validators in either the current epoch or the
/// proposed new epoch when they see an `AdminTransaction::EpochChange`. The message
/// includes the validator's signature over the epoch transition.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ValidatorReadyMessage {
    /// The current epoch number (the epoch being transitioned from).
    /// TODO: Instead of using a number for the current epoch we should use the hash of the certificate for the epoch - <https://linear.app/subzero-labs/issue/SUB-1505/create-a-chain-of-governance-tx>
    pub current_epoch: EpochIdentifier,

    /// The deterministic hash of the EpochChangeConfig being agreed upon.
    /// This binds the ready message to a specific epoch configuration, preventing
    /// validators from accidentally agreeing to different configurations.
    pub epoch_config_hash: [u8; BLAKE3_HASH_SIZE],

    /// The validator's authority public key identifying the sender.
    /// This is used to verify the sender is a validator in the current or new epoch.
    pub authority_key: AuthorityPublicKey,

    /// The validator's protocol public key used to verify the signature.
    pub protocol_key: ProtocolPublicKey,

    /// Ed25519 signature over the epoch transition (current_epoch + epoch_config_hash as 40 bytes).
    /// The signature is created using the validator's protocol key.
    #[serde(with = "serde_big_array::BigArray")]
    pub signature: [u8; ED25519_SIGNATURE_SIZE],
}

impl ValidatorReadyMessage {
    /// Returns the message bytes that should be signed.
    ///
    /// The message format is: current_epoch (8 bytes LE) || epoch_config_hash (32 bytes)
    pub fn signing_message(
        current_epoch: EpochIdentifier,
        epoch_config_hash: &[u8; BLAKE3_HASH_SIZE],
    ) -> [u8; READY_MESSAGE_SIGNING_SIZE] {
        let mut msg = [0u8; READY_MESSAGE_SIGNING_SIZE];
        msg[0..8].copy_from_slice(&current_epoch.to_le_bytes());
        msg[8..READY_MESSAGE_SIGNING_SIZE].copy_from_slice(epoch_config_hash);
        msg
    }

    /// Returns the message bytes for this ready message.
    pub fn message_bytes(&self) -> [u8; READY_MESSAGE_SIGNING_SIZE] {
        Self::signing_message(self.current_epoch, &self.epoch_config_hash)
    }
}

/// A handover certificate marking an epoch transition.
///
/// This is auto-generated by BlockPool when Ready quorum is reached.
/// Contains the full EpochChangeConfig, making the certificate self-contained
/// for syncing nodes to verify and process epoch transitions.
///
/// Note: This is the unsigned certificate. `SignedHandoverCertificate` (with
/// validator signatures) will be added in a future phase.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct HandoverCertificate {
    /// Block index of this Handover in the main chain.
    pub block_index: u64,

    /// The epoch being transitioned from.
    pub source_epoch: EpochIdentifier,

    /// The epoch being transitioned to.
    pub dest_epoch: EpochIdentifier,

    /// Full configuration for the new epoch (self-contained).
    /// This allows syncing nodes to verify the epoch transition without
    /// needing to look up the original EpochChange transaction.
    pub epoch_config: EpochChangeConfig,

    /// Blake3 hash of the previous HandoverCertificate (forms skiplist chain).
    /// - Genesis: zero hash `[0u8; 32]`
    /// - Subsequent: Blake3 hash of the previous certificate
    pub previous_handover_hash: Blake3Hash,
}

impl HandoverCertificate {
    /// Computes the deterministic Blake3 hash of this certificate.
    ///
    /// This hash is used as `previous_handover_hash` in the next certificate,
    /// forming the skiplist chain.
    pub fn deterministic_hash(&self) -> Blake3Hash {
        let mut hasher = blake3::Hasher::new();

        // Hash block index
        hasher.update(&self.block_index.to_le_bytes());

        // Hash epoch identifiers
        hasher.update(&self.source_epoch.to_le_bytes());
        hasher.update(&self.dest_epoch.to_le_bytes());

        // Hash the epoch config using its deterministic hash
        hasher.update(&self.epoch_config.deterministic_hash());

        // Hash the previous handover hash
        hasher.update(&self.previous_handover_hash);

        *hasher.finalize().as_bytes()
    }

    /// Creates a genesis handover certificate.
    ///
    /// Genesis is a degenerate certificate where `source_epoch == dest_epoch`
    /// and `previous_handover_hash` is zero.
    pub fn genesis(epoch: EpochIdentifier, epoch_config: EpochChangeConfig) -> Self {
        Self {
            block_index: 0,
            source_epoch: epoch,
            dest_epoch: epoch,
            epoch_config,
            previous_handover_hash: [0u8; BLAKE3_HASH_SIZE],
        }
    }

    /// Returns true if this is a genesis certificate.
    ///
    /// A genesis certificate has `source_epoch == dest_epoch == 0`.
    pub fn is_genesis(&self) -> bool {
        self.source_epoch == EpochIdentifier::from(0) && self.dest_epoch == EpochIdentifier::from(0)
    }
}

/// A snapshot attestation from a validator.
///
/// This message is generated by validators after they successfully create a snapshot,
/// attesting to the existence of a snapshot at a specific block height with a given
/// key-value hash. When f+1 validators attest to the same snapshot, it becomes
/// a certified snapshot.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct SnapshotAttestation {
    /// The block height at which the snapshot was taken.
    pub block_height: u64,

    /// The Blake3 hash of the snapshot's key-value state.
    pub keysvals_hash: [u8; BLAKE3_HASH_SIZE],

    /// The validator's authority public key identifying the sender.
    pub authority_key: AuthorityPublicKey,

    /// The validator's protocol public key used to verify the signature.
    pub protocol_key: ProtocolPublicKey,

    /// Ed25519 signature over (block_height || keysvals_hash) as 40 bytes.
    /// The signature is created using the validator's protocol key.
    #[serde(with = "serde_big_array::BigArray")]
    pub signature: [u8; ED25519_SIGNATURE_SIZE],
}

/// Size of the signing message for SnapshotAttestation.
/// Format: block_height (8 bytes) || keysvals_hash (32 bytes) = 40 bytes
pub const SNAPSHOT_ATTESTATION_SIGNING_SIZE: usize = 8 + BLAKE3_HASH_SIZE;

impl SnapshotAttestation {
    /// Returns the message bytes that should be signed for a snapshot attestation.
    ///
    /// The message format is: block_height (8 bytes LE) || keysvals_hash (32 bytes)
    pub fn signing_message(
        block_height: u64,
        keysvals_hash: &[u8; BLAKE3_HASH_SIZE],
    ) -> [u8; SNAPSHOT_ATTESTATION_SIGNING_SIZE] {
        let mut msg = [0u8; SNAPSHOT_ATTESTATION_SIGNING_SIZE];
        msg[0..8].copy_from_slice(&block_height.to_le_bytes());
        msg[8..SNAPSHOT_ATTESTATION_SIGNING_SIZE].copy_from_slice(keysvals_hash);
        msg
    }

    /// Returns the message bytes for this attestation.
    pub fn message_bytes(&self) -> [u8; SNAPSHOT_ATTESTATION_SIGNING_SIZE] {
        Self::signing_message(self.block_height, &self.keysvals_hash)
    }
}

/// Wrapper for admin transactions that go through consensus.
///
/// Admin transactions are privileged operations that are processed
/// separately from regular user transactions and oracle updates.
#[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 handover certificate marking an epoch transition.
    ///
    /// This is auto-generated by BlockPool when Ready quorum is reached.
    /// The Node detects epoch transitions by parsing this transaction from
    /// committed blocks.
    Handover(Box<HandoverCertificate>),

    /// A snapshot attestation from a validator.
    ///
    /// This is sent by validators after they create a snapshot, attesting to the
    /// snapshot's existence and hash. When f+1 validators attest to the same
    /// snapshot, it becomes certified and can be used for recovery.
    SnapshotAttestation(Box<SnapshotAttestation>),
}

#[cfg(test)]
mod tests {
    use fastcrypto::{ed25519, traits::KeyPair};
    use rand::SeedableRng;

    use super::*;
    use crate::consensus_crypto::{AuthorityPublicKey, NetworkPublicKey, ProtocolPublicKey};

    /// Helper to create test keys with a given seed for deterministic tests.
    fn create_test_keys(seed: u64) -> (AuthorityPublicKey, ProtocolPublicKey, NetworkPublicKey) {
        let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
        let authority_key = AuthorityPublicKey::new(
            fastcrypto::bls12381::min_sig::BLS12381KeyPair::generate(&mut rng)
                .public()
                .clone(),
        );
        let protocol_key =
            ProtocolPublicKey::new(ed25519::Ed25519KeyPair::generate(&mut rng).public().clone());
        let network_key =
            NetworkPublicKey::new(ed25519::Ed25519KeyPair::generate(&mut rng).public().clone());
        (authority_key, protocol_key, network_key)
    }

    #[test]
    fn test_epoch_change_config_serialization() {
        let (authority_key, protocol_key, network_key) = create_test_keys(42);
        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);
    }

    #[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(43);
        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);
    }

    #[test]
    fn test_validator_ready_message_signing_message() {
        let (authority_key, protocol_key, _) = create_test_keys(44);
        let epoch_config_hash = [0xABu8; BLAKE3_HASH_SIZE];
        let msg =
            ValidatorReadyMessage::signing_message(EpochIdentifier::new(0), &epoch_config_hash);
        let mut expected = [0u8; READY_MESSAGE_SIGNING_SIZE];
        expected[0..8].copy_from_slice(&0u64.to_le_bytes());
        expected[8..READY_MESSAGE_SIGNING_SIZE].copy_from_slice(&epoch_config_hash);
        assert_eq!(msg, expected);

        let ready_msg = ValidatorReadyMessage {
            current_epoch: EpochIdentifier::new(5),
            epoch_config_hash,
            authority_key,
            protocol_key,
            signature: [2u8; ED25519_SIGNATURE_SIZE],
        };
        let msg_bytes = ready_msg.message_bytes();
        let mut expected2 = [0u8; READY_MESSAGE_SIGNING_SIZE];
        expected2[0..8].copy_from_slice(&5u64.to_le_bytes());
        expected2[8..READY_MESSAGE_SIGNING_SIZE].copy_from_slice(&epoch_config_hash);
        assert_eq!(msg_bytes, expected2);
    }

    #[test]
    fn test_admin_transaction_ready_serialization() {
        let (authority_key, protocol_key, _) = create_test_keys(45);
        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_handover_certificate_serialization() {
        let epoch_config = EpochChangeConfig {
            current_epoch: EpochIdentifier::new(0),
            new_epoch: EpochIdentifier::new(1),
            validators: vec![],
            consensus_config: None,
        };

        let cert = HandoverCertificate {
            block_index: 42,
            source_epoch: EpochIdentifier::new(0),
            dest_epoch: EpochIdentifier::new(1),
            epoch_config,
            previous_handover_hash: [0xABu8; BLAKE3_HASH_SIZE],
        };

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

        assert_eq!(deserialized.block_index, 42);
        assert_eq!(deserialized.source_epoch, EpochIdentifier::new(0));
        assert_eq!(deserialized.dest_epoch, EpochIdentifier::new(1));
        assert_eq!(
            deserialized.previous_handover_hash,
            [0xABu8; BLAKE3_HASH_SIZE]
        );
    }

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

        let cert1 = HandoverCertificate {
            block_index: 42,
            source_epoch: EpochIdentifier::new(0),
            dest_epoch: EpochIdentifier::new(1),
            epoch_config: epoch_config.clone(),
            previous_handover_hash: [0u8; BLAKE3_HASH_SIZE],
        };

        // Same cert should produce same hash
        let cert2 = cert1.clone();
        assert_eq!(cert1.deterministic_hash(), cert2.deterministic_hash());

        // Different block_index should produce different hash
        let cert3 = HandoverCertificate {
            block_index: 43,
            ..cert1.clone()
        };
        assert_ne!(cert1.deterministic_hash(), cert3.deterministic_hash());

        // Different previous_handover_hash should produce different hash
        let cert4 = HandoverCertificate {
            previous_handover_hash: [1u8; BLAKE3_HASH_SIZE],
            ..cert1.clone()
        };
        assert_ne!(cert1.deterministic_hash(), cert4.deterministic_hash());
    }

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

        let genesis = HandoverCertificate::genesis(EpochIdentifier::new(0), epoch_config.clone());

        assert_eq!(genesis.block_index, 0);
        assert_eq!(genesis.source_epoch, EpochIdentifier::new(0));
        assert_eq!(genesis.dest_epoch, EpochIdentifier::new(0));
        assert_eq!(genesis.previous_handover_hash, [0u8; BLAKE3_HASH_SIZE]);
        assert_eq!(genesis.epoch_config, epoch_config);
    }

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

        // Genesis certificate: source_epoch == dest_epoch == 0
        let genesis = HandoverCertificate::genesis(EpochIdentifier::new(0), epoch_config.clone());
        assert!(genesis.is_genesis());

        // Non-genesis: source_epoch = 0, dest_epoch = 1
        let handover_0_to_1 = HandoverCertificate {
            block_index: 100,
            source_epoch: EpochIdentifier::new(0),
            dest_epoch: EpochIdentifier::new(1),
            epoch_config: epoch_config.clone(),
            previous_handover_hash: [0u8; BLAKE3_HASH_SIZE],
        };
        assert!(!handover_0_to_1.is_genesis());

        // Non-genesis: source_epoch = 1, dest_epoch = 1 (degenerate but not epoch 0)
        let handover_1_to_1 = HandoverCertificate {
            block_index: 200,
            source_epoch: EpochIdentifier::new(1),
            dest_epoch: EpochIdentifier::new(1),
            epoch_config: epoch_config.clone(),
            previous_handover_hash: [0u8; BLAKE3_HASH_SIZE],
        };
        assert!(!handover_1_to_1.is_genesis());

        // Non-genesis: source_epoch = 1, dest_epoch = 2
        let handover_1_to_2 = HandoverCertificate {
            block_index: 300,
            source_epoch: EpochIdentifier::new(1),
            dest_epoch: EpochIdentifier::new(2),
            epoch_config,
            previous_handover_hash: [0u8; BLAKE3_HASH_SIZE],
        };
        assert!(!handover_1_to_2.is_genesis());
    }

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

        let cert = HandoverCertificate {
            block_index: 100,
            source_epoch: EpochIdentifier::new(0),
            dest_epoch: EpochIdentifier::new(1),
            epoch_config,
            previous_handover_hash: [0u8; BLAKE3_HASH_SIZE],
        };

        let admin_tx = AdminTransaction::Handover(Box::new(cert));
        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::Handover(c) => {
                assert_eq!(c.block_index, 100);
                assert_eq!(c.source_epoch, EpochIdentifier::new(0));
                assert_eq!(c.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(50);
        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());
    }

    #[test]
    fn test_snapshot_attestation_serialization() {
        let (authority_key, protocol_key, _) = create_test_keys(60);
        let attestation = SnapshotAttestation {
            block_height: 100,
            keysvals_hash: [0xABu8; BLAKE3_HASH_SIZE],
            authority_key: authority_key.clone(),
            protocol_key: protocol_key.clone(),
            signature: [3u8; ED25519_SIGNATURE_SIZE],
        };

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

        assert_eq!(deserialized.block_height, 100);
        assert_eq!(deserialized.keysvals_hash, [0xABu8; BLAKE3_HASH_SIZE]);
        assert_eq!(deserialized.authority_key, authority_key);
        assert_eq!(deserialized.protocol_key, protocol_key);
        assert_eq!(deserialized.signature, [3u8; ED25519_SIGNATURE_SIZE]);
    }

    #[test]
    fn test_snapshot_attestation_signing_message() {
        let keysvals_hash = [0xCDu8; BLAKE3_HASH_SIZE];
        let msg = SnapshotAttestation::signing_message(42, &keysvals_hash);

        // Verify the message format: block_height (8 bytes LE) || keysvals_hash (32 bytes)
        assert_eq!(msg.len(), SNAPSHOT_ATTESTATION_SIGNING_SIZE);
        assert_eq!(msg[0..8], 42u64.to_le_bytes());
        assert_eq!(msg[8..SNAPSHOT_ATTESTATION_SIGNING_SIZE], keysvals_hash);

        // Test with different values
        let msg2 = SnapshotAttestation::signing_message(1000, &keysvals_hash);
        assert_eq!(msg2[0..8], 1000u64.to_le_bytes());
        assert_eq!(msg2[8..SNAPSHOT_ATTESTATION_SIGNING_SIZE], keysvals_hash);

        // Different block heights should produce different messages
        assert_ne!(msg, msg2);
    }

    #[test]
    fn test_snapshot_attestation_message_bytes() {
        let (authority_key, protocol_key, _) = create_test_keys(61);
        let keysvals_hash = [0xEFu8; BLAKE3_HASH_SIZE];
        let attestation = SnapshotAttestation {
            block_height: 12345,
            keysvals_hash,
            authority_key,
            protocol_key,
            signature: [0u8; ED25519_SIGNATURE_SIZE],
        };

        let msg_bytes = attestation.message_bytes();
        let expected = SnapshotAttestation::signing_message(12345, &keysvals_hash);

        assert_eq!(msg_bytes, expected);
        assert_eq!(msg_bytes[0..8], 12345u64.to_le_bytes());
        assert_eq!(
            msg_bytes[8..SNAPSHOT_ATTESTATION_SIGNING_SIZE],
            keysvals_hash
        );
    }

    #[test]
    fn test_admin_transaction_snapshot_attestation_serialization() {
        let (authority_key, protocol_key, _) = create_test_keys(62);
        let attestation = SnapshotAttestation {
            block_height: 999,
            keysvals_hash: [0x12u8; BLAKE3_HASH_SIZE],
            authority_key: authority_key.clone(),
            protocol_key: protocol_key.clone(),
            signature: [0x78u8; ED25519_SIGNATURE_SIZE],
        };

        let admin_tx = AdminTransaction::SnapshotAttestation(Box::new(attestation.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::SnapshotAttestation(att) => {
                assert_eq!(att.block_height, 999);
                assert_eq!(att.keysvals_hash, [0x12u8; BLAKE3_HASH_SIZE]);
                assert_eq!(att.authority_key, authority_key);
                assert_eq!(att.protocol_key, protocol_key);
                assert_eq!(att.signature, [0x78u8; ED25519_SIGNATURE_SIZE]);
            }
            _ => panic!("Expected SnapshotAttestation"),
        }
    }
}