solana_program/stake/
state.rs

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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
#![allow(clippy::arithmetic_side_effects)]
// Remove the following `allow` when `StakeState` is removed, required to avoid
// warnings from uses of deprecated types during trait derivations.
#![allow(deprecated)]

use {
    crate::{
        clock::{Clock, Epoch, UnixTimestamp},
        instruction::InstructionError,
        pubkey::Pubkey,
        stake::{
            instruction::{LockupArgs, StakeError},
            stake_flags::StakeFlags,
        },
        stake_history::{StakeHistory, StakeHistoryEntry},
    },
    borsh::{io, BorshDeserialize, BorshSchema, BorshSerialize},
    std::collections::HashSet,
};

pub type StakeActivationStatus = StakeHistoryEntry;

// means that no more than RATE of current effective stake may be added or subtracted per
// epoch
pub const DEFAULT_WARMUP_COOLDOWN_RATE: f64 = 0.25;
pub const NEW_WARMUP_COOLDOWN_RATE: f64 = 0.09;
pub const DEFAULT_SLASH_PENALTY: u8 = ((5 * std::u8::MAX as usize) / 100) as u8;

pub fn warmup_cooldown_rate(current_epoch: Epoch, new_rate_activation_epoch: Option<Epoch>) -> f64 {
    if current_epoch < new_rate_activation_epoch.unwrap_or(u64::MAX) {
        DEFAULT_WARMUP_COOLDOWN_RATE
    } else {
        NEW_WARMUP_COOLDOWN_RATE
    }
}

macro_rules! impl_borsh_stake_state {
    ($borsh:ident) => {
        impl $borsh::BorshDeserialize for StakeState {
            fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
                let enum_value: u32 = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                match enum_value {
                    0 => Ok(StakeState::Uninitialized),
                    1 => {
                        let meta: Meta = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        Ok(StakeState::Initialized(meta))
                    }
                    2 => {
                        let meta: Meta = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        let stake: Stake = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        Ok(StakeState::Stake(meta, stake))
                    }
                    3 => Ok(StakeState::RewardsPool),
                    _ => Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Invalid enum value",
                    )),
                }
            }
        }
        impl $borsh::BorshSerialize for StakeState {
            fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
                match self {
                    StakeState::Uninitialized => writer.write_all(&0u32.to_le_bytes()),
                    StakeState::Initialized(meta) => {
                        writer.write_all(&1u32.to_le_bytes())?;
                        $borsh::BorshSerialize::serialize(&meta, writer)
                    }
                    StakeState::Stake(meta, stake) => {
                        writer.write_all(&2u32.to_le_bytes())?;
                        $borsh::BorshSerialize::serialize(&meta, writer)?;
                        $borsh::BorshSerialize::serialize(&stake, writer)
                    }
                    StakeState::RewardsPool => writer.write_all(&3u32.to_le_bytes()),
                }
            }
        }
    };
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, Copy, AbiExample)]
#[allow(clippy::large_enum_variant)]
#[deprecated(
    since = "1.17.0",
    note = "Please use `StakeStateV2` instead, and match the third `StakeFlags` field when matching `StakeStateV2::Stake` to resolve any breakage. For example, `if let StakeState::Stake(meta, stake)` becomes `if let StakeStateV2::Stake(meta, stake, _stake_flags)`."
)]
pub enum StakeState {
    #[default]
    Uninitialized,
    Initialized(Meta),
    Stake(Meta, Stake),
    RewardsPool,
}
impl_borsh_stake_state!(borsh);
impl_borsh_stake_state!(borsh0_10);
impl StakeState {
    /// The fixed number of bytes used to serialize each stake account
    pub const fn size_of() -> usize {
        200 // see test_size_of
    }

    pub fn stake(&self) -> Option<Stake> {
        match self {
            StakeState::Stake(_meta, stake) => Some(*stake),
            _ => None,
        }
    }

    pub fn delegation(&self) -> Option<Delegation> {
        match self {
            StakeState::Stake(_meta, stake) => Some(stake.delegation),
            _ => None,
        }
    }

    pub fn authorized(&self) -> Option<Authorized> {
        match self {
            StakeState::Stake(meta, _stake) => Some(meta.authorized),
            StakeState::Initialized(meta) => Some(meta.authorized),
            _ => None,
        }
    }

    pub fn lockup(&self) -> Option<Lockup> {
        self.meta().map(|meta| meta.lockup)
    }

