rialo-validator-registry-interface 0.4.1

Instructions and constructors for a registry containing validator identities
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Instructions for the Validator registry program.

use std::collections::BTreeMap;

use rialo_s_instruction::{AccountMeta, Instruction};
use rialo_s_program::system_program;
use rialo_s_pubkey::Pubkey;
use serde::{Deserialize, Serialize};

/// Instructions supported by the Validator Registry program
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub enum ValidatorRegistryInstruction {
    /// Register a new validator in the registry. The signing_key account pays for and
    /// becomes the initial owner/withdrawer of the validator info PDA account.
    ///
    /// Returns `InstructionError::AccountAlreadyInitialized` if the validator is already
    /// registered.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA derived from authority_key)
    /// 1. `[signer, writable]` Signing key account (must match signing_key in instruction data, pays for PDA creation)
    /// 2. `[]` System program
    /// 3. `[writable]` Self-bond stake account (PDA derived from validator_info)
    /// 4. `[]` StakeManager program
    /// 5. `[]` ValidatorRegistry program (needed for ActivateStake → AddStake CPI callback)
    Register {
        /// The validator's signing key (the initial withdrawal key)
        signing_key: Pubkey,
        /// Network address for communicating with the authority.
        address: Vec<u8>,
        /// State sync address for state synchronization (Multiaddr bytes).
        state_sync_address: Vec<u8>,
        /// The authority's hostname, for metrics and logging.
        hostname: String,
        /// The authority's public key as Rialo identity.
        authority_key: Vec<u8>,
        /// The authority's public key for verifying blocks.
        protocol_key: Pubkey,
        /// The authority's public key for TLS and as network identity.
        network_key: Pubkey,
        /// The validator's commission from the inflation rewards
        /// in basis points, e.g. 835 corresponds to 8.35%
        commission_rate: u16,
        /// The minimum duration in milliseconds that StakeInfo accounts must commit
        /// to delegate for; can be set by the validator to earn
        /// increased rewards (bonus)
        lockup_period: u64,
    },

    /// Update the withdrawal key for a validator
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA - cannot sign)
    /// 1. `[signer]` Current withdrawal key
    /// 2. `[]` New withdrawal key
    UpdateWithdrawer {
        /// New authority who can withdraw rewards
        new_withdrawal_key: Pubkey,
    },

    /// Add stake to a validator's aggregate stake.
    ///
    /// This instruction is called via CPI from the StakeManager program when
    /// a stake account is activated (delegated to a validator). It increases
    /// the validator's `stake` field by the specified amount.
    ///
    /// This is a privileged operation that can only be called via CPI from
    /// the StakeManager program.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA derived from authority_key)
    AddStake {
        /// Amount of stake to add
        amount: u64,
    },

    /// Subtract stake from a validator's aggregate stake.
    ///
    /// This instruction is called via CPI from the StakeManager program when
    /// a stake account is deactivated. It decreases the validator's `stake`
    /// field by the specified amount.
    ///
    /// This is a privileged operation that can only be called via CPI from
    /// the StakeManager program.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA derived from authority_key)
    SubStake {
        /// Amount of stake to subtract
        amount: u64,
    },

    /// Set the unbonding period for a validator.
    ///
    /// This instruction sets the `unbonding_period` field on a validator's info account.
    /// The unbonding period determines how long deactivated stake must wait before
    /// it can be withdrawn. This is intended to be set by the runtime to punish
    /// misbehaving validators.
    ///
    /// **IMPORTANT:** This instruction can ONLY be called via CPI from the
    /// TokenomicsGovernance program. The processor verifies the CPI caller.
    /// Direct invocation will fail with `IncorrectProgramId`.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA derived from authority_key)
    SetUnbondingPeriod {
        /// The new unbonding period in milliseconds
        unbonding_period: u64,
    },

    /// Change the commission rate for a validator.
    ///
    /// This instruction allows a validator to request a commission rate change.
    /// The new rate is stored in `new_commission_rate` and will be applied at
    /// the next epoch boundary (during FreezeStakes) to give delegators time
    /// to react to the change.
    ///
    /// Validation:
    /// - 0 ≤ new_commission_rate ≤ MAX_COMMISSION_RATE (10000 basis points = 100%)
    /// - |new_commission_rate - current_commission_rate| ≤ MAX_COMMISSION_CHANGE (200 bp)
    ///   (protects delegators from sudden large changes)
    /// - If lockup_period > 0, only decreases are allowed (increases are rejected).
    ///   Validators with a lockup period commit to their commission rate in exchange
    ///   for higher delegation and commission revenue from the higher lockup rewards.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA)
    /// 1. `[signer]` Signing key (must match validator_account's signing_key)
    ChangeCommissionRate {
        /// New commission rate in basis points (e.g., 835 = 8.35%)
        new_commission_rate: u16,
    },

    /// Withdraw kelvins from a validator account.
    ///
    /// This instruction allows the withdrawal key to withdraw kelvins
    /// from the validator info account. This is typically used to withdraw
    /// accumulated rewards or excess funds.
    ///
    /// The withdrawal transfers kelvins from the validator info account to
    /// the withdrawal_key account. The validator account must have
    /// sufficient kelvins after the withdrawal to remain rent-exempt.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA)
    /// 1. `[signer, writable]` Withdrawal key (must match validator_account's withdrawal_key)
    Withdraw {
        /// Amount of kelvins to withdraw
        amount: u64,
    },

    /// Change the earliest shutdown timestamp for a validator.
    ///
    /// This instruction allows a validator to announce a future timestamp after which
    /// they don't intend to participate in committees and earn rewards.
    /// This is particularly important for validators with a lockup_period, to prevent
    /// new delegators from locking up their capital longer than it would be rewarded.
    ///
    /// When `earliest_shutdown` is `Some(timestamp)`:
    /// - The timestamp must be >= current_timestamp + lockup_period.
    ///   This ensures every currently-locked staker will have their full lockup
    ///   honored before the validator stops.
    ///
    /// When `earliest_shutdown` is `None`:
    /// - Resets the field, signaling the validator intends to continue operating.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA)
    /// 1. `[signer]` Signing key (must match validator_account's signing_key)
    ChangeEarliestShutdown {
        /// The earliest timestamp (ms) after which the validator intends to shut down,
        /// or None to reset/clear the shutdown signal.
        earliest_shutdown: Option<u64>,
    },

    /// Update the signing key for a validator.
    ///
    /// This instruction allows a validator to rotate their signing key.
    /// The current signing key must sign the transaction to authorize the change.
    ///
    /// **Note:** This only updates the ValidatorInfo account. If the validator's
    /// self-bond stake account uses the signing key as admin_authority (the default
    /// during registration), that authority must be updated separately via
    /// `StakeManager::change_admin_authority` to fully migrate control.
    ///
    /// Accounts expected:
    /// 0. `[writable]` Validator info account (PDA)
    /// 1. `[signer]` Current signing key (must match validator_account's signing_key)
    /// 2. `[]` New signing key
    UpdateSigner {
        /// The new signing key
        new_signing_key: Pubkey,
    },
}

