rialo-types 0.4.1

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
// 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).
//! - [`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 handover;
mod snapshot;
#[cfg(test)]
mod test_helpers;

// 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 handover::{
    HandoverAttestation, HandoverCertificate, HandoverCertificateAddAttestationError,
    HandoverChain, HandoverChainError, HandoverRecord,
};
pub use snapshot::{
    SnapshotAttestation, SnapshotAttestationSubmission, SnapshotAttestationSubmissionError,
    SnapshotCertificate, SnapshotCertificateAddAttestationError, SnapshotRecord,
};

/// Wrapper for admin transactions that go through consensus.
///
/// Admin transactions are privileged operations that are processed
/// separately from regular user transactions and REX updates.
///
/// # 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.
#[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 record 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<HandoverRecord>),

    /// A snapshot attestation submission from a validator.
    ///
    /// Bundles a `SnapshotRecord` with a signed `SnapshotAttestation` for
    /// consensus delivery. Validators submit these after creating a snapshot.
    SnapshotAttestationSubmission(Box<SnapshotAttestationSubmission>),
}

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

    use super::{
        test_helpers::{
            test_keys::create_test_keys_with_keypair, test_records::create_test_snapshot_record,
        },
        *,
    };
    use crate::consensus_crypto::{AuthorityPublicKey, NetworkPublicKey, ProtocolPublicKey};

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

    /// 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(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);
    }

    #[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_admin_transaction_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 admin_tx = AdminTransaction::Handover(Box::new(record));
        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(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_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_admin_transaction_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 admin_tx = AdminTransaction::Handover(Box::new(record));
        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::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"),
        }
    }
}