    pub fn meta(&self) -> Option<Meta> {
        match self {
            StakeState::Stake(meta, _stake) => Some(*meta),
            StakeState::Initialized(meta) => Some(*meta),
            _ => None,
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, Copy, AbiExample)]
#[allow(clippy::large_enum_variant)]
pub enum StakeStateV2 {
    #[default]
    Uninitialized,
    Initialized(Meta),
    Stake(Meta, Stake, StakeFlags),
    RewardsPool,
}
macro_rules! impl_borsh_stake_state_v2 {
    ($borsh:ident) => {
        impl $borsh::BorshDeserialize for StakeStateV2 {
            fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
                let enum_value: u32 = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                match enum_value {
                    0 => Ok(StakeStateV2::Uninitialized),
                    1 => {
                        let meta: Meta = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        Ok(StakeStateV2::Initialized(meta))
                    }
                    2 => {
                        let meta: Meta = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        let stake: Stake = $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        let stake_flags: StakeFlags =
                            $borsh::BorshDeserialize::deserialize_reader(reader)?;
                        Ok(StakeStateV2::Stake(meta, stake, stake_flags))
                    }
                    3 => Ok(StakeStateV2::RewardsPool),
                    _ => Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Invalid enum value",
                    )),
                }
            }
        }
        impl $borsh::BorshSerialize for StakeStateV2 {
            fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
                match self {
                    StakeStateV2::Uninitialized => writer.write_all(&0u32.to_le_bytes()),
                    StakeStateV2::Initialized(meta) => {
                        writer.write_all(&1u32.to_le_bytes())?;
                        $borsh::BorshSerialize::serialize(&meta, writer)
                    }
                    StakeStateV2::Stake(meta, stake, stake_flags) => {
                        writer.write_all(&2u32.to_le_bytes())?;
                        $borsh::BorshSerialize::serialize(&meta, writer)?;
                        $borsh::BorshSerialize::serialize(&stake, writer)?;
                        $borsh::BorshSerialize::serialize(&stake_flags, writer)
                    }
                    StakeStateV2::RewardsPool => writer.write_all(&3u32.to_le_bytes()),
                }
            }
        }
    };
}
impl_borsh_stake_state_v2!(borsh);
impl_borsh_stake_state_v2!(borsh0_10);

impl StakeStateV2 {
    /// The fixed number of bytes used to serialize each stake account
    pub const fn size_of() -> usize {
        200 // see test_size_of
    }

    pub fn stake(&self) -> Option<Stake> {
        match self {
            StakeStateV2::Stake(_meta, stake, _stake_flags) => Some(*stake),
            _ => None,
        }
    }

    pub fn delegation(&self) -> Option<Delegation> {
        match self {
            StakeStateV2::Stake(_meta, stake, _stake_flags) => Some(stake.delegation),
            _ => None,
        }
    }

    pub fn authorized(&self) -> Option<Authorized> {
        match self {
            StakeStateV2::Stake(meta, _stake, _stake_flags) => Some(meta.authorized),
            StakeStateV2::Initialized(meta) => Some(meta.authorized),
            _ => None,
        }
    }

    pub fn lockup(&self) -> Option<Lockup> {
        self.meta().map(|meta| meta.lockup)
    }

    pub fn meta(&self) -> Option<Meta> {
        match self {
            StakeStateV2::Stake(meta, _stake, _stake_flags) => Some(*meta),
            StakeStateV2::Initialized(meta) => Some(*meta),
            _ => None,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Copy, AbiExample)]
pub enum StakeAuthorize {
    Staker,
    Withdrawer,
}

#[derive(
    Default,
    Debug,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    Clone,
    Copy,
    AbiExample,
    BorshDeserialize,
    BorshSchema,
    BorshSerialize,
)]
#[borsh(crate = "borsh")]
pub struct Lockup {
    /// UnixTimestamp at which this stake will allow withdrawal, unless the
    ///   transaction is signed by the custodian
    pub unix_timestamp: UnixTimestamp,
    /// epoch height at which this stake will allow withdrawal, unless the
    ///   transaction is signed by the custodian
    pub epoch: Epoch,
    /// custodian signature on a transaction exempts the operation from
    ///  lockup constraints
    pub custodian: Pubkey,
}
impl Lockup {
    pub fn is_in_force(&self, clock: &Clock, custodian: Option<&Pubkey>) -> bool {
        if custodian == Some(&self.custodian) {
            return false;
        }
        self.unix_timestamp > clock.unix_timestamp || self.epoch > clock.epoch
    }
}
impl borsh0_10::de::BorshDeserialize for Lockup {
    fn deserialize_reader<R: borsh0_10::maybestd::io::Read>(
        reader: &mut R,
    ) -> ::core::result::Result<Self, borsh0_10::maybestd::io::Error> {
        Ok(Self {
            unix_timestamp: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            epoch: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            custodian: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
        })
    }
}
impl borsh0_10::BorshSchema for Lockup {
    fn declaration() -> borsh0_10::schema::Declaration {
        "Lockup".to_string()
    }
    fn add_definitions_recursively(
        definitions: &mut borsh0_10::maybestd::collections::HashMap<
            borsh0_10::schema::Declaration,
            borsh0_10::schema::Definition,
        >,
    ) {
        let fields = borsh0_10::schema::Fields::NamedFields(<[_]>::into_vec(
            borsh0_10::maybestd::boxed::Box::new([
                (
                    "unix_timestamp".to_string(),
                    <UnixTimestamp as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "epoch".to_string(),
                    <Epoch as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "custodian".to_string(),
                    <Pubkey as borsh0_10::BorshSchema>::declaration(),
                ),
            ]),
        ));
        let definition = borsh0_10::schema::Definition::Struct { fields };
        Self::add_definition(
            <Self as borsh0_10::BorshSchema>::declaration(),
            definition,
            definitions,
        );
        <UnixTimestamp as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Epoch as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Pubkey as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
    }
}
impl borsh0_10::ser::BorshSerialize for Lockup {
    fn serialize<W: borsh0_10::maybestd::io::Write>(
        &self,
        writer: &mut W,
    ) -> ::core::result::Result<(), borsh0_10::maybestd::io::Error> {
        borsh0_10::BorshSerialize::serialize(&self.unix_timestamp, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.epoch, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.custodian, writer)?;
        Ok(())
    }
}