/// Error type for converting a `StoredAccount` to `ValidatorInfo`.
#[cfg(feature = "typed-account")]
#[derive(Debug, thiserror::Error)]
pub enum ValidatorInfoParseError {
    /// The account is not owned by the ValidatorRegistry program.
    #[error("Account owner mismatch: expected {expected}, got {actual}")]
    InvalidOwner {
        expected: rialo_s_pubkey::Pubkey,
        actual: rialo_s_pubkey::Pubkey,
    },
    /// The account data could not be deserialized as `ValidatorInfo`.
    #[error("Failed to deserialize ValidatorInfo: {0}")]
    DeserializationFailed(#[from] bincode::Error),
}

/// Data structure for the validator information account. This data structure is meant to hold
/// all information about a validator, such that we can leverage it in Epoch negotiation
/// and create a proper `Authority` object on Epoch change.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct ValidatorInfo {
    /// The validator's public key for transaction signing.
    pub signing_key: Pubkey,
    /// The validator's public key for withdrawing commission.
    pub withdrawal_key: Pubkey,
    /// Amount of token staked.
    pub stake: u64,
    /// Network address for consensus protocol communication (Multiaddr bytes).
    pub address: Vec<u8>,
    /// Network address for state sync communication (Multiaddr bytes).
    pub state_sync_address: Vec<u8>,
    /// Human-readable hostname for metrics and logging.
    pub hostname: String,
    /// The validator's identity key (currently BLS12-381).
    pub authority_key: Vec<u8>,
    /// The validator's public key for verifying blocks (Ed25519).
    pub protocol_key: Pubkey,
    /// The validator's public key for TLS and as network identity (Ed25519).
    pub network_key: Pubkey,
    /// When the validator registered.
    pub registration_time: i64,
    /// Last time info was updated.
    pub last_update: i64,
    /// Historical unbonding periods: effective_from_timestamp → unbonding_period_ms.
    ///
    /// The duration in milliseconds that deactivating StakeInfo accounts wait before becoming
    /// inactive. Set by the runtime (via SetUnbondingPeriod) to punish misbehaving validators.
    ///
    /// The first entry (key = registration_time) contains the default unbonding period.
    /// Subsequent entries are added by SetUnbondingPeriod to extend or reduce the period.
    /// Entries are in ascending order by timestamp (guaranteed by BTreeMap).
    ///
    /// Note: A deactivated stake cannot be withdrawn until the unbonding period that was
    /// effective at deactivation time has elapsed — see `end_of_unbonding()`.
    pub unbonding_periods: BTreeMap<u64, u64>,
    /// The minimum duration in milliseconds that StakeInfo accounts must commit to delegate for.
    /// Can be set by the validator to earn increased rewards (bonus).
    /// Note: An activated stake cannot be deactivated until
    /// `current_timestamp >= activation_requested + lockup_period`.
    /// This is fixed at registration and cannot be changed.
    pub lockup_period: u64,
    /// The validator's commission from the inflation rewards
    /// in basis points, e.g. 835 corresponds to 8.35%
    pub commission_rate: u16,
    /// New commission_rate to be applied from the next epoch
    pub new_commission_rate: Option<u16>,
    /// Optional timestamp (ms) after which the validator does not intend to participate
    /// in committees. Must be >= current_timestamp + lockup_period when set.
    /// Passing None resets the field (validator decides to continue).
    pub earliest_shutdown: Option<u64>,
}

