forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 81
/
stake_state.rs
2885 lines (2673 loc) · 103 KB
/
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
//! Stake state
//! * delegate stakes to vote accounts
//! * keep track of rewards
//! * own mining pools
#[deprecated(
since = "1.8.0",
note = "Please use `solana_sdk::stake::state` or `solana_program::stake::state` instead"
)]
pub use solana_sdk::stake::state::*;
use {
solana_program_runtime::{ic_msg, invoke_context::InvokeContext},
solana_sdk::{
account::{AccountSharedData, ReadableAccount},
account_utils::StateMut,
clock::{Clock, Epoch},
feature_set::{self, FeatureSet},
instruction::{checked_add, InstructionError},
pubkey::Pubkey,
rent::Rent,
stake::{
instruction::{LockupArgs, StakeError},
program::id,
stake_flags::StakeFlags,
tools::{acceptable_reference_epoch_credits, eligible_for_deactivate_delinquent},
},
stake_history::{StakeHistory, StakeHistoryEntry},
transaction_context::{
BorrowedAccount, IndexOfAccount, InstructionContext, TransactionContext,
},
},
solana_vote_program::vote_state::{self, VoteState, VoteStateVersions},
std::{collections::HashSet, convert::TryFrom},
};
// utility function, used by Stakes, tests
pub fn from<T: ReadableAccount + StateMut<StakeStateV2>>(account: &T) -> Option<StakeStateV2> {
account.state().ok()
}
pub fn stake_from<T: ReadableAccount + StateMut<StakeStateV2>>(account: &T) -> Option<Stake> {
from(account).and_then(|state: StakeStateV2| state.stake())
}
pub fn delegation_from(account: &AccountSharedData) -> Option<Delegation> {
from(account).and_then(|state: StakeStateV2| state.delegation())
}
pub fn authorized_from(account: &AccountSharedData) -> Option<Authorized> {
from(account).and_then(|state: StakeStateV2| state.authorized())
}
pub fn lockup_from<T: ReadableAccount + StateMut<StakeStateV2>>(account: &T) -> Option<Lockup> {
from(account).and_then(|state: StakeStateV2| state.lockup())
}
pub fn meta_from(account: &AccountSharedData) -> Option<Meta> {
from(account).and_then(|state: StakeStateV2| state.meta())
}
pub(crate) fn new_warmup_cooldown_rate_epoch(invoke_context: &InvokeContext) -> Option<Epoch> {
let epoch_schedule = invoke_context
.get_sysvar_cache()
.get_epoch_schedule()
.unwrap();
invoke_context
.feature_set
.new_warmup_cooldown_rate_epoch(epoch_schedule.as_ref())
}
fn get_stake_status(
invoke_context: &InvokeContext,
stake: &Stake,
clock: &Clock,
) -> Result<StakeActivationStatus, InstructionError> {
let stake_history = invoke_context.get_sysvar_cache().get_stake_history()?;
Ok(stake.delegation.stake_activating_and_deactivating(
clock.epoch,
&stake_history,
new_warmup_cooldown_rate_epoch(invoke_context),
))
}
fn redelegate_stake(
invoke_context: &InvokeContext,
stake: &mut Stake,
stake_lamports: u64,
voter_pubkey: &Pubkey,
vote_state: &VoteState,
clock: &Clock,
stake_history: &StakeHistory,
) -> Result<(), StakeError> {
let new_rate_activation_epoch = new_warmup_cooldown_rate_epoch(invoke_context);
// If stake is currently active:
if stake.stake(clock.epoch, stake_history, new_rate_activation_epoch) != 0 {
let stake_lamports_ok = if invoke_context
.feature_set
.is_active(&feature_set::stake_redelegate_instruction::id())
{
// When a stake account is redelegated, the delegated lamports from the source stake
// account are transferred to a new stake account. Do not permit the deactivation of
// the source stake account to be rescinded, by more generally requiring the delegation
// be configured with the expected amount of stake lamports before rescinding.
stake_lamports >= stake.delegation.stake
} else {
true
};
// If pubkey of new voter is the same as current,
// and we are scheduled to start deactivating this epoch,
// we rescind deactivation
if stake.delegation.voter_pubkey == *voter_pubkey
&& clock.epoch == stake.delegation.deactivation_epoch
&& stake_lamports_ok
{
stake.delegation.deactivation_epoch = std::u64::MAX;
return Ok(());
} else {
// can't redelegate to another pubkey if stake is active.
return Err(StakeError::TooSoonToRedelegate);
}
}
// Either the stake is freshly activated, is active but has been
// deactivated this epoch, or has fully de-activated.
// Redelegation implies either re-activation or un-deactivation
stake.delegation.stake = stake_lamports;
stake.delegation.activation_epoch = clock.epoch;
stake.delegation.deactivation_epoch = std::u64::MAX;
stake.delegation.voter_pubkey = *voter_pubkey;
stake.credits_observed = vote_state.credits();
Ok(())
}
pub(crate) fn new_stake(
stake: u64,
voter_pubkey: &Pubkey,
vote_state: &VoteState,
activation_epoch: Epoch,
) -> Stake {
Stake {
delegation: Delegation::new(voter_pubkey, stake, activation_epoch),
credits_observed: vote_state.credits(),
}
}
pub fn initialize(
stake_account: &mut BorrowedAccount,
authorized: &Authorized,
lockup: &Lockup,
rent: &Rent,
) -> Result<(), InstructionError> {
if stake_account.get_data().len() != StakeStateV2::size_of() {
return Err(InstructionError::InvalidAccountData);
}
if let StakeStateV2::Uninitialized = stake_account.get_state()? {
let rent_exempt_reserve = rent.minimum_balance(stake_account.get_data().len());
if stake_account.get_lamports() >= rent_exempt_reserve {
stake_account.set_state(&StakeStateV2::Initialized(Meta {
rent_exempt_reserve,
authorized: *authorized,
lockup: *lockup,
}))
} else {
Err(InstructionError::InsufficientFunds)
}
} else {
Err(InstructionError::InvalidAccountData)
}
}
/// Authorize the given pubkey to manage stake (deactivate, withdraw). This may be called
/// multiple times, but will implicitly withdraw authorization from the previously authorized
/// staker. The default staker is the owner of the stake account's pubkey.
pub fn authorize(
stake_account: &mut BorrowedAccount,
signers: &HashSet<Pubkey>,
new_authority: &Pubkey,
stake_authorize: StakeAuthorize,
clock: &Clock,
custodian: Option<&Pubkey>,
) -> Result<(), InstructionError> {
match stake_account.get_state()? {
StakeStateV2::Stake(mut meta, stake, stake_flags) => {
meta.authorized.authorize(
signers,
new_authority,
stake_authorize,
Some((&meta.lockup, clock, custodian)),
)?;
stake_account.set_state(&StakeStateV2::Stake(meta, stake, stake_flags))
}
StakeStateV2::Initialized(mut meta) => {
meta.authorized.authorize(
signers,
new_authority,
stake_authorize,
Some((&meta.lockup, clock, custodian)),
)?;
stake_account.set_state(&StakeStateV2::Initialized(meta))
}
_ => Err(InstructionError::InvalidAccountData),
}
}
#[allow(clippy::too_many_arguments)]
pub fn authorize_with_seed(
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account: &mut BorrowedAccount,
authority_base_index: IndexOfAccount,
authority_seed: &str,
authority_owner: &Pubkey,
new_authority: &Pubkey,
stake_authorize: StakeAuthorize,
clock: &Clock,
custodian: Option<&Pubkey>,
) -> Result<(), InstructionError> {
let mut signers = HashSet::default();
if instruction_context.is_instruction_account_signer(authority_base_index)? {
let base_pubkey = transaction_context.get_key_of_account_at_index(
instruction_context
.get_index_of_instruction_account_in_transaction(authority_base_index)?,
)?;
signers.insert(Pubkey::create_with_seed(
base_pubkey,
authority_seed,
authority_owner,
)?);
}
authorize(
stake_account,
&signers,
new_authority,
stake_authorize,
clock,
custodian,
)
}
#[allow(clippy::too_many_arguments)]
pub fn delegate(
invoke_context: &InvokeContext,
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account_index: IndexOfAccount,
vote_account_index: IndexOfAccount,
clock: &Clock,
stake_history: &StakeHistory,
signers: &HashSet<Pubkey>,
feature_set: &FeatureSet,
) -> Result<(), InstructionError> {
let vote_account = instruction_context
.try_borrow_instruction_account(transaction_context, vote_account_index)?;
if *vote_account.get_owner() != solana_vote_program::id() {
return Err(InstructionError::IncorrectProgramId);
}
let vote_pubkey = *vote_account.get_key();
let vote_state = vote_account.get_state::<VoteStateVersions>();
drop(vote_account);
let mut stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
match stake_account.get_state()? {
StakeStateV2::Initialized(meta) => {
meta.authorized.check(signers, StakeAuthorize::Staker)?;
let ValidatedDelegatedInfo { stake_amount } =
validate_delegated_amount(&stake_account, &meta, feature_set)?;
let stake = new_stake(
stake_amount,
&vote_pubkey,
&vote_state?.convert_to_current(),
clock.epoch,
);
stake_account.set_state(&StakeStateV2::Stake(meta, stake, StakeFlags::empty()))
}
StakeStateV2::Stake(meta, mut stake, stake_flags) => {
meta.authorized.check(signers, StakeAuthorize::Staker)?;
let ValidatedDelegatedInfo { stake_amount } =
validate_delegated_amount(&stake_account, &meta, feature_set)?;
redelegate_stake(
invoke_context,
&mut stake,
stake_amount,
&vote_pubkey,
&vote_state?.convert_to_current(),
clock,
stake_history,
)?;
stake_account.set_state(&StakeStateV2::Stake(meta, stake, stake_flags))
}
_ => Err(InstructionError::InvalidAccountData),
}
}
fn deactivate_stake(
invoke_context: &InvokeContext,
stake: &mut Stake,
stake_flags: &mut StakeFlags,
epoch: Epoch,
) -> Result<(), InstructionError> {
if invoke_context
.feature_set
.is_active(&feature_set::stake_redelegate_instruction::id())
{
if stake_flags.contains(StakeFlags::MUST_FULLY_ACTIVATE_BEFORE_DEACTIVATION_IS_PERMITTED) {
let stake_history = invoke_context.get_sysvar_cache().get_stake_history()?;
// when MUST_FULLY_ACTIVATE_BEFORE_DEACTIVATION_IS_PERMITTED flag is set on stake_flags,
// deactivation is only permitted when the stake delegation activating amount is zero.
let status = stake.delegation.stake_activating_and_deactivating(
epoch,
&stake_history,
new_warmup_cooldown_rate_epoch(invoke_context),
);
if status.activating != 0 {
Err(InstructionError::from(
StakeError::RedelegatedStakeMustFullyActivateBeforeDeactivationIsPermitted,
))
} else {
stake.deactivate(epoch)?;
// After deactivation, need to clear `MustFullyActivateBeforeDeactivationIsPermitted` flag if any.
// So that future activation and deactivation are not subject to that restriction.
stake_flags
.remove(StakeFlags::MUST_FULLY_ACTIVATE_BEFORE_DEACTIVATION_IS_PERMITTED);
Ok(())
}
} else {
stake.deactivate(epoch)?;
Ok(())
}
} else {
stake.deactivate(epoch)?;
Ok(())
}
}
pub fn deactivate(
invoke_context: &InvokeContext,
stake_account: &mut BorrowedAccount,
clock: &Clock,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
if let StakeStateV2::Stake(meta, mut stake, mut stake_flags) = stake_account.get_state()? {
meta.authorized.check(signers, StakeAuthorize::Staker)?;
deactivate_stake(invoke_context, &mut stake, &mut stake_flags, clock.epoch)?;
stake_account.set_state(&StakeStateV2::Stake(meta, stake, stake_flags))
} else {
Err(InstructionError::InvalidAccountData)
}
}
pub fn set_lockup(
stake_account: &mut BorrowedAccount,
lockup: &LockupArgs,
signers: &HashSet<Pubkey>,
clock: &Clock,
) -> Result<(), InstructionError> {
match stake_account.get_state()? {
StakeStateV2::Initialized(mut meta) => {
meta.set_lockup(lockup, signers, clock)?;
stake_account.set_state(&StakeStateV2::Initialized(meta))
}
StakeStateV2::Stake(mut meta, stake, stake_flags) => {
meta.set_lockup(lockup, signers, clock)?;
stake_account.set_state(&StakeStateV2::Stake(meta, stake, stake_flags))
}
_ => Err(InstructionError::InvalidAccountData),
}
}
pub fn split(
invoke_context: &InvokeContext,
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account_index: IndexOfAccount,
lamports: u64,
split_index: IndexOfAccount,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
let split =
instruction_context.try_borrow_instruction_account(transaction_context, split_index)?;
if *split.get_owner() != id() {
return Err(InstructionError::IncorrectProgramId);
}
if split.get_data().len() != StakeStateV2::size_of() {
return Err(InstructionError::InvalidAccountData);
}
if !matches!(split.get_state()?, StakeStateV2::Uninitialized) {
return Err(InstructionError::InvalidAccountData);
}
let split_lamport_balance = split.get_lamports();
drop(split);
let stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
if lamports > stake_account.get_lamports() {
return Err(InstructionError::InsufficientFunds);
}
let stake_state = stake_account.get_state()?;
drop(stake_account);
match stake_state {
StakeStateV2::Stake(meta, mut stake, stake_flags) => {
meta.authorized.check(signers, StakeAuthorize::Staker)?;
let minimum_delegation = crate::get_minimum_delegation(&invoke_context.feature_set);
let is_active = {
let clock = invoke_context.get_sysvar_cache().get_clock()?;
let status = get_stake_status(invoke_context, &stake, &clock)?;
status.effective > 0
};
let validated_split_info = validate_split_amount(
invoke_context,
transaction_context,
instruction_context,
stake_account_index,
split_index,
lamports,
&meta,
minimum_delegation,
is_active,
)?;
// split the stake, subtract rent_exempt_balance unless
// the destination account already has those lamports
// in place.
// this means that the new stake account will have a stake equivalent to
// lamports minus rent_exempt_reserve if it starts out with a zero balance
let (remaining_stake_delta, split_stake_amount) =
if validated_split_info.source_remaining_balance == 0 {
// If split amount equals the full source stake (as implied by 0
// source_remaining_balance), the new split stake must equal the same
// amount, regardless of any current lamport balance in the split account.
// Since split accounts retain the state of their source account, this
// prevents any magic activation of stake by prefunding the split account.
//
// The new split stake also needs to ignore any positive delta between the
// original rent_exempt_reserve and the split_rent_exempt_reserve, in order
// to prevent magic activation of stake by splitting between accounts of
// different sizes.
let remaining_stake_delta = lamports.saturating_sub(meta.rent_exempt_reserve);
(remaining_stake_delta, remaining_stake_delta)
} else {
// Otherwise, the new split stake should reflect the entire split
// requested, less any lamports needed to cover the split_rent_exempt_reserve.
if stake.delegation.stake.saturating_sub(lamports) < minimum_delegation {
return Err(StakeError::InsufficientDelegation.into());
}
(
lamports,
lamports.saturating_sub(
validated_split_info
.destination_rent_exempt_reserve
.saturating_sub(split_lamport_balance),
),
)
};
if split_stake_amount < minimum_delegation {
return Err(StakeError::InsufficientDelegation.into());
}
let split_stake = stake.split(remaining_stake_delta, split_stake_amount)?;
let mut split_meta = meta;
split_meta.rent_exempt_reserve = validated_split_info.destination_rent_exempt_reserve;
let mut stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
stake_account.set_state(&StakeStateV2::Stake(meta, stake, stake_flags))?;
drop(stake_account);
let mut split = instruction_context
.try_borrow_instruction_account(transaction_context, split_index)?;
split.set_state(&StakeStateV2::Stake(split_meta, split_stake, stake_flags))?;
}
StakeStateV2::Initialized(meta) => {
meta.authorized.check(signers, StakeAuthorize::Staker)?;
let validated_split_info = validate_split_amount(
invoke_context,
transaction_context,
instruction_context,
stake_account_index,
split_index,
lamports,
&meta,
0, // additional_required_lamports
false,
)?;
let mut split_meta = meta;
split_meta.rent_exempt_reserve = validated_split_info.destination_rent_exempt_reserve;
let mut split = instruction_context
.try_borrow_instruction_account(transaction_context, split_index)?;
split.set_state(&StakeStateV2::Initialized(split_meta))?;
}
StakeStateV2::Uninitialized => {
let stake_pubkey = transaction_context.get_key_of_account_at_index(
instruction_context
.get_index_of_instruction_account_in_transaction(stake_account_index)?,
)?;
if !signers.contains(stake_pubkey) {
return Err(InstructionError::MissingRequiredSignature);
}
}
_ => return Err(InstructionError::InvalidAccountData),
}
// Deinitialize state upon zero balance
let mut stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
if lamports == stake_account.get_lamports() {
stake_account.set_state(&StakeStateV2::Uninitialized)?;
}
drop(stake_account);
let mut split =
instruction_context.try_borrow_instruction_account(transaction_context, split_index)?;
split.checked_add_lamports(lamports)?;
drop(split);
let mut stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
stake_account.checked_sub_lamports(lamports)?;
Ok(())
}
pub fn merge(
invoke_context: &InvokeContext,
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account_index: IndexOfAccount,
source_account_index: IndexOfAccount,
clock: &Clock,
stake_history: &StakeHistory,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
let mut source_account = instruction_context
.try_borrow_instruction_account(transaction_context, source_account_index)?;
// Ensure source isn't spoofed
if *source_account.get_owner() != id() {
return Err(InstructionError::IncorrectProgramId);
}
// Close the stake_account-reference loophole
if instruction_context.get_index_of_instruction_account_in_transaction(stake_account_index)?
== instruction_context
.get_index_of_instruction_account_in_transaction(source_account_index)?
{
return Err(InstructionError::InvalidArgument);
}
let mut stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
ic_msg!(invoke_context, "Checking if destination stake is mergeable");
let stake_merge_kind = MergeKind::get_if_mergeable(
invoke_context,
&stake_account.get_state()?,
stake_account.get_lamports(),
clock,
stake_history,
)?;
// Authorized staker is allowed to split/merge accounts
stake_merge_kind
.meta()
.authorized
.check(signers, StakeAuthorize::Staker)?;
ic_msg!(invoke_context, "Checking if source stake is mergeable");
let source_merge_kind = MergeKind::get_if_mergeable(
invoke_context,
&source_account.get_state()?,
source_account.get_lamports(),
clock,
stake_history,
)?;
ic_msg!(invoke_context, "Merging stake accounts");
if let Some(merged_state) = stake_merge_kind.merge(invoke_context, source_merge_kind, clock)? {
stake_account.set_state(&merged_state)?;
}
// Source is about to be drained, deinitialize its state
source_account.set_state(&StakeStateV2::Uninitialized)?;
// Drain the source stake account
let lamports = source_account.get_lamports();
source_account.checked_sub_lamports(lamports)?;
stake_account.checked_add_lamports(lamports)?;
Ok(())
}
pub fn redelegate(
invoke_context: &InvokeContext,
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account: &mut BorrowedAccount,
uninitialized_stake_account_index: IndexOfAccount,
vote_account_index: IndexOfAccount,
signers: &HashSet<Pubkey>,
) -> Result<(), InstructionError> {
let clock = invoke_context.get_sysvar_cache().get_clock()?;
// ensure `uninitialized_stake_account_index` is in the uninitialized state
let mut uninitialized_stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, uninitialized_stake_account_index)?;
if *uninitialized_stake_account.get_owner() != id() {
ic_msg!(
invoke_context,
"expected uninitialized stake account owner to be {}, not {}",
id(),
*uninitialized_stake_account.get_owner()
);
return Err(InstructionError::IncorrectProgramId);
}
if uninitialized_stake_account.get_data().len() != StakeStateV2::size_of() {
ic_msg!(
invoke_context,
"expected uninitialized stake account data len to be {}, not {}",
StakeStateV2::size_of(),
uninitialized_stake_account.get_data().len()
);
return Err(InstructionError::InvalidAccountData);
}
if !matches!(
uninitialized_stake_account.get_state()?,
StakeStateV2::Uninitialized
) {
ic_msg!(
invoke_context,
"expected uninitialized stake account to be uninitialized",
);
return Err(InstructionError::AccountAlreadyInitialized);
}
// validate the provided vote account
let vote_account = instruction_context
.try_borrow_instruction_account(transaction_context, vote_account_index)?;
if *vote_account.get_owner() != solana_vote_program::id() {
ic_msg!(
invoke_context,
"expected vote account owner to be {}, not {}",
solana_vote_program::id(),
*vote_account.get_owner()
);
return Err(InstructionError::IncorrectProgramId);
}
let vote_pubkey = *vote_account.get_key();
let vote_state = vote_account.get_state::<VoteStateVersions>()?;
let (stake_meta, effective_stake) =
if let StakeStateV2::Stake(meta, stake, _stake_flags) = stake_account.get_state()? {
let status = get_stake_status(invoke_context, &stake, &clock)?;
if status.effective == 0 || status.activating != 0 || status.deactivating != 0 {
ic_msg!(invoke_context, "stake is not active");
return Err(StakeError::RedelegateTransientOrInactiveStake.into());
}
// Deny redelegating to the same vote account. This is nonsensical and could be used to
// grief the global stake warm-up/cool-down rate
if stake.delegation.voter_pubkey == vote_pubkey {
ic_msg!(
invoke_context,
"redelegating to the same vote account not permitted"
);
return Err(StakeError::RedelegateToSameVoteAccount.into());
}
(meta, status.effective)
} else {
ic_msg!(invoke_context, "invalid stake account data",);
return Err(InstructionError::InvalidAccountData);
};
// deactivate `stake_account`
//
// Note: This function also ensures `signers` contains the `StakeAuthorize::Staker`
deactivate(invoke_context, stake_account, &clock, signers)?;
// transfer the effective stake to the uninitialized stake account
stake_account.checked_sub_lamports(effective_stake)?;
uninitialized_stake_account.checked_add_lamports(effective_stake)?;
// initialize and schedule `uninitialized_stake_account` for activation
let sysvar_cache = invoke_context.get_sysvar_cache();
let rent = sysvar_cache.get_rent()?;
let mut uninitialized_stake_meta = stake_meta;
uninitialized_stake_meta.rent_exempt_reserve =
rent.minimum_balance(uninitialized_stake_account.get_data().len());
let ValidatedDelegatedInfo { stake_amount } = validate_delegated_amount(
&uninitialized_stake_account,
&uninitialized_stake_meta,
&invoke_context.feature_set,
)?;
uninitialized_stake_account.set_state(&StakeStateV2::Stake(
uninitialized_stake_meta,
new_stake(
stake_amount,
&vote_pubkey,
&vote_state.convert_to_current(),
clock.epoch,
),
StakeFlags::MUST_FULLY_ACTIVATE_BEFORE_DEACTIVATION_IS_PERMITTED,
))?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn withdraw(
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account_index: IndexOfAccount,
lamports: u64,
to_index: IndexOfAccount,
clock: &Clock,
stake_history: &StakeHistory,
withdraw_authority_index: IndexOfAccount,
custodian_index: Option<IndexOfAccount>,
new_rate_activation_epoch: Option<Epoch>,
) -> Result<(), InstructionError> {
let withdraw_authority_pubkey = transaction_context.get_key_of_account_at_index(
instruction_context
.get_index_of_instruction_account_in_transaction(withdraw_authority_index)?,
)?;
if !instruction_context.is_instruction_account_signer(withdraw_authority_index)? {
return Err(InstructionError::MissingRequiredSignature);
}
let mut signers = HashSet::new();
signers.insert(*withdraw_authority_pubkey);
let mut stake_account = instruction_context
.try_borrow_instruction_account(transaction_context, stake_account_index)?;
let (lockup, reserve, is_staked) = match stake_account.get_state()? {
StakeStateV2::Stake(meta, stake, _stake_flag) => {
meta.authorized
.check(&signers, StakeAuthorize::Withdrawer)?;
// if we have a deactivation epoch and we're in cooldown
let staked = if clock.epoch >= stake.delegation.deactivation_epoch {
stake
.delegation
.stake(clock.epoch, stake_history, new_rate_activation_epoch)
} else {
// Assume full stake if the stake account hasn't been
// de-activated, because in the future the exposed stake
// might be higher than stake.stake() due to warmup
stake.delegation.stake
};
let staked_and_reserve = checked_add(staked, meta.rent_exempt_reserve)?;
(meta.lockup, staked_and_reserve, staked != 0)
}
StakeStateV2::Initialized(meta) => {
meta.authorized
.check(&signers, StakeAuthorize::Withdrawer)?;
// stake accounts must have a balance >= rent_exempt_reserve
(meta.lockup, meta.rent_exempt_reserve, false)
}
StakeStateV2::Uninitialized => {
if !signers.contains(stake_account.get_key()) {
return Err(InstructionError::MissingRequiredSignature);
}
(Lockup::default(), 0, false) // no lockup, no restrictions
}
_ => return Err(InstructionError::InvalidAccountData),
};
// verify that lockup has expired or that the withdrawal is signed by
// the custodian, both epoch and unix_timestamp must have passed
let custodian_pubkey = if let Some(custodian_index) = custodian_index {
if instruction_context.is_instruction_account_signer(custodian_index)? {
Some(
transaction_context.get_key_of_account_at_index(
instruction_context
.get_index_of_instruction_account_in_transaction(custodian_index)?,
)?,
)
} else {
None
}
} else {
None
};
if lockup.is_in_force(clock, custodian_pubkey) {
return Err(StakeError::LockupInForce.into());
}
let lamports_and_reserve = checked_add(lamports, reserve)?;
// if the stake is active, we mustn't allow the account to go away
if is_staked // line coverage for branch coverage
&& lamports_and_reserve > stake_account.get_lamports()
{
return Err(InstructionError::InsufficientFunds);
}
if lamports != stake_account.get_lamports() // not a full withdrawal
&& lamports_and_reserve > stake_account.get_lamports()
{
assert!(!is_staked);
return Err(InstructionError::InsufficientFunds);
}
// Deinitialize state upon zero balance
if lamports == stake_account.get_lamports() {
stake_account.set_state(&StakeStateV2::Uninitialized)?;
}
stake_account.checked_sub_lamports(lamports)?;
drop(stake_account);
let mut to =
instruction_context.try_borrow_instruction_account(transaction_context, to_index)?;
to.checked_add_lamports(lamports)?;
Ok(())
}
pub(crate) fn deactivate_delinquent(
invoke_context: &InvokeContext,
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
stake_account: &mut BorrowedAccount,
delinquent_vote_account_index: IndexOfAccount,
reference_vote_account_index: IndexOfAccount,
current_epoch: Epoch,
) -> Result<(), InstructionError> {
let delinquent_vote_account_pubkey = transaction_context.get_key_of_account_at_index(
instruction_context
.get_index_of_instruction_account_in_transaction(delinquent_vote_account_index)?,
)?;
let delinquent_vote_account = instruction_context
.try_borrow_instruction_account(transaction_context, delinquent_vote_account_index)?;
if *delinquent_vote_account.get_owner() != solana_vote_program::id() {
return Err(InstructionError::IncorrectProgramId);
}
let delinquent_vote_state = delinquent_vote_account
.get_state::<VoteStateVersions>()?
.convert_to_current();
let reference_vote_account = instruction_context
.try_borrow_instruction_account(transaction_context, reference_vote_account_index)?;
if *reference_vote_account.get_owner() != solana_vote_program::id() {
return Err(InstructionError::IncorrectProgramId);
}
let reference_vote_state = reference_vote_account
.get_state::<VoteStateVersions>()?
.convert_to_current();
if !acceptable_reference_epoch_credits(&reference_vote_state.epoch_credits, current_epoch) {
return Err(StakeError::InsufficientReferenceVotes.into());
}
if let StakeStateV2::Stake(meta, mut stake, mut stake_flags) = stake_account.get_state()? {
if stake.delegation.voter_pubkey != *delinquent_vote_account_pubkey {
return Err(StakeError::VoteAddressMismatch.into());
}
// Deactivate the stake account if its delegated vote account has never voted or has not
// voted in the last `MINIMUM_DELINQUENT_EPOCHS_FOR_DEACTIVATION`
if eligible_for_deactivate_delinquent(&delinquent_vote_state.epoch_credits, current_epoch) {
deactivate_stake(invoke_context, &mut stake, &mut stake_flags, current_epoch)?;
stake_account.set_state(&StakeStateV2::Stake(meta, stake, stake_flags))
} else {
Err(StakeError::MinimumDelinquentEpochsForDeactivationNotMet.into())
}
} else {
Err(InstructionError::InvalidAccountData)
}
}
/// After calling `validate_delegated_amount()`, this struct contains calculated values that are used
/// by the caller.
struct ValidatedDelegatedInfo {
stake_amount: u64,
}
/// Ensure the stake delegation amount is valid. This checks that the account meets the minimum
/// balance requirements of delegated stake. If not, return an error.
fn validate_delegated_amount(
account: &BorrowedAccount,
meta: &Meta,
feature_set: &FeatureSet,
) -> Result<ValidatedDelegatedInfo, InstructionError> {
let stake_amount = account
.get_lamports()
.saturating_sub(meta.rent_exempt_reserve); // can't stake the rent
// Stake accounts may be initialized with a stake amount below the minimum delegation so check
// that the minimum is met before delegation.
if stake_amount < crate::get_minimum_delegation(feature_set) {
return Err(StakeError::InsufficientDelegation.into());
}
Ok(ValidatedDelegatedInfo { stake_amount })
}
/// After calling `validate_split_amount()`, this struct contains calculated values that are used
/// by the caller.
#[derive(Copy, Clone, Debug, Default)]
struct ValidatedSplitInfo {
source_remaining_balance: u64,
destination_rent_exempt_reserve: u64,
}
/// Ensure the split amount is valid. This checks the source and destination accounts meet the
/// minimum balance requirements, which is the rent exempt reserve plus the minimum stake
/// delegation, and that the source account has enough lamports for the request split amount. If
/// not, return an error.
fn validate_split_amount(
invoke_context: &InvokeContext,
transaction_context: &TransactionContext,
instruction_context: &InstructionContext,
source_account_index: IndexOfAccount,
destination_account_index: IndexOfAccount,
lamports: u64,
source_meta: &Meta,
additional_required_lamports: u64,
source_is_active: bool,
) -> Result<ValidatedSplitInfo, InstructionError> {
let source_account = instruction_context
.try_borrow_instruction_account(transaction_context, source_account_index)?;
let source_lamports = source_account.get_lamports();
drop(source_account);
let destination_account = instruction_context
.try_borrow_instruction_account(transaction_context, destination_account_index)?;
let destination_lamports = destination_account.get_lamports();
let destination_data_len = destination_account.get_data().len();
drop(destination_account);
// Split amount has to be something
if lamports == 0 {
return Err(InstructionError::InsufficientFunds);
}
// Obviously cannot split more than what the source account has
if lamports > source_lamports {
return Err(InstructionError::InsufficientFunds);
}
// Verify that the source account still has enough lamports left after splitting:
// EITHER at least the minimum balance, OR zero (in this case the source
// account is transferring all lamports to new destination account, and the source
// account will be closed)
let source_minimum_balance = source_meta
.rent_exempt_reserve
.saturating_add(additional_required_lamports);
let source_remaining_balance = source_lamports.saturating_sub(lamports);
if source_remaining_balance == 0 {
// full amount is a withdrawal
// nothing to do here
} else if source_remaining_balance < source_minimum_balance {
// the remaining balance is too low to do the split
return Err(InstructionError::InsufficientFunds);
} else {
// all clear!
// nothing to do here
}
let rent = invoke_context.get_sysvar_cache().get_rent()?;
let destination_rent_exempt_reserve = rent.minimum_balance(destination_data_len);
// If the source is active stake, one of these criteria must be met:
// 1. the destination account must be prefunded with at least the rent-exempt reserve, or
// 2. the split must consume 100% of the source
if source_is_active
&& source_remaining_balance != 0
&& destination_lamports < destination_rent_exempt_reserve
{
return Err(InstructionError::InsufficientFunds);
}
// Verify the destination account meets the minimum balance requirements
// This must handle:
// 1. The destination account having a different rent exempt reserve due to data size changes
// 2. The destination account being prefunded, which would lower the minimum split amount
let destination_minimum_balance =
destination_rent_exempt_reserve.saturating_add(additional_required_lamports);
let destination_balance_deficit =
destination_minimum_balance.saturating_sub(destination_lamports);
if lamports < destination_balance_deficit {
return Err(InstructionError::InsufficientFunds);
}
Ok(ValidatedSplitInfo {
source_remaining_balance,
destination_rent_exempt_reserve,
})
}
#[derive(Clone, Debug, PartialEq)]
enum MergeKind {
Inactive(Meta, u64, StakeFlags),
ActivationEpoch(Meta, Stake, StakeFlags),
FullyActive(Meta, Stake),
}
impl MergeKind {
fn meta(&self) -> &Meta {
match self {
Self::Inactive(meta, _, _) => meta,
Self::ActivationEpoch(meta, _, _) => meta,
Self::FullyActive(meta, _) => meta,
}
}