#[derive(
    Default,
    Debug,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    Clone,
    Copy,
    AbiExample,
    BorshDeserialize,
    BorshSchema,
    BorshSerialize,
)]
#[borsh(crate = "borsh")]
pub struct Authorized {
    pub staker: Pubkey,
    pub withdrawer: Pubkey,
}

impl Authorized {
    pub fn auto(authorized: &Pubkey) -> Self {
        Self {
            staker: *authorized,
            withdrawer: *authorized,
        }
    }
    pub fn check(
        &self,
        signers: &HashSet<Pubkey>,
        stake_authorize: StakeAuthorize,
    ) -> Result<(), InstructionError> {
        match stake_authorize {
            StakeAuthorize::Staker if signers.contains(&self.staker) => Ok(()),
            StakeAuthorize::Withdrawer if signers.contains(&self.withdrawer) => Ok(()),
            _ => Err(InstructionError::MissingRequiredSignature),
        }
    }

    pub fn authorize(
        &mut self,
        signers: &HashSet<Pubkey>,
        new_authorized: &Pubkey,
        stake_authorize: StakeAuthorize,
        lockup_custodian_args: Option<(&Lockup, &Clock, Option<&Pubkey>)>,
    ) -> Result<(), InstructionError> {
        match stake_authorize {
            StakeAuthorize::Staker => {
                // Allow either the staker or the withdrawer to change the staker key
                if !signers.contains(&self.staker) && !signers.contains(&self.withdrawer) {
                    return Err(InstructionError::MissingRequiredSignature);
                }
                self.staker = *new_authorized
            }
            StakeAuthorize::Withdrawer => {
                if let Some((lockup, clock, custodian)) = lockup_custodian_args {
                    if lockup.is_in_force(clock, None) {
                        match custodian {
                            None => {
                                return Err(StakeError::CustodianMissing.into());
                            }
                            Some(custodian) => {
                                if !signers.contains(custodian) {
                                    return Err(StakeError::CustodianSignatureMissing.into());
                                }

                                if lockup.is_in_force(clock, Some(custodian)) {
                                    return Err(StakeError::LockupInForce.into());
                                }
                            }
                        }
                    }
                }
                self.check(signers, stake_authorize)?;
                self.withdrawer = *new_authorized
            }
        }
        Ok(())
    }
}
impl borsh0_10::de::BorshDeserialize for Authorized {
    fn deserialize_reader<R: borsh0_10::maybestd::io::Read>(
        reader: &mut R,
    ) -> ::core::result::Result<Self, borsh0_10::maybestd::io::Error> {
        Ok(Self {
            staker: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            withdrawer: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
        })
    }
}
impl borsh0_10::BorshSchema for Authorized {
    fn declaration() -> borsh0_10::schema::Declaration {
        "Authorized".to_string()
    }
    fn add_definitions_recursively(
        definitions: &mut borsh0_10::maybestd::collections::HashMap<
            borsh0_10::schema::Declaration,
            borsh0_10::schema::Definition,
        >,
    ) {
        let fields = borsh0_10::schema::Fields::NamedFields(<[_]>::into_vec(
            borsh0_10::maybestd::boxed::Box::new([
                (
                    "staker".to_string(),
                    <Pubkey as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "withdrawer".to_string(),
                    <Pubkey as borsh0_10::BorshSchema>::declaration(),
                ),
            ]),
        ));
        let definition = borsh0_10::schema::Definition::Struct { fields };
        Self::add_definition(
            <Self as borsh0_10::BorshSchema>::declaration(),
            definition,
            definitions,
        );
        <Pubkey as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Pubkey as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
    }
}
impl borsh0_10::ser::BorshSerialize for Authorized {
    fn serialize<W: borsh0_10::maybestd::io::Write>(
        &self,
        writer: &mut W,
    ) -> ::core::result::Result<(), borsh0_10::maybestd::io::Error> {
        borsh0_10::BorshSerialize::serialize(&self.staker, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.withdrawer, writer)?;
        Ok(())
    }
}

#[derive(
    Default,
    Debug,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    Clone,
    Copy,
    AbiExample,
    BorshDeserialize,
    BorshSchema,
    BorshSerialize,
)]
#[borsh(crate = "borsh")]
pub struct Meta {
    pub rent_exempt_reserve: u64,
    pub authorized: Authorized,
    pub lockup: Lockup,
}