impl ValidatorInfo {
    /// Maximum number of historical unbonding period entries allowed in the `unbonding_periods` map.
    /// 100 entries × 16 bytes (8-byte key + 8-byte value) = 1600 bytes of map data.
    /// Enforced by the SetUnbondingPeriod handler to prevent unbounded account growth.
    // Old entries predating all currently-unbonding stakes could be pruned to reclaim space.
    pub const MAX_UNBONDING_PERIOD_ENTRIES: usize = 100;

    /// Calculate the account data size needed to store a `ValidatorInfo` with the given
    /// variable-length field sizes.
    ///
    /// Uses the in-memory struct size as a safe upper bound, plus the actual lengths of
    /// the variable-length fields (address, hostname, authority_key).
    #[inline]
    pub const fn account_size(
        address_len: usize,
        state_sync_address_len: usize,
        hostname_len: usize,
        authority_key_len: usize,
    ) -> usize {
        std::mem::size_of::<Self>()
            + address_len
            + state_sync_address_len
            + hostname_len
            + authority_key_len
    }

    /// Calculate when unbonding ends for a stake that requested deactivation at the given timestamp.
    ///
    /// This handles three cases correctly:
    /// 1. **Active stake**: Deactivated after punishment → uses punished period
    /// 2. **Unbonding stake**: Was unbonding when punishment hit → gets extended
    /// 3. **Fully unbonded**: Completed unbonding before punishment → exempt
    ///
    /// # Algorithm (Dual-Tracking)
    ///
    /// Uses two variables to achieve **fairness** (reductions apply to still-unbonding
    /// accounts) while preventing **flash attacks** (brief 0-period can't free accounts):
    ///
    /// - `max_end`: monotonically increasing, tracks the longest unbonding window ever
    ///   applicable. Used ONLY for the exemption check ("was this account genuinely done
    ///   before this entry?"). Prevents flash reductions from creating false exemption gaps.
    ///
    /// - `effective_end`: tracks the latest applicable period. This is the ACTUAL result.
    ///   Can decrease when governance reduces a punishment.
    ///
    /// # Complexity
    /// O(log n + k) where n = total entries, k = entries after deactivation (typically 0-2)
    ///
    /// # Arguments
    /// * `deactivation_requested` - When DeactivateStake was called (in milliseconds)
    ///
    /// # Returns
    /// The timestamp when unbonding completes
    pub fn end_of_unbonding(&self, deactivation_requested: u64) -> u64 {
        // Step 1: Binary search to find the unbonding_period at deactivation time.
        let initial_period = self
            .unbonding_periods
            .range(..=deactivation_requested)
            .next_back()
            .map(|(_, &period)| period)
            .unwrap_or(0);

        let initial_end = deactivation_requested.saturating_add(initial_period);
        let mut max_end = initial_end; // monotonic — for exemption check only
        let mut effective_end = initial_end; // latest applicable — the actual result

        // Step 2: Iterate entries AFTER deactivation.
        for (&entry_ts, &entry_period) in self.unbonding_periods.range((
            std::ops::Bound::Excluded(deactivation_requested),
            std::ops::Bound::Unbounded,
        )) {
            // Step 3a: Exemption check uses max_end (never decreases).
            // If the account was genuinely done before this entry, stop.
            if max_end < entry_ts {
                break;
            }

            // Step 3b: Apply this entry.
            let new_end = deactivation_requested.saturating_add(entry_period);
            max_end = max_end.max(new_end); // only grows (preserves exemption window)
            effective_end = new_end; // tracks latest (CAN decrease for reductions)
        }

        effective_end
    }
}

#[cfg(feature = "typed-account")]
impl TryFrom<rialo_s_account::StoredAccount> for ValidatorInfo {
    type Error = ValidatorInfoParseError;

    /// Attempts to parse a `StoredAccount` as a `ValidatorInfo`.
    ///
    /// # Errors
    /// - `ValidatorInfoParseError::InvalidOwner` if the account is not owned by the ValidatorRegistry program.
    /// - `ValidatorInfoParseError::DeserializationFailed` if the account data cannot be deserialized.
    fn try_from(account: rialo_s_account::StoredAccount) -> Result<Self, Self::Error> {
        use rialo_s_account::ReadableAccount;

        // Verify ownership
        let owner = *account.owner();
        if owner != crate::id() {
            return Err(ValidatorInfoParseError::InvalidOwner {
                expected: crate::id(),
                actual: owner,
            });
        }

        // Deserialize the account data
        let validator_info: ValidatorInfo = bincode::deserialize(account.data())?;
        Ok(validator_info)
    }
}

#[cfg(feature = "typed-account")]
impl TryFrom<&rialo_s_account::StoredAccount> for ValidatorInfo {
    type Error = ValidatorInfoParseError;

    /// Attempts to parse a reference to a `StoredAccount` as a `ValidatorInfo`.
    ///
    /// # Errors
    /// - `ValidatorInfoParseError::InvalidOwner` if the account is not owned by the ValidatorRegistry program.
    /// - `ValidatorInfoParseError::DeserializationFailed` if the account data cannot be deserialized.
    fn try_from(account: &rialo_s_account::StoredAccount) -> Result<Self, Self::Error> {
        use rialo_s_account::ReadableAccount;

        // Verify ownership
        let owner = *account.owner();
        if owner != crate::id() {
            return Err(ValidatorInfoParseError::InvalidOwner {
                expected: crate::id(),
                actual: owner,
            });
        }

        // Deserialize the account data
        let validator_info: ValidatorInfo = bincode::deserialize(account.data())?;
        Ok(validator_info)
    }
}

impl ValidatorRegistryInstruction {
    /// Create a `ValidatorRegistryInstruction::Register` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA derived from authority_key)
    ///   1. `[SIGNER, WRITABLE]` Signing key account (must match signing_key in instruction data, pays for PDA creation)
    ///   2. `[]` System program
    ///   3. `[WRITABLE]` Self-bond stake account (PDA derived from validator_info)
    ///   4. `[]` StakeManager program
    ///   5. `[]` ValidatorRegistry program (needed for ActivateStake → AddStake CPI callback)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `signing_key` - The validator's signing key (must sign, pays for PDA creation)
    /// * `address` - The network address for communicating with the authority
    /// * `state_sync_address` - The state sync address for state synchronization (Multiaddr bytes)
    /// * `hostname` - The hostname of the authority
    /// * `authority_key` - The public key of the authority (used to derive the PDA)
    /// * `protocol_key` - The public key for verifying blocks
    /// * `network_key` - The public key for TLS and as network identity
    /// * `commission_rate` - The validator's commission in basis points (e.g. 835 = 8.35%)
    /// * `lockup_period` - Minimum duration in milliseconds stake must be delegated for
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn register(
        validator_info_pubkey: Pubkey,
        signing_key: Pubkey,
        address: Vec<u8>,
        state_sync_address: Vec<u8>,
        hostname: String,
        authority_key: Vec<u8>,
        protocol_key: Pubkey,
        network_key: Pubkey,
        commission_rate: u16,
        lockup_period: u64,
    ) -> Instruction {
        // Derive self-bond PDA internally to avoid breaking caller interface
        let self_bond_pubkey = crate::pda::derive_self_bond_address(&validator_info_pubkey);

        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::Register {
                signing_key,
                address,
                state_sync_address,
                hostname,
                authority_key,
                protocol_key,
                network_key,
                commission_rate,
                lockup_period,
            },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // PDA, not a signer
                AccountMeta::new(signing_key, true), // signing key must sign and pays for PDA
                AccountMeta::new_readonly(system_program::id(), false), // system program
                AccountMeta::new(self_bond_pubkey, false), // self-bond PDA (writable)
                AccountMeta::new_readonly(crate::STAKE_MANAGER_PROGRAM_ID, false), // StakeManager program
                AccountMeta::new_readonly(crate::id(), false), // ValidatorRegistry program (for ActivateStake → AddStake CPI)
            ],
        )
    }

    /// Create a `ValidatorRegistryInstruction::UpdateWithdrawer` `Instruction`
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA - cannot sign)
    ///   1. `[SIGNER]` Current withdrawal key account
    ///   2. `[READONLY]` New withdrawal key account
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `current_withdrawer` - The public key of the current withdrawal key
    /// * `new_withdrawal_key` - The public key of the new withdrawal key
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn update_withdrawer(
        validator_info_pubkey: Pubkey,
        current_withdrawer: Pubkey,
        new_withdrawal_key: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::UpdateWithdrawer { new_withdrawal_key },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // PDA cannot sign
                AccountMeta::new_readonly(current_withdrawer, true),
                AccountMeta::new_readonly(new_withdrawal_key, false),
            ],
        )
    }

    /// Create a `ValidatorRegistryInstruction::AddStake` `Instruction`
    ///
    /// This instruction adds stake to a validator's aggregate stake.
    /// It is called via CPI from the StakeManager program when a stake
    /// account is activated (delegated to a validator).
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA derived from authority_key)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `amount` - The amount of stake to add
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn add_stake(validator_info_pubkey: Pubkey, amount: u64) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::AddStake { amount },
            vec![AccountMeta::new(validator_info_pubkey, false)],
        )
    }

    /// Create a `ValidatorRegistryInstruction::SubStake` `Instruction`
    ///
    /// This instruction subtracts stake from a validator's aggregate stake.
    /// It is called via CPI from the StakeManager program when a stake
    /// account is deactivated.
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA derived from authority_key)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `amount` - The amount of stake to subtract
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn sub_stake(validator_info_pubkey: Pubkey, amount: u64) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::SubStake { amount },
            vec![AccountMeta::new(validator_info_pubkey, false)],
        )
    }

    /// Create a `ValidatorRegistryInstruction::SetUnbondingPeriod` `Instruction`
    ///
    /// This instruction sets the unbonding period for a validator. The unbonding
    /// period determines how long deactivated stake must wait before it can be
    /// withdrawn. This is intended to be set by the runtime to punish misbehaving
    /// validators.
    ///
    /// **IMPORTANT:** This instruction can ONLY be called via CPI from the
    /// TokenomicsGovernance program. The processor verifies the CPI caller.
    /// Direct invocation will fail with `IncorrectProgramId`.
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA derived from authority_key)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `unbonding_period` - The new unbonding period in milliseconds
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn set_unbonding_period(
        validator_info_pubkey: Pubkey,
        unbonding_period: u64,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::SetUnbondingPeriod { unbonding_period },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // Validator info account (writable)
            ],
        )
    }

    /// Create a `ValidatorRegistryInstruction::ChangeCommissionRate` `Instruction`
    ///
    /// This instruction allows a validator to request a commission rate change.
    /// The new rate is stored in `new_commission_rate` and will be applied at
    /// the next epoch boundary (during FreezeStakes).
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA)
    ///   1. `[SIGNER]` Signing key (must match validator_account's signing_key)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `signing_key` - The validator's signing key (must sign)
    /// * `new_commission_rate` - The new commission rate in basis points (0-10000)
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn change_commission_rate(
        validator_info_pubkey: Pubkey,
        signing_key: Pubkey,
        new_commission_rate: u16,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::ChangeCommissionRate {
                new_commission_rate,
            },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // Validator info account (writable)
                AccountMeta::new_readonly(signing_key, true),   // Signing key must sign
            ],
        )
    }

    /// Create a `ValidatorRegistryInstruction::Withdraw` `Instruction`
    ///
    /// This instruction allows the withdrawal key to withdraw kelvins
    /// from a validator info account. The withdrawal transfers kelvins to the
    /// withdrawal_key account.
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA)
    ///   1. `[SIGNER, WRITABLE]` Withdrawal key (must match validator_account's withdrawal_key)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `withdrawal_key` - The public key of the withdrawal key (must sign)
    /// * `amount` - The amount of kelvins to withdraw
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn withdraw(
        validator_info_pubkey: Pubkey,
        withdrawal_key: Pubkey,
        amount: u64,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::Withdraw { amount },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // Validator info account (writable)
                AccountMeta::new(withdrawal_key, true), // Withdrawal key must sign, receives kelvins
            ],
        )
    }

    /// Create a `ValidatorRegistryInstruction::UpdateSigner` `Instruction`
    ///
    /// This instruction allows a validator to rotate their signing key.
    /// The current signing key must sign the transaction.
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA)
    ///   1. `[SIGNER]` Current signing key (must match validator_account's signing_key)
    ///   2. `[READONLY]` New signing key
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `current_signing_key` - The current signing key (must sign)
    /// * `new_signing_key` - The new signing key
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn update_signer(
        validator_info_pubkey: Pubkey,
        current_signing_key: Pubkey,
        new_signing_key: Pubkey,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::UpdateSigner { new_signing_key },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // PDA cannot sign
                AccountMeta::new_readonly(current_signing_key, true), // Current signing key must sign
                AccountMeta::new_readonly(new_signing_key, false),    // New signing key
            ],
        )
    }

    /// Create a `ValidatorRegistryInstruction::ChangeEarliestShutdown` `Instruction`
    ///
    /// This instruction allows a validator to announce (or clear) a future timestamp
    /// after which they don't intend to participate in committees.
    ///
    /// # Account references
    ///   0. `[WRITABLE]` Validator info account (PDA)
    ///   1. `[SIGNER]` Signing key (must match validator_account's signing_key)
    ///
    /// # Arguments
    /// * `validator_info_pubkey` - The public key of the validator info account (PDA)
    /// * `signing_key` - The validator's signing key (must sign)
    /// * `earliest_shutdown` - The shutdown timestamp in ms, or None to clear
    ///
    /// # Returns
    /// * `Instruction` - A Solana instruction to be included in a transaction
    pub fn change_earliest_shutdown(
        validator_info_pubkey: Pubkey,
        signing_key: Pubkey,
        earliest_shutdown: Option<u64>,
    ) -> Instruction {
        Instruction::new_with_bincode(
            crate::id(),
            &ValidatorRegistryInstruction::ChangeEarliestShutdown { earliest_shutdown },
            vec![
                AccountMeta::new(validator_info_pubkey, false), // Validator info account (writable)
                AccountMeta::new_readonly(signing_key, true),   // Signing key must sign
            ],
        )
    }
}