impl Meta {
    pub fn set_lockup(
        &mut self,
        lockup: &LockupArgs,
        signers: &HashSet<Pubkey>,
        clock: &Clock,
    ) -> Result<(), InstructionError> {
        // post-stake_program_v4 behavior:
        // * custodian can update the lockup while in force
        // * withdraw authority can set a new lockup
        if self.lockup.is_in_force(clock, None) {
            if !signers.contains(&self.lockup.custodian) {
                return Err(InstructionError::MissingRequiredSignature);
            }
        } else if !signers.contains(&self.authorized.withdrawer) {
            return Err(InstructionError::MissingRequiredSignature);
        }
        if let Some(unix_timestamp) = lockup.unix_timestamp {
            self.lockup.unix_timestamp = unix_timestamp;
        }
        if let Some(epoch) = lockup.epoch {
            self.lockup.epoch = epoch;
        }
        if let Some(custodian) = lockup.custodian {
            self.lockup.custodian = custodian;
        }
        Ok(())
    }

    pub fn auto(authorized: &Pubkey) -> Self {
        Self {
            authorized: Authorized::auto(authorized),
            ..Meta::default()
        }
    }
}
impl borsh0_10::de::BorshDeserialize for Meta {
    fn deserialize_reader<R: borsh0_10::maybestd::io::Read>(
        reader: &mut R,
    ) -> ::core::result::Result<Self, borsh0_10::maybestd::io::Error> {
        Ok(Self {
            rent_exempt_reserve: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            authorized: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            lockup: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
        })
    }
}
impl borsh0_10::BorshSchema for Meta {
    fn declaration() -> borsh0_10::schema::Declaration {
        "Meta".to_string()
    }
    fn add_definitions_recursively(
        definitions: &mut borsh0_10::maybestd::collections::HashMap<
            borsh0_10::schema::Declaration,
            borsh0_10::schema::Definition,
        >,
    ) {
        let fields = borsh0_10::schema::Fields::NamedFields(<[_]>::into_vec(
            borsh0_10::maybestd::boxed::Box::new([
                (
                    "rent_exempt_reserve".to_string(),
                    <u64 as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "authorized".to_string(),
                    <Authorized as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "lockup".to_string(),
                    <Lockup as borsh0_10::BorshSchema>::declaration(),
                ),
            ]),
        ));
        let definition = borsh0_10::schema::Definition::Struct { fields };
        Self::add_definition(
            <Self as borsh0_10::BorshSchema>::declaration(),
            definition,
            definitions,
        );
        <u64 as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Authorized as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Lockup as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
    }
}
impl borsh0_10::ser::BorshSerialize for Meta {
    fn serialize<W: borsh0_10::maybestd::io::Write>(
        &self,
        writer: &mut W,
    ) -> ::core::result::Result<(), borsh0_10::maybestd::io::Error> {
        borsh0_10::BorshSerialize::serialize(&self.rent_exempt_reserve, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.authorized, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.lockup, writer)?;
        Ok(())
    }
}

#[derive(
    Debug,
    Serialize,
    Deserialize,
    PartialEq,
    Clone,
    Copy,
    AbiExample,
    BorshDeserialize,
    BorshSchema,
    BorshSerialize,
)]
#[borsh(crate = "borsh")]
pub struct Delegation {
    /// to whom the stake is delegated
    pub voter_pubkey: Pubkey,
    /// activated stake amount, set at delegate() time
    pub stake: u64,
    /// epoch at which this stake was activated, std::Epoch::MAX if is a bootstrap stake
    pub activation_epoch: Epoch,
    /// epoch the stake was deactivated, std::Epoch::MAX if not deactivated
    pub deactivation_epoch: Epoch,
    /// how much stake we can activate per-epoch as a fraction of currently effective stake
    #[deprecated(
        since = "1.16.7",
        note = "Please use `solana_sdk::stake::state::warmup_cooldown_rate()` instead"
    )]
    pub warmup_cooldown_rate: f64,
}

impl Default for Delegation {
    fn default() -> Self {
        #[allow(deprecated)]
        Self {
            voter_pubkey: Pubkey::default(),
            stake: 0,
            activation_epoch: 0,
            deactivation_epoch: std::u64::MAX,
            warmup_cooldown_rate: DEFAULT_WARMUP_COOLDOWN_RATE,
        }
    }
}

impl Delegation {
    pub fn new(voter_pubkey: &Pubkey, stake: u64, activation_epoch: Epoch) -> Self {
        Self {
            voter_pubkey: *voter_pubkey,
            stake,
            activation_epoch,
            ..Delegation::default()
        }
    }
    pub fn is_bootstrap(&self) -> bool {
        self.activation_epoch == std::u64::MAX
    }

    pub fn stake(
        &self,
        epoch: Epoch,
        history: &StakeHistory,
        new_rate_activation_epoch: Option<Epoch>,
    ) -> u64 {
        self.stake_activating_and_deactivating(epoch, history, new_rate_activation_epoch)
            .effective
    }

    #[allow(clippy::comparison_chain)]
    pub fn stake_activating_and_deactivating(
        &self,
        target_epoch: Epoch,
        history: &StakeHistory,
        new_rate_activation_epoch: Option<Epoch>,
    ) -> StakeActivationStatus {
        // first, calculate an effective and activating stake
        let (effective_stake, activating_stake) =
            self.stake_and_activating(target_epoch, history, new_rate_activation_epoch);

        // then de-activate some portion if necessary
        if target_epoch < self.deactivation_epoch {
            // not deactivated
            if activating_stake == 0 {
                StakeActivationStatus::with_effective(effective_stake)
            } else {
                StakeActivationStatus::with_effective_and_activating(
                    effective_stake,
                    activating_stake,
                )
            }
        } else if target_epoch == self.deactivation_epoch {
            // can only deactivate what's activated
            StakeActivationStatus::with_deactivating(effective_stake)
        } else if let Some((history, mut prev_epoch, mut prev_cluster_stake)) = history
            .get(self.deactivation_epoch)
            .map(|cluster_stake_at_deactivation_epoch| {
                (
                    history,
                    self.deactivation_epoch,
                    cluster_stake_at_deactivation_epoch,
                )
            })
        {
            // target_epoch > self.deactivation_epoch

            // loop from my deactivation epoch until the target epoch
            // current effective stake is updated using its previous epoch's cluster stake
            let mut current_epoch;
            let mut current_effective_stake = effective_stake;
            loop {
                current_epoch = prev_epoch + 1;
                // if there is no deactivating stake at prev epoch, we should have been
                // fully undelegated at this moment
                if prev_cluster_stake.deactivating == 0 {
                    break;
                }

                // I'm trying to get to zero, how much of the deactivation in stake
                //   this account is entitled to take
                let weight =
                    current_effective_stake as f64 / prev_cluster_stake.deactivating as f64;
                let warmup_cooldown_rate =
                    warmup_cooldown_rate(current_epoch, new_rate_activation_epoch);

                // portion of newly not-effective cluster stake I'm entitled to at current epoch
                let newly_not_effective_cluster_stake =
                    prev_cluster_stake.effective as f64 * warmup_cooldown_rate;
                let newly_not_effective_stake =
                    ((weight * newly_not_effective_cluster_stake) as u64).max(1);

                current_effective_stake =
                    current_effective_stake.saturating_sub(newly_not_effective_stake);
                if current_effective_stake == 0 {
                    break;
                }

                if current_epoch >= target_epoch {
                    break;
                }
                if let Some(current_cluster_stake) = history.get(current_epoch) {
                    prev_epoch = current_epoch;
                    prev_cluster_stake = current_cluster_stake;
                } else {
                    break;
                }
            }

            // deactivating stake should equal to all of currently remaining effective stake
            StakeActivationStatus::with_deactivating(current_effective_stake)
        } else {
            // no history or I've dropped out of history, so assume fully deactivated
            StakeActivationStatus::default()
        }
    }

    // returned tuple is (effective, activating) stake
    fn stake_and_activating(
        &self,
        target_epoch: Epoch,
        history: &StakeHistory,
        new_rate_activation_epoch: Option<Epoch>,
    ) -> (u64, u64) {
        let delegated_stake = self.stake;

        if self.is_bootstrap() {
            // fully effective immediately
            (delegated_stake, 0)
        } else if self.activation_epoch == self.deactivation_epoch {
            // activated but instantly deactivated; no stake at all regardless of target_epoch
            // this must be after the bootstrap check and before all-is-activating check
            (0, 0)
        } else if target_epoch == self.activation_epoch {
            // all is activating
            (0, delegated_stake)
        } else if target_epoch < self.activation_epoch {
            // not yet enabled
            (0, 0)
        } else if let Some((history, mut prev_epoch, mut prev_cluster_stake)) = history
            .get(self.activation_epoch)
            .map(|cluster_stake_at_activation_epoch| {
                (
                    history,
                    self.activation_epoch,
                    cluster_stake_at_activation_epoch,
                )
            })
        {
            // target_epoch > self.activation_epoch

            // loop from my activation epoch until the target epoch summing up my entitlement
            // current effective stake is updated using its previous epoch's cluster stake
            let mut current_epoch;
            let mut current_effective_stake = 0;
            loop {
                current_epoch = prev_epoch + 1;
                // if there is no activating stake at prev epoch, we should have been
                // fully effective at this moment
                if prev_cluster_stake.activating == 0 {
                    break;
                }

                // how much of the growth in stake this account is
                //  entitled to take
                let remaining_activating_stake = delegated_stake - current_effective_stake;
                let weight =
                    remaining_activating_stake as f64 / prev_cluster_stake.activating as f64;
                let warmup_cooldown_rate =
                    warmup_cooldown_rate(current_epoch, new_rate_activation_epoch);

                // portion of newly effective cluster stake I'm entitled to at current epoch
                let newly_effective_cluster_stake =
                    prev_cluster_stake.effective as f64 * warmup_cooldown_rate;
                let newly_effective_stake =
                    ((weight * newly_effective_cluster_stake) as u64).max(1);

                current_effective_stake += newly_effective_stake;
                if current_effective_stake >= delegated_stake {
                    current_effective_stake = delegated_stake;
                    break;
                }

                if current_epoch >= target_epoch || current_epoch >= self.deactivation_epoch {
                    break;
                }
                if let Some(current_cluster_stake) = history.get(current_epoch) {
                    prev_epoch = current_epoch;
                    prev_cluster_stake = current_cluster_stake;
                } else {
                    break;
                }
            }

            (
                current_effective_stake,
                delegated_stake - current_effective_stake,
            )
        } else {
            // no history or I've dropped out of history, so assume fully effective
            (delegated_stake, 0)
        }
    }
}
impl borsh0_10::de::BorshDeserialize for Delegation {
    fn deserialize_reader<R: borsh0_10::maybestd::io::Read>(
        reader: &mut R,
    ) -> ::core::result::Result<Self, borsh0_10::maybestd::io::Error> {
        Ok(Self {
            voter_pubkey: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            stake: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            activation_epoch: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            deactivation_epoch: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            warmup_cooldown_rate: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
        })
    }
}
impl borsh0_10::BorshSchema for Delegation {
    fn declaration() -> borsh0_10::schema::Declaration {
        "Delegation".to_string()
    }
    fn add_definitions_recursively(
        definitions: &mut borsh0_10::maybestd::collections::HashMap<
            borsh0_10::schema::Declaration,
            borsh0_10::schema::Definition,
        >,
    ) {
        let fields = borsh0_10::schema::Fields::NamedFields(<[_]>::into_vec(
            borsh0_10::maybestd::boxed::Box::new([
                (
                    "voter_pubkey".to_string(),
                    <Pubkey as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "stake".to_string(),
                    <u64 as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "activation_epoch".to_string(),
                    <Epoch as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "deactivation_epoch".to_string(),
                    <Epoch as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "warmup_cooldown_rate".to_string(),
                    <f64 as borsh0_10::BorshSchema>::declaration(),
                ),
            ]),
        ));
        let definition = borsh0_10::schema::Definition::Struct { fields };
        Self::add_definition(
            <Self as borsh0_10::BorshSchema>::declaration(),
            definition,
            definitions,
        );
        <Pubkey as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <u64 as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Epoch as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <Epoch as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <f64 as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
    }
}
impl borsh0_10::ser::BorshSerialize for Delegation {
    fn serialize<W: borsh0_10::maybestd::io::Write>(
        &self,
        writer: &mut W,
    ) -> ::core::result::Result<(), borsh0_10::maybestd::io::Error> {
        borsh0_10::BorshSerialize::serialize(&self.voter_pubkey, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.stake, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.activation_epoch, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.deactivation_epoch, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.warmup_cooldown_rate, writer)?;
        Ok(())
    }
}