#[cfg(test)]
mod tests {
    use std::net::Ipv4Addr;

    use fastcrypto::{
        bls12381::min_sig::BLS12381KeyPair,
        traits::{KeyPair, ToFromBytes},
    };
    use multiaddr::Multiaddr;

    use super::*;

    fn create_test_pubkeys() -> (Pubkey, Pubkey, Pubkey) {
        let validator_info_pubkey = Pubkey::new_unique();
        let signing_key = Pubkey::new_unique();
        let new_withdrawer = Pubkey::new_unique();
        (validator_info_pubkey, signing_key, new_withdrawer)
    }

    #[test]
    fn test_register_instruction() {
        let mut rng = rand::thread_rng();

        let (validator_info_pubkey, signing_key, protocol_key) = create_test_pubkeys();

        let hostname = String::from("localhost");
        let authority_key = BLS12381KeyPair::generate(&mut rng)
            .public()
            .as_bytes()
            .to_vec();
        let network_key = Pubkey::new_unique();
        let address = Multiaddr::from(Ipv4Addr::LOCALHOST);
        let commission_rate = 500u16; // 5%
        let lockup_period = 10u64;

        // Create the register instruction
        let instruction = ValidatorRegistryInstruction::register(
            validator_info_pubkey,
            signing_key,
            address.to_vec(),
            vec![], // state_sync_address
            hostname.clone(),
            authority_key.clone(),
            protocol_key,
            network_key,
            commission_rate,
            lockup_period,
        );

        // Verify the program ID
        assert_eq!(instruction.program_id, crate::id());

        // Verify first 3 accounts (the remaining 3 are derived internally)
        assert_eq!(instruction.accounts.len(), 6);
        assert_eq!(
            instruction.accounts[0],
            AccountMeta::new(validator_info_pubkey, false)
        ); // PDA
        assert_eq!(instruction.accounts[1], AccountMeta::new(signing_key, true)); // signing key (signer)
        assert_eq!(
            instruction.accounts[2],
            AccountMeta::new_readonly(system_program::id(), false)
        ); // system program
           // [3] = self-bond PDA (derived from validator_info_pubkey)
        assert!(instruction.accounts[3].is_writable);
        assert!(!instruction.accounts[3].is_signer);
        // [4] = StakeManager program
        assert_eq!(
            instruction.accounts[4].pubkey,
            crate::STAKE_MANAGER_PROGRAM_ID
        );
        assert!(!instruction.accounts[4].is_writable);
        // [5] = ValidatorRegistry program (for ActivateStake → AddStake CPI)
        assert_eq!(instruction.accounts[5].pubkey, crate::id());
        assert!(!instruction.accounts[5].is_writable);

        // Deserialize and verify instruction data
        let decoded_instruction: ValidatorRegistryInstruction =
            bincode::deserialize(&instruction.data).unwrap();

        match decoded_instruction {
            ValidatorRegistryInstruction::Register {
                signing_key: decoded_signing_key,
                address: decoded_address,
                state_sync_address: decoded_state_sync_address,
                hostname: decoded_hostname,
                authority_key: decoded_authority_key,
                protocol_key: decoded_protocol_key,
                network_key: decoded_network_key,
                commission_rate: decoded_commission_rate,
                lockup_period: decoded_lockup_period,
            } => {
                assert_eq!(decoded_signing_key, signing_key);
                assert_eq!(decoded_address, address.to_vec());
                assert_eq!(decoded_state_sync_address, Vec::<u8>::new());
                assert_eq!(decoded_hostname, hostname);
                assert_eq!(decoded_authority_key, authority_key);
                assert_eq!(decoded_protocol_key, protocol_key);
                assert_eq!(decoded_network_key, network_key);
                assert_eq!(decoded_commission_rate, commission_rate);
                assert_eq!(decoded_lockup_period, lockup_period);
            }
            _ => panic!("Expected Register instruction"),
        }
    }

    /// Helper to create a ValidatorInfo with the given unbonding_periods map.
    fn vi_with_periods(periods: BTreeMap<u64, u64>) -> ValidatorInfo {
        ValidatorInfo {
            signing_key: Pubkey::default(),
            withdrawal_key: Pubkey::default(),
            stake: 0,
            address: vec![],
            state_sync_address: vec![],
            hostname: String::new(),
            authority_key: vec![],
            protocol_key: Pubkey::default(),
            network_key: Pubkey::default(),
            registration_time: 0,
            last_update: 0,
            unbonding_periods: periods,
            lockup_period: 0,
            commission_rate: 0,
            new_commission_rate: None,
            earliest_shutdown: None,
        }
    }

    /// Single entry — uses the one period (backward compatible with old behavior).
    #[test]
    fn test_end_of_unbonding_single_entry() {
        let vi = vi_with_periods(BTreeMap::from([(0, 7)]));
        assert_eq!(vi.end_of_unbonding(100), 107); // 100 + 7
    }

    /// Empty map — should return deactivation_requested + 0 = deactivation_requested.
    #[test]
    fn test_end_of_unbonding_empty_map() {
        let vi = vi_with_periods(BTreeMap::new());
        assert_eq!(vi.end_of_unbonding(100), 100); // 100 + 0
    }

    /// No punishment during unbonding (exempt).
    ///
    /// unbonding_periods = { 0: 7, 1000: 30 }
    /// deactivation_requested = 100
    /// initial_end = 100 + 7 = 107
    /// Check entry at 1000: max_end(107) < 1000 → exempt, break
    /// Result: 107 (original period, not affected by later punishment)
    #[test]
    fn test_end_of_unbonding_example1_exempt() {
        let vi = vi_with_periods(BTreeMap::from([(0, 7), (1000, 30)]));
        assert_eq!(vi.end_of_unbonding(100), 107);
    }

    /// Punishment during unbonding (extended).
    ///
    /// unbonding_periods = { 0: 7, 50: 30 }
    /// deactivation_requested = 100
    /// initial_period = 30 (entry at 50, which is <= 100)
    /// Result: 100 + 30 = 130
    #[test]
    fn test_end_of_unbonding_example2_deactivated_after_punishment() {
        let vi = vi_with_periods(BTreeMap::from([(0, 7), (50, 30)]));
        assert_eq!(vi.end_of_unbonding(100), 130);
    }