#[derive(
    Debug,
    Default,
    Serialize,
    Deserialize,
    PartialEq,
    Clone,
    Copy,
    AbiExample,
    BorshDeserialize,
    BorshSchema,
    BorshSerialize,
)]
#[borsh(crate = "borsh")]
pub struct Stake {
    pub delegation: Delegation,
    /// credits observed is credits from vote account state when delegated or redeemed
    pub credits_observed: u64,
}

impl Stake {
    pub fn stake(
        &self,
        epoch: Epoch,
        history: &StakeHistory,
        new_rate_activation_epoch: Option<Epoch>,
    ) -> u64 {
        self.delegation
            .stake(epoch, history, new_rate_activation_epoch)
    }

    pub fn split(
        &mut self,
        remaining_stake_delta: u64,
        split_stake_amount: u64,
    ) -> Result<Self, StakeError> {
        if remaining_stake_delta > self.delegation.stake {
            return Err(StakeError::InsufficientStake);
        }
        self.delegation.stake -= remaining_stake_delta;
        let new = Self {
            delegation: Delegation {
                stake: split_stake_amount,
                ..self.delegation
            },
            ..*self
        };
        Ok(new)
    }

    pub fn deactivate(&mut self, epoch: Epoch) -> Result<(), StakeError> {
        if self.delegation.deactivation_epoch != std::u64::MAX {
            Err(StakeError::AlreadyDeactivated)
        } else {
            self.delegation.deactivation_epoch = epoch;
            Ok(())
        }
    }
}
impl borsh0_10::de::BorshDeserialize for Stake {
    fn deserialize_reader<R: borsh0_10::maybestd::io::Read>(
        reader: &mut R,
    ) -> ::core::result::Result<Self, borsh0_10::maybestd::io::Error> {
        Ok(Self {
            delegation: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
            credits_observed: borsh0_10::BorshDeserialize::deserialize_reader(reader)?,
        })
    }
}
impl borsh0_10::BorshSchema for Stake {
    fn declaration() -> borsh0_10::schema::Declaration {
        "Stake".to_string()
    }
    fn add_definitions_recursively(
        definitions: &mut borsh0_10::maybestd::collections::HashMap<
            borsh0_10::schema::Declaration,
            borsh0_10::schema::Definition,
        >,
    ) {
        let fields = borsh0_10::schema::Fields::NamedFields(<[_]>::into_vec(
            borsh0_10::maybestd::boxed::Box::new([
                (
                    "delegation".to_string(),
                    <Delegation as borsh0_10::BorshSchema>::declaration(),
                ),
                (
                    "credits_observed".to_string(),
                    <u64 as borsh0_10::BorshSchema>::declaration(),
                ),
            ]),
        ));
        let definition = borsh0_10::schema::Definition::Struct { fields };
        Self::add_definition(
            <Self as borsh0_10::BorshSchema>::declaration(),
            definition,
            definitions,
        );
        <Delegation as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
        <u64 as borsh0_10::BorshSchema>::add_definitions_recursively(definitions);
    }
}
impl borsh0_10::ser::BorshSerialize for Stake {
    fn serialize<W: borsh0_10::maybestd::io::Write>(
        &self,
        writer: &mut W,
    ) -> ::core::result::Result<(), borsh0_10::maybestd::io::Error> {
        borsh0_10::BorshSerialize::serialize(&self.delegation, writer)?;
        borsh0_10::BorshSerialize::serialize(&self.credits_observed, writer)?;
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use {
        super::*, crate::borsh1::try_from_slice_unchecked, assert_matches::assert_matches,
        bincode::serialize,
    };

    fn check_borsh_deserialization(stake: StakeStateV2) {
        let serialized = serialize(&stake).unwrap();
        let deserialized = StakeStateV2::try_from_slice(&serialized).unwrap();
        assert_eq!(stake, deserialized);
    }

    fn check_borsh_serialization(stake: StakeStateV2) {
        let bincode_serialized = serialize(&stake).unwrap();
        let borsh_serialized = borsh::to_vec(&stake).unwrap();
        assert_eq!(bincode_serialized, borsh_serialized);
    }

    #[test]
    fn test_size_of() {
        assert_eq!(StakeStateV2::size_of(), std::mem::size_of::<StakeStateV2>());
    }

    #[test]
    fn bincode_vs_borsh_deserialization() {
        check_borsh_deserialization(StakeStateV2::Uninitialized);
        check_borsh_deserialization(StakeStateV2::RewardsPool);
        check_borsh_deserialization(StakeStateV2::Initialized(Meta {
            rent_exempt_reserve: u64::MAX,
            authorized: Authorized {
                staker: Pubkey::new_unique(),
                withdrawer: Pubkey::new_unique(),
            },
            lockup: Lockup::default(),
        }));
        check_borsh_deserialization(StakeStateV2::Stake(
            Meta {
                rent_exempt_reserve: 1,
                authorized: Authorized {
                    staker: Pubkey::new_unique(),
                    withdrawer: Pubkey::new_unique(),
                },
                lockup: Lockup::default(),
            },
            Stake {
                delegation: Delegation {
                    voter_pubkey: Pubkey::new_unique(),
                    stake: u64::MAX,
                    activation_epoch: Epoch::MAX,
                    deactivation_epoch: Epoch::MAX,
                    ..Delegation::default()
                },
                credits_observed: 1,
            },
            StakeFlags::empty(),
        ));
    }

    #[test]
    fn bincode_vs_borsh_serialization() {
        check_borsh_serialization(StakeStateV2::Uninitialized);
        check_borsh_serialization(StakeStateV2::RewardsPool);
        check_borsh_serialization(StakeStateV2::Initialized(Meta {
            rent_exempt_reserve: u64::MAX,
            authorized: Authorized {
                staker: Pubkey::new_unique(),
                withdrawer: Pubkey::new_unique(),
            },
            lockup: Lockup::default(),
        }));
        check_borsh_serialization(StakeStateV2::Stake(
            Meta {
                rent_exempt_reserve: 1,
                authorized: Authorized {
                    staker: Pubkey::new_unique(),
                    withdrawer: Pubkey::new_unique(),
                },
                lockup: Lockup::default(),
            },
            Stake {
                delegation: Delegation {
                    voter_pubkey: Pubkey::new_unique(),
                    stake: u64::MAX,
                    activation_epoch: Epoch::MAX,
                    deactivation_epoch: Epoch::MAX,
                    ..Default::default()
                },
                credits_observed: 1,
            },
            StakeFlags::MUST_FULLY_ACTIVATE_BEFORE_DEACTIVATION_IS_PERMITTED,
        ));
    }

    #[test]
    fn borsh_deserialization_live_data() {
        let data = [
            1, 0, 0, 0, 128, 213, 34, 0, 0, 0, 0, 0, 133, 0, 79, 231, 141, 29, 73, 61, 232, 35,
            119, 124, 168, 12, 120, 216, 195, 29, 12, 166, 139, 28, 36, 182, 186, 154, 246, 149,
            224, 109, 52, 100, 133, 0, 79, 231, 141, 29, 73, 61, 232, 35, 119, 124, 168, 12, 120,
            216, 195, 29, 12, 166, 139, 28, 36, 182, 186, 154, 246, 149, 224, 109, 52, 100, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0,
        ];
        // As long as we get the 4-byte enum and the first field right, then
        // we're sure the rest works out
        let deserialized = try_from_slice_unchecked::<StakeStateV2>(&data).unwrap();
        assert_matches!(
            deserialized,
            StakeStateV2::Initialized(Meta {
                rent_exempt_reserve: 2282880,
                ..
            })
        );
    }

    #[test]
    fn stake_flag_member_offset() {
        const FLAG_OFFSET: usize = 196;
        let check_flag = |flag, expected| {
            let stake = StakeStateV2::Stake(
                Meta {
                    rent_exempt_reserve: 1,
                    authorized: Authorized {
                        staker: Pubkey::new_unique(),
                        withdrawer: Pubkey::new_unique(),
                    },
                    lockup: Lockup::default(),
                },
                Stake {
                    delegation: Delegation {
                        voter_pubkey: Pubkey::new_unique(),
                        stake: u64::MAX,
                        activation_epoch: Epoch::MAX,
                        deactivation_epoch: Epoch::MAX,
                        warmup_cooldown_rate: f64::MAX,
                    },
                    credits_observed: 1,
                },
                flag,
            );

            let bincode_serialized = serialize(&stake).unwrap();
            let borsh_serialized = borsh::to_vec(&stake).unwrap();

            assert_eq!(bincode_serialized[FLAG_OFFSET], expected);
            assert_eq!(borsh_serialized[FLAG_OFFSET], expected);
        };
        check_flag(
            StakeFlags::MUST_FULLY_ACTIVATE_BEFORE_DEACTIVATION_IS_PERMITTED,
            1,
        );
        check_flag(StakeFlags::empty(), 0);
    }

    mod deprecated {
        use super::*;
        fn check_borsh_deserialization(stake: StakeState) {
            let serialized = serialize(&stake).unwrap();
            let deserialized = StakeState::try_from_slice(&serialized).unwrap();
            assert_eq!(stake, deserialized);
        }

        fn check_borsh_serialization(stake: StakeState) {
            let bincode_serialized = serialize(&stake).unwrap();
            let borsh_serialized = borsh::to_vec(&stake).unwrap();
            assert_eq!(bincode_serialized, borsh_serialized);
        }

        #[test]
        fn test_size_of() {
            assert_eq!(StakeState::size_of(), std::mem::size_of::<StakeState>());
        }

        #[test]
        fn bincode_vs_borsh_deserialization() {
            check_borsh_deserialization(StakeState::Uninitialized);
            check_borsh_deserialization(StakeState::RewardsPool);
            check_borsh_deserialization(StakeState::Initialized(Meta {
                rent_exempt_reserve: u64::MAX,
                authorized: Authorized {
                    staker: Pubkey::new_unique(),
                    withdrawer: Pubkey::new_unique(),
                },
                lockup: Lockup::default(),
            }));
            check_borsh_deserialization(StakeState::Stake(
                Meta {
                    rent_exempt_reserve: 1,
                    authorized: Authorized {
                        staker: Pubkey::new_unique(),
                        withdrawer: Pubkey::new_unique(),
                    },
                    lockup: Lockup::default(),
                },
                Stake {
                    delegation: Delegation {
                        voter_pubkey: Pubkey::new_unique(),
                        stake: u64::MAX,
                        activation_epoch: Epoch::MAX,
                        deactivation_epoch: Epoch::MAX,
                        warmup_cooldown_rate: f64::MAX,
                    },
                    credits_observed: 1,
                },
            ));
        }

        #[test]
        fn bincode_vs_borsh_serialization() {
            check_borsh_serialization(StakeState::Uninitialized);
            check_borsh_serialization(StakeState::RewardsPool);
            check_borsh_serialization(StakeState::Initialized(Meta {
                rent_exempt_reserve: u64::MAX,
                authorized: Authorized {
                    staker: Pubkey::new_unique(),
                    withdrawer: Pubkey::new_unique(),
                },
                lockup: Lockup::default(),
            }));
            check_borsh_serialization(StakeState::Stake(
                Meta {
                    rent_exempt_reserve: 1,
                    authorized: Authorized {
                        staker: Pubkey::new_unique(),
                        withdrawer: Pubkey::new_unique(),
                    },
                    lockup: Lockup::default(),
                },
                Stake {
                    delegation: Delegation {
                        voter_pubkey: Pubkey::new_unique(),
                        stake: u64::MAX,
                        activation_epoch: Epoch::MAX,
                        deactivation_epoch: Epoch::MAX,
                        warmup_cooldown_rate: f64::MAX,
                    },
                    credits_observed: 1,
                },
            ));
        }

        #[test]
        fn borsh_deserialization_live_data() {
            let data = [
                1, 0, 0, 0, 128, 213, 34, 0, 0, 0, 0, 0, 133, 0, 79, 231, 141, 29, 73, 61, 232, 35,
                119, 124, 168, 12, 120, 216, 195, 29, 12, 166, 139, 28, 36, 182, 186, 154, 246,
                149, 224, 109, 52, 100, 133, 0, 79, 231, 141, 29, 73, 61, 232, 35, 119, 124, 168,
                12, 120, 216, 195, 29, 12, 166, 139, 28, 36, 182, 186, 154, 246, 149, 224, 109, 52,
                100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            ];
            // As long as we get the 4-byte enum and the first field right, then
            // we're sure the rest works out
            let deserialized = try_from_slice_unchecked::<StakeState>(&data).unwrap();
            assert_matches!(
                deserialized,
                StakeState::Initialized(Meta {
                    rent_exempt_reserve: 2282880,
                    ..
                })
            );
        }
    }
}