    /// Deactivated before punishment, still unbonding when hit.
    ///
    /// unbonding_periods = { 0: 7, 105: 30 }
    /// deactivation_requested = 100
    /// initial_end = 107, max_end = 107
    /// Entry at 105: max_end(107) >= 105 → apply. new_end = 130, max_end = 130
    /// Result: 130 = 100 + 30
    #[test]
    fn test_end_of_unbonding_example3_extended_during_unbonding() {
        let vi = vi_with_periods(BTreeMap::from([(0, 7), (105, 30)]));
        assert_eq!(vi.end_of_unbonding(100), 130);
    }

    /// Multiple punishments, partial application.
    ///
    /// unbonding_periods = { 0: 5, 104: 10, 200: 30 }
    /// deactivation_requested = 100
    /// initial_end = 105, max_end = 105
    /// Entry at 104: max_end(105) >= 104 → apply. new_end = 110, max_end = 110
    /// Entry at 200: max_end(110) < 200 → exempt, break
    /// Result: 110 = 100 + 10
    #[test]
    fn test_end_of_unbonding_example4_partial_application() {
        let vi = vi_with_periods(BTreeMap::from([(0, 5), (104, 10), (200, 30)]));
        assert_eq!(vi.end_of_unbonding(100), 110);
    }

    /// Genuine reduction (fairness).
    ///
    /// unbonding_periods = { 0: 2, 100: 30, 500: 7 }
    /// deactivation_requested = 200 (during 30-period phase)
    /// initial_period = 30 (entry at 100), initial_end = 230
    /// Entry at 500: max_end(230) >= 500? No (230 < 500) → exempt, break
    ///
    /// In that case, 200 + 30 = 230 < 500. So the account IS exempt and gets 230.
    ///
    /// This is because in real milliseconds, 30 days = 2,592,000,000 ms >> 500.
    ///
    #[test]
    fn test_end_of_unbonding_example5_reduction_fairness() {
        let day: u64 = 86_400_000; // 1 day in ms
        let vi = vi_with_periods(BTreeMap::from([
            (0, 2 * day),
            (100, 30 * day),
            (500, 7 * day),
        ]));
        // deactivation at 200 (during 30-day phase)
        // initial_period = 30 days, initial_end = 200 + 30*day
        // Entry at 500: max_end(200 + 30*day) >= 500? Yes (huge) → apply
        //   new_end = 200 + 7*day, max_end = max(200+30d, 200+7d) = 200+30d
        //   effective_end = 200 + 7*day
        // Result: 200 + 7 days ← reduction applied! ✅
        assert_eq!(vi.end_of_unbonding(200), 200 + 7 * day);
    }

    ///  Mistaken lowering then revert (flash resistance).
    ///
    /// unbonding_periods = { 0: 30_days, 100: 0, 101: 30_days }
    /// deactivation_requested = 50
    /// initial_end = 50 + 30d, max_end = 50+30d
    /// Entry at 100: max_end(50+30d) >= 100 → apply. new_end = 50. max_end stays 50+30d.
    /// Entry at 101: max_end(50+30d) >= 101 → apply. new_end = 50+30d. max_end stays.
    /// effective_end = 50 + 30d ← punishment preserved! ✅
    #[test]
    fn test_end_of_unbonding_example6_flash_resistance() {
        let day: u64 = 86_400_000;
        let vi = vi_with_periods(BTreeMap::from([(0, 30 * day), (100, 0), (101, 30 * day)]));
        assert_eq!(vi.end_of_unbonding(50), 50 + 30 * day);
    }

    /// Deactivation at exact timestamp of a period change — uses that entry.
    #[test]
    fn test_end_of_unbonding_deactivation_at_exact_entry() {
        let vi = vi_with_periods(BTreeMap::from([(0, 5), (100, 20)]));
        // Deactivation at exactly 100 → initial_period = 20 (entry at 100 is <= 100)
        assert_eq!(vi.end_of_unbonding(100), 120);
    }

    /// Deactivation before any entry — uses 0 as default.
    #[test]
    fn test_end_of_unbonding_deactivation_before_first_entry() {
        let vi = vi_with_periods(BTreeMap::from([(100, 10)]));
        // Deactivation at 50 — no entry <= 50, so period = 0
        // initial_end = 50, max_end = 50
        // Entry at 100: max_end(50) < 100 → exempt
        assert_eq!(vi.end_of_unbonding(50), 50);
    }

    /// Multiple reductions — effective_end decreases with each.
    #[test]
    fn test_end_of_unbonding_multiple_reductions() {
        let day: u64 = 86_400_000;
        let vi = vi_with_periods(BTreeMap::from([
            (0, 30 * day),
            (500, 14 * day),
            (600, 7 * day),
        ]));
        // deactivation at 200 (during 30-day phase)
        // initial_end = 200 + 30d, max_end = 200 + 30d
        // Entry at 500: apply → new_end = 200 + 14d, max_end stays 200+30d, effective = 200+14d
        // Entry at 600: apply → new_end = 200 + 7d, max_end stays, effective = 200+7d
        assert_eq!(vi.end_of_unbonding(200), 200 + 7 * day);
    }

    /// Punishment after full unbonding — must NOT extend (exempt).
    #[test]
    fn test_end_of_unbonding_punishment_after_full_unbonding() {
        let vi = vi_with_periods(BTreeMap::from([(0, 5), (200, 30)]));
        // deactivation at 100, initial_end = 105
        // Entry at 200: max_end(105) < 200 → exempt
        assert_eq!(vi.end_of_unbonding(100), 105);
    }

    /// Increasing punishment chain — each extends further.
    #[test]
    fn test_end_of_unbonding_increasing_punishments() {
        let vi = vi_with_periods(BTreeMap::from([(0, 5), (104, 10), (109, 20)]));
        // deactivation at 100, initial_end = 105
        // Entry at 104: max_end(105) >= 104 → apply. new_end = 110, max_end = 110
        // Entry at 109: max_end(110) >= 109 → apply. new_end = 120, max_end = 120
        assert_eq!(vi.end_of_unbonding(100), 120);
    }

    #[test]
    fn test_update_withdrawer_instruction() {
        let (validator_info_pubkey, current_withdrawer, new_withdrawer) = create_test_pubkeys();

        // Create the update withdrawer instruction
        let instruction = ValidatorRegistryInstruction::update_withdrawer(
            validator_info_pubkey,
            current_withdrawer,
            new_withdrawer,
        );

        // Verify the program ID
        assert_eq!(instruction.program_id, crate::id());

        // Expected accounts:
        // Note: validator_info_pubkey is a PDA and cannot sign
        let expected_accounts = vec![
            AccountMeta::new(validator_info_pubkey, false), // validator info account (PDA, writable, NOT a signer)
            AccountMeta::new_readonly(current_withdrawer, true), // current withdrawer (signer, readonly)
            AccountMeta::new_readonly(new_withdrawer, false),    // new withdrawer (readonly)
        ];

        // Verify accounts
        assert_eq!(instruction.accounts, expected_accounts);

        // Deserialize and verify instruction data
        let decoded_instruction: ValidatorRegistryInstruction =
            bincode::deserialize(&instruction.data).unwrap();

        match decoded_instruction {
            ValidatorRegistryInstruction::UpdateWithdrawer { new_withdrawal_key } => {
                assert_eq!(new_withdrawal_key, new_withdrawer);
            }
            _ => panic!("Expected UpdateWithdrawer instruction"),
        }
    }

    #[test]
    fn test_change_earliest_shutdown_instruction() {
        let validator_info_pubkey = Pubkey::new_unique();
        let signing_key = Pubkey::new_unique();
        let shutdown_ts = 1_000_000u64;

        // Test with Some(timestamp)
        let instruction = ValidatorRegistryInstruction::change_earliest_shutdown(
            validator_info_pubkey,
            signing_key,
            Some(shutdown_ts),
        );

        assert_eq!(instruction.program_id, crate::id());
        assert_eq!(instruction.accounts.len(), 2);
        assert_eq!(instruction.accounts[0].pubkey, validator_info_pubkey);
        assert!(!instruction.accounts[0].is_signer);
        assert!(instruction.accounts[0].is_writable);
        assert_eq!(instruction.accounts[1].pubkey, signing_key);
        assert!(instruction.accounts[1].is_signer);
        assert!(!instruction.accounts[1].is_writable);

        let decoded: ValidatorRegistryInstruction =
            bincode::deserialize(&instruction.data).unwrap();
        assert_eq!(
            decoded,
            ValidatorRegistryInstruction::ChangeEarliestShutdown {
                earliest_shutdown: Some(shutdown_ts),
            }
        );

        // Test with None
        let instruction_none = ValidatorRegistryInstruction::change_earliest_shutdown(
            validator_info_pubkey,
            signing_key,
            None,
        );

        let decoded_none: ValidatorRegistryInstruction =
            bincode::deserialize(&instruction_none.data).unwrap();
        assert_eq!(
            decoded_none,
            ValidatorRegistryInstruction::ChangeEarliestShutdown {
                earliest_shutdown: None,
            }
        );
    }

    #[test]
    fn test_update_signer_instruction() {
        let validator_info_pubkey = Pubkey::new_unique();
        let current_signing_key = Pubkey::new_unique();
        let new_signing_key = Pubkey::new_unique();

        let instruction = ValidatorRegistryInstruction::update_signer(
            validator_info_pubkey,
            current_signing_key,
            new_signing_key,
        );

        // Verify program ID
        assert_eq!(instruction.program_id, crate::id());

        // Verify accounts: 3 accounts expected
        assert_eq!(instruction.accounts.len(), 3);

        // Account 0: validator info PDA (writable, not signer)
        assert_eq!(instruction.accounts[0].pubkey, validator_info_pubkey);
        assert!(!instruction.accounts[0].is_signer);
        assert!(instruction.accounts[0].is_writable);

        // Account 1: current signing key (signer, not writable)
        assert_eq!(instruction.accounts[1].pubkey, current_signing_key);
        assert!(instruction.accounts[1].is_signer);
        assert!(!instruction.accounts[1].is_writable);

        // Account 2: new signing key (not signer, not writable)
        assert_eq!(instruction.accounts[2].pubkey, new_signing_key);
        assert!(!instruction.accounts[2].is_signer);
        assert!(!instruction.accounts[2].is_writable);

        // Verify instruction data deserializes correctly
        let decoded: ValidatorRegistryInstruction =
            bincode::deserialize(&instruction.data).unwrap();
        assert_eq!(
            decoded,
            ValidatorRegistryInstruction::UpdateSigner { new_signing_key },
        );
    }
}