-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathinterface.rs
More file actions
1334 lines (1195 loc) · 45.6 KB
/
interface.rs
File metadata and controls
1334 lines (1195 loc) · 45.6 KB
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
#![allow(clippy::arithmetic_side_effects)]
use {
arbitrary::{Arbitrary, Unstructured},
mollusk_svm::{result::Check, Mollusk},
mollusk_svm_result::InstructionResult as MolluskResult,
solana_account::{Account, ReadableAccount, WritableAccount},
solana_clock::Clock,
solana_epoch_rewards::EpochRewards,
solana_epoch_schedule::EpochSchedule,
solana_instruction::{AccountMeta, Instruction},
solana_native_token::LAMPORTS_PER_SOL,
solana_pubkey::Pubkey,
solana_rent::{Rent, DEFAULT_LAMPORTS_PER_BYTE_YEAR},
solana_sdk_ids::system_program,
solana_stake_interface::{
instruction::{self, LockupArgs},
stake_flags::StakeFlags,
stake_history::StakeHistory,
state::{
warmup_cooldown_rate, Authorized, Delegation, Lockup, Meta, Stake, StakeAuthorize,
StakeStateV2, NEW_WARMUP_COOLDOWN_RATE,
},
},
solana_stake_interface_v2::stake_history::StakeHistoryEntry as MolluskStakeHistoryEntry,
solana_stake_program::{get_minimum_delegation, id},
solana_svm_log_collector::LogCollector,
solana_sysvar_id::SysvarId,
solana_vote_interface::{
program as vote_program,
state::{VoteStateV4, VoteStateVersions},
},
std::{
collections::{HashMap, HashSet},
sync::LazyLock,
},
test_case::test_case,
};
// StakeInterface encapsulates every combination of instruction, account states, and input parameters
// that we want to test, so that we can exhaustively generate valid, successful instructions. The
// output instructions can be used as-is to verify the program interface works for all combinations of
// input classes. They can also be changed to operations that must fail, to test error checks have no gaps.
//
// Env encapulates the mollusk test runner, a set of "base" accounts constituting the default state,
// and a set of "override" accounts which change that state prior to instruction execution.
// This is to allow us to repeatedly reuse one Env (by dropping the overrides and creating new ones)
// instead of creating it from scratch for each test, which would make these tests take minutes
// to run once we add more cases.
//
// All constants and addresses in this file are used with mollusk to set up base usable accounts,
// which StakeInterface then puts into a suitable state for particular instructions. For example,
// Merge sets up two stake accounts with appropriate lockups, authorities, and activation states.
// NOTE ideas for future tests:
// * fail with different vote accounts on operations that require them to match
// * fail with different authorities/lockups on operations that require metas to match
// arbitrary, gives us room to set up activations/deactivations
const EXECUTION_EPOCH: u64 = 8;
// mollusk doesnt charge transaction fees, this is just a convenient source/sink for lamports
const PAYER: Pubkey = Pubkey::from_str_const("PAYER11111111111111111111111111111111111111");
const PAYER_BALANCE: u64 = 1_000_000 * LAMPORTS_PER_SOL;
// two vote accounts with no credits
const VOTE_ACCOUNT_RED: Pubkey =
Pubkey::from_str_const("RED1111111111111111111111111111111111111111");
const VOTE_ACCOUNT_BLUE: Pubkey =
Pubkey::from_str_const("BLUE111111111111111111111111111111111111111");
// reference vote account for DeactivateDelinquent
const VOTE_ACCOUNT_GOLD: Pubkey =
Pubkey::from_str_const("GXLD111111111111111111111111111111111111111");
// two blank stake accounts that can be serialized into for tests
const STAKE_ACCOUNT_BLACK: Pubkey =
Pubkey::from_str_const("BLACK11111111111111111111111111111111111111");
const STAKE_ACCOUNT_WHITE: Pubkey =
Pubkey::from_str_const("WH1TE11111111111111111111111111111111111111");
// separate authorities for two stake accounts
const STAKER_BLACK: Pubkey = Pubkey::from_str_const("STAKERBLACK11111111111111111111111111111111");
const WITHDRAWER_BLACK: Pubkey =
Pubkey::from_str_const("W1THDRAWERBLACK1111111111111111111111111111");
const STAKER_WHITE: Pubkey = Pubkey::from_str_const("STAKERWH1TE11111111111111111111111111111111");
const WITHDRAWER_WHITE: Pubkey =
Pubkey::from_str_const("W1THDRAWERWH1TE1111111111111111111111111111");
// shared authorities for two stake accounts, clearly distinguished from the above
const STAKER_GRAY: Pubkey = Pubkey::from_str_const("STAKERGRAY111111111111111111111111111111111");
const WITHDRAWER_GRAY: Pubkey =
Pubkey::from_str_const("W1THDRAWERGRAY11111111111111111111111111111");
// valid custodians for any stake account
const CUSTODIAN_LEFT: Pubkey =
Pubkey::from_str_const("CUSTXD1ANLEFT111111111111111111111111111111");
const CUSTODIAN_RIGHT: Pubkey =
Pubkey::from_str_const("CUSTXD1ANR1GHT11111111111111111111111111111");
// stake delegated to some imaginary vote account in all epochs
// with a warmup/cooldown rate of 9%, routine tests moving under 9sol can ignore stake history
// while also making it easy to write tests involving partial (de)activations
// if the warmup/cooldown rate changes, this number must be adjusted
const PERSISTENT_ACTIVE_STAKE: u64 = 100 * LAMPORTS_PER_SOL;
#[test]
fn assert_warmup_cooldown_rate() {
assert_eq!(warmup_cooldown_rate(0, Some(0)), NEW_WARMUP_COOLDOWN_RATE);
}
// this mirrors the false const for `Meta.rent_exempt_reserve` in the stake program
// the stake program uses true `Rent` unconditionally but maintains this field for compatibility
// assert our consts in case cluster rent changes eventually lead to these values changing
const PSEUDO_RENT_EXEMPT_RESERVE: u64 = 2_282_880;
#[test]
fn assert_pseudo_stake_rent_exemption() {
assert_eq!(
Rent::default().minimum_balance(StakeStateV2::size_of()),
PSEUDO_RENT_EXEMPT_RESERVE
);
assert_eq!(
1_000_000_000 / 100 * 365 / (1024 * 1024),
DEFAULT_LAMPORTS_PER_BYTE_YEAR,
);
}
// exhaustive set of all test instruction declarations
// this is probabilistic but should exceed ten nines
// implementing it by hand would be extremely annoying
static INSTRUCTION_DECLARATIONS: LazyLock<HashSet<StakeInterface>> = LazyLock::new(|| {
let mut declarations = HashSet::new();
for _ in 0..10_000 {
let raw_data: Vec<u8> = (0..StakeInterface::max_size())
.map(|_| rand::random::<u8>())
.collect();
let mut unstructured = Unstructured::new(&raw_data);
declarations.insert(StakeInterface::arbitrary(&mut unstructured).unwrap());
}
declarations
});
// we use two hashmaps because cloning mollusk is impossible and creating it is expensive
// doing this we let base_accounts be immutable and can set and clear override_accounts
struct Env {
mollusk: Mollusk,
base_accounts: HashMap<Pubkey, Account>,
override_accounts: HashMap<Pubkey, Account>,
}
impl Env {
// set up a test environment with valid stake history, two vote accounts, and two blank stake accounts
fn init() -> Self {
Env::with_rent(Rent::default())
}
fn with_rent(rent: Rent) -> Self {
// create a test environment at the execution epoch
let mut base_accounts = HashMap::new();
let mut mollusk = Mollusk::new(&id(), "solana_stake_program");
mollusk.sysvars.rent = rent;
mollusk.warp_to_slot(EXECUTION_EPOCH * mollusk.sysvars.epoch_schedule.slots_per_epoch + 1);
assert_eq!(mollusk.sysvars.clock.epoch, EXECUTION_EPOCH);
// backfill stake history
let stake_delta_amount =
(PERSISTENT_ACTIVE_STAKE as f64 * NEW_WARMUP_COOLDOWN_RATE).floor() as u64;
for epoch in 0..EXECUTION_EPOCH {
mollusk.sysvars.stake_history.add(
epoch,
MolluskStakeHistoryEntry {
effective: PERSISTENT_ACTIVE_STAKE,
activating: stake_delta_amount,
deactivating: stake_delta_amount,
},
);
}
// add a lamports source
let payer_account =
Account::new_rent_epoch(PAYER_BALANCE, 0, &system_program::id(), u64::MAX);
base_accounts.insert(PAYER, payer_account);
// create two blank vote accounts
let vote_rent_exemption = mollusk.sysvars.rent.minimum_balance(VoteStateV4::size_of());
let vote_state_versions = VoteStateVersions::new_v4(VoteStateV4::default());
let vote_data = bincode::serialize(&vote_state_versions).unwrap();
let vote_account = Account::create(
vote_rent_exemption,
vote_data,
vote_program::id(),
false,
u64::MAX,
);
base_accounts.insert(VOTE_ACCOUNT_RED, vote_account.clone());
base_accounts.insert(VOTE_ACCOUNT_BLUE, vote_account);
// create a reference vote account
let mut reference_vote_state = VoteStateV4::default();
for epoch in 0..=EXECUTION_EPOCH {
reference_vote_state
.epoch_credits
.push((epoch, epoch, epoch.saturating_sub(1)));
}
let vote_state_versions = VoteStateVersions::new_v4(reference_vote_state);
let vote_data = bincode::serialize(&vote_state_versions).unwrap();
let vote_account = Account::create(
vote_rent_exemption,
vote_data,
vote_program::id(),
false,
u64::MAX,
);
base_accounts.insert(VOTE_ACCOUNT_GOLD, vote_account);
// create two blank stake accounts
let stake_account = Account::create(
mollusk
.sysvars
.rent
.minimum_balance(StakeStateV2::size_of()),
vec![0; StakeStateV2::size_of()],
id(),
false,
u64::MAX,
);
base_accounts.insert(STAKE_ACCOUNT_BLACK, stake_account.clone());
base_accounts.insert(STAKE_ACCOUNT_WHITE, stake_account);
Self {
mollusk,
base_accounts,
override_accounts: HashMap::new(),
}
}
// set up one of the preconfigured blank stake accounts at some starting state
// to mutate the accounts after initial setup, do it directly or execute instructions
// note these accounts are already rent exempt, so lamports specified are stake or extra
fn update_stake(
&mut self,
pubkey: &Pubkey,
stake_state: &StakeStateV2,
additional_lamports: u64,
) {
assert!(*pubkey == STAKE_ACCOUNT_BLACK || *pubkey == STAKE_ACCOUNT_WHITE);
let mut stake_account = if let Some(stake_account) = self.override_accounts.get(pubkey) {
stake_account.clone()
} else {
self.base_accounts.get(pubkey).cloned().unwrap()
};
let current_lamports = stake_account.lamports();
stake_account.set_lamports(current_lamports + additional_lamports);
bincode::serialize_into(stake_account.data_as_mut_slice(), stake_state).unwrap();
self.override_accounts.insert(*pubkey, stake_account);
}
// get the accounts from our account store that this transaction expects to see
// we dont need implicit sysvars, mollusk resolves them internally via syscall stub
fn resolve_accounts(&self, account_metas: &[AccountMeta]) -> Vec<(Pubkey, Account)> {
let mut accounts = vec![];
for account_meta in account_metas {
let key = account_meta.pubkey;
let account_shared_data = if Rent::check_id(&key) {
self.mollusk.sysvars.keyed_account_for_rent_sysvar().1
} else if Clock::check_id(&key) {
self.mollusk.sysvars.keyed_account_for_clock_sysvar().1
} else if EpochSchedule::check_id(&key) {
self.mollusk
.sysvars
.keyed_account_for_epoch_schedule_sysvar()
.1
} else if EpochRewards::check_id(&key) {
self.mollusk
.sysvars
.keyed_account_for_epoch_rewards_sysvar()
.1
} else if StakeHistory::check_id(&key) {
self.mollusk
.sysvars
.keyed_account_for_stake_history_sysvar()
.1
} else if let Some(account) = self.override_accounts.get(&key).cloned() {
account
} else {
self.base_accounts.get(&key).cloned().unwrap_or_default()
};
accounts.push((key, account_shared_data));
}
accounts
}
// immutable process that should succeed
fn process_success(&self, instruction: &Instruction) -> MolluskResult {
let accounts = self.resolve_accounts(&instruction.accounts);
self.mollusk
.process_and_validate_instruction(instruction, &accounts, &[Check::success()])
}
// immutable process that should fail
fn process_fail(&self, instruction: &Instruction) {
let accounts = self.resolve_accounts(&instruction.accounts);
let result = self.mollusk.process_instruction(instruction, &accounts);
assert!(result.program_result.is_err());
}
// reset Env back to its setup state for reuse
fn reset(&mut self) {
self.override_accounts.clear()
}
// calculate rent exemption via our configured Rent
fn minimum_balance(&self, size: usize) -> u64 {
self.mollusk.sysvars.rent.minimum_balance(size)
}
}
// NOTE we skip:
// * redelegate: will never be enabled
// * minimum delegation: cannot fail in any nontrivial way
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Arbitrary)]
enum StakeInterface {
Initialize {
lockup_state: LockupState,
},
InitializeChecked,
Authorize {
checked: bool,
authority_type: AuthorityType,
lockup_state: LockupState,
},
AuthorizeWithSeed {
checked: bool,
authority_type: AuthorityType,
lockup_state: LockupState,
},
SetLockup {
checked: bool,
existing_lockup_state: LockupState,
new_lockup_state: LockupState,
},
DelegateStake {
lockup_state: LockupState,
},
Split {
lockup_state: LockupState,
full_split: bool,
},
Merge {
lockup_state: LockupState,
},
MoveStake {
lockup_state: LockupState,
active_destination: bool,
full_move: bool,
},
MoveLamports {
lockup_state: LockupState,
active_source: bool,
destination_status: MoveLamportsStatus,
},
Withdraw {
lockup_state: LockupState,
source_status: WithdrawStatus,
full_withdraw: bool,
},
Deactivate {
lockup_state: LockupState,
},
DeactivateDelinquent {
lockup_state: LockupState,
},
}
impl StakeInterface {
// unfortunately `size_hint()` is useless
// we substantially overshoot to avoid mistakes
fn max_size() -> usize {
128
}
// state of any existing lockup on the stake accounts
fn lockup_state(self) -> LockupState {
match self {
Self::Initialize { .. }
| Self::InitializeChecked
| Self::Withdraw {
source_status: WithdrawStatus::Uninitialized,
..
} => LockupState::None,
Self::Authorize { lockup_state, .. }
| Self::AuthorizeWithSeed { lockup_state, .. }
| Self::SetLockup {
existing_lockup_state: lockup_state,
..
}
| Self::DelegateStake { lockup_state, .. }
| Self::Split { lockup_state, .. }
| Self::Merge { lockup_state, .. }
| Self::MoveStake { lockup_state, .. }
| Self::MoveLamports { lockup_state, .. }
| Self::Withdraw { lockup_state, .. }
| Self::Deactivate { lockup_state, .. }
| Self::DeactivateDelinquent { lockup_state, .. } => lockup_state,
}
}
// creates an instruction with the given combination of settings that is guaranteed to succeed
fn to_instruction(self, env: &mut Env) -> Instruction {
let rent_exempt_reserve = env.minimum_balance(StakeStateV2::size_of());
let minimum_delegation = get_minimum_delegation();
match self {
Self::Initialize { lockup_state } => instruction::initialize(
&STAKE_ACCOUNT_BLACK,
&Authorized {
staker: STAKER_BLACK,
withdrawer: WITHDRAWER_BLACK,
},
&lockup_state.to_lockup(CUSTODIAN_LEFT),
),
Self::InitializeChecked => instruction::initialize_checked(
&STAKE_ACCOUNT_BLACK,
&Authorized {
staker: STAKER_BLACK,
withdrawer: WITHDRAWER_BLACK,
},
),
Self::Authorize {
checked,
authority_type,
lockup_state,
} => {
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&initialized_stake(
STAKE_ACCOUNT_BLACK,
minimum_delegation,
false,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
let authorize = authority_type.into();
let (old_authority, new_authority) = match authorize {
StakeAuthorize::Staker => (STAKER_BLACK, STAKER_GRAY),
StakeAuthorize::Withdrawer => (WITHDRAWER_BLACK, WITHDRAWER_GRAY),
};
let make_instruction = if checked {
instruction::authorize_checked
} else {
instruction::authorize
};
make_instruction(
&STAKE_ACCOUNT_BLACK,
&old_authority,
&new_authority,
authorize,
lockup_state.to_custodian(&CUSTODIAN_LEFT),
)
}
Self::AuthorizeWithSeed {
checked,
authority_type,
lockup_state,
} => {
let seed_base = Pubkey::new_unique();
let seed = "seed";
let seed_authority =
Pubkey::create_with_seed(&seed_base, seed, &system_program::id()).unwrap();
let mut black_state = initialized_stake(
STAKE_ACCOUNT_BLACK,
minimum_delegation,
false,
lockup_state.to_lockup(CUSTODIAN_LEFT),
);
let authorize = authority_type.into();
let new_authority = match black_state {
StakeStateV2::Initialized(ref mut meta) => match authorize {
StakeAuthorize::Staker => {
meta.authorized.staker = seed_authority;
STAKER_GRAY
}
StakeAuthorize::Withdrawer => {
meta.authorized.withdrawer = seed_authority;
WITHDRAWER_GRAY
}
},
_ => unreachable!(),
};
env.update_stake(&STAKE_ACCOUNT_BLACK, &black_state, minimum_delegation);
let make_instruction = if checked {
instruction::authorize_checked_with_seed
} else {
instruction::authorize_with_seed
};
make_instruction(
&STAKE_ACCOUNT_BLACK,
&seed_base,
seed.to_string(),
&system_program::id(),
&new_authority,
authorize,
lockup_state.to_custodian(&CUSTODIAN_LEFT),
)
}
Self::SetLockup {
checked,
existing_lockup_state,
new_lockup_state,
} => {
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&initialized_stake(
STAKE_ACCOUNT_BLACK,
minimum_delegation,
false,
existing_lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
let make_instruction = if checked {
instruction::set_lockup_checked
} else {
instruction::set_lockup
};
make_instruction(
&STAKE_ACCOUNT_BLACK,
&new_lockup_state.to_args(CUSTODIAN_RIGHT),
existing_lockup_state
.to_custodian(&CUSTODIAN_LEFT)
.unwrap_or(&WITHDRAWER_BLACK),
)
}
Self::DelegateStake { lockup_state } => {
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&initialized_stake(
STAKE_ACCOUNT_BLACK,
minimum_delegation,
false,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
instruction::delegate_stake(&STAKE_ACCOUNT_BLACK, &STAKER_BLACK, &VOTE_ACCOUNT_RED)
}
Self::Split {
lockup_state,
full_split,
} => {
let delegated_stake = minimum_delegation * 2;
let split_amount = if full_split {
delegated_stake + rent_exempt_reserve
} else {
delegated_stake / 2
};
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
delegated_stake,
StakeStatus::Active,
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
delegated_stake,
);
instruction::split(
&STAKE_ACCOUNT_BLACK,
&STAKER_GRAY,
split_amount,
&STAKE_ACCOUNT_WHITE,
)
.remove(2)
}
Self::Merge { lockup_state } => {
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
minimum_delegation,
StakeStatus::Active,
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
env.update_stake(
&STAKE_ACCOUNT_WHITE,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_WHITE,
minimum_delegation,
StakeStatus::Active,
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
instruction::merge(&STAKE_ACCOUNT_WHITE, &STAKE_ACCOUNT_BLACK, &STAKER_GRAY)
.remove(0)
}
Self::MoveStake {
lockup_state,
active_destination,
full_move,
} => {
let source_delegation = minimum_delegation * 2;
let move_amount = if full_move {
source_delegation
} else {
source_delegation / 2
};
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
source_delegation,
StakeStatus::Active,
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
source_delegation,
);
env.update_stake(
&STAKE_ACCOUNT_WHITE,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_WHITE,
minimum_delegation,
if active_destination {
StakeStatus::Active
} else {
StakeStatus::Initialized
},
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
instruction::move_stake(
&STAKE_ACCOUNT_BLACK,
&STAKE_ACCOUNT_WHITE,
&STAKER_GRAY,
move_amount,
)
}
Self::MoveLamports {
lockup_state,
active_source,
destination_status,
} => {
let free_lamports = LAMPORTS_PER_SOL;
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
minimum_delegation,
if active_source {
StakeStatus::Active
} else {
StakeStatus::Initialized
},
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation + free_lamports,
);
env.update_stake(
&STAKE_ACCOUNT_WHITE,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_WHITE,
minimum_delegation,
destination_status.into(),
true,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
instruction::move_lamports(
&STAKE_ACCOUNT_BLACK,
&STAKE_ACCOUNT_WHITE,
&STAKER_GRAY,
free_lamports,
)
}
Self::Withdraw {
lockup_state,
full_withdraw,
source_status,
} => {
let free_lamports = LAMPORTS_PER_SOL;
let source_status = source_status.into();
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
minimum_delegation,
source_status,
false,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation + free_lamports,
);
let withdraw_amount = if full_withdraw && source_status != StakeStatus::Active {
free_lamports + minimum_delegation + rent_exempt_reserve
} else {
free_lamports
};
let authority = if source_status == StakeStatus::Uninitialized {
STAKE_ACCOUNT_BLACK
} else {
WITHDRAWER_BLACK
};
instruction::withdraw(
&STAKE_ACCOUNT_BLACK,
&authority,
&PAYER,
withdraw_amount,
lockup_state.to_custodian(&CUSTODIAN_LEFT),
)
}
Self::Deactivate { lockup_state } => {
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
minimum_delegation,
StakeStatus::Active,
false,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
instruction::deactivate_stake(&STAKE_ACCOUNT_BLACK, &STAKER_BLACK)
}
Self::DeactivateDelinquent { lockup_state } => {
env.update_stake(
&STAKE_ACCOUNT_BLACK,
&fully_configurable_stake(
VOTE_ACCOUNT_RED,
STAKE_ACCOUNT_BLACK,
minimum_delegation,
StakeStatus::Active,
false,
lockup_state.to_lockup(CUSTODIAN_LEFT),
),
minimum_delegation,
);
instruction::deactivate_delinquent_stake(
&STAKE_ACCOUNT_BLACK,
&VOTE_ACCOUNT_RED,
&VOTE_ACCOUNT_GOLD,
)
}
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Arbitrary)]
enum StakeStatus {
Uninitialized,
Initialized,
Activating,
Active,
Deactivating,
Deactive,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Arbitrary)]
enum MoveLamportsStatus {
Initialized,
Activating,
Active,
}
impl From<MoveLamportsStatus> for StakeStatus {
fn from(status: MoveLamportsStatus) -> Self {
match status {
MoveLamportsStatus::Initialized => StakeStatus::Initialized,
MoveLamportsStatus::Activating => StakeStatus::Activating,
MoveLamportsStatus::Active => StakeStatus::Active,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Arbitrary)]
enum WithdrawStatus {
Uninitialized,
Initialized,
Active,
}
impl From<WithdrawStatus> for StakeStatus {
fn from(status: WithdrawStatus) -> Self {
match status {
WithdrawStatus::Uninitialized => StakeStatus::Uninitialized,
WithdrawStatus::Initialized => StakeStatus::Initialized,
WithdrawStatus::Active => StakeStatus::Active,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Arbitrary)]
enum AuthorityType {
Staker,
Withdrawer,
}
impl From<AuthorityType> for StakeAuthorize {
fn from(authority_type: AuthorityType) -> Self {
match authority_type {
AuthorityType::Staker => Self::Staker,
AuthorityType::Withdrawer => Self::Withdrawer,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Arbitrary)]
enum LockupState {
Active,
Inactive,
None,
}
impl LockupState {
fn to_lockup(self, custodian: Pubkey) -> Lockup {
match self {
Self::Active => Lockup {
custodian,
epoch: EXECUTION_EPOCH + 1,
unix_timestamp: 0,
},
Self::Inactive => Lockup {
custodian,
epoch: EXECUTION_EPOCH - 1,
unix_timestamp: 0,
},
Self::None => Lockup::default(),
}
}
fn to_custodian(self, custodian: &Pubkey) -> Option<&Pubkey> {
match self {
Self::Active => Some(custodian),
_ => None,
}
}
fn to_args(self, custodian: Pubkey) -> LockupArgs {
match self {
Self::None => LockupArgs::default(),
_ => LockupArgs {
custodian: self.to_custodian(&custodian).cloned(),
epoch: Some(self.to_lockup(custodian).epoch),
unix_timestamp: None,
},
}
}
}
// initialized with settable authority and lockup
fn initialized_stake(
stake_pubkey: Pubkey,
stake: u64,
use_gray_authority: bool,
lockup: Lockup,
) -> StakeStateV2 {
fully_configurable_stake(
Pubkey::default(),
stake_pubkey,
stake,
StakeStatus::Initialized,
use_gray_authority,
lockup,
)
}
// any point in the stake lifecycle with settable vote account, authority, and lockup
fn fully_configurable_stake(
voter_pubkey: Pubkey,
stake_pubkey: Pubkey,
stake: u64,
stake_status: StakeStatus,
use_gray_authority: bool,
lockup: Lockup,
) -> StakeStateV2 {
assert!(stake_pubkey != VOTE_ACCOUNT_RED);
assert!(stake_pubkey != VOTE_ACCOUNT_BLUE);
let authorized = match stake_pubkey {
_ if use_gray_authority => Authorized {
staker: STAKER_GRAY,
withdrawer: WITHDRAWER_GRAY,
},
STAKE_ACCOUNT_BLACK => Authorized {
staker: STAKER_BLACK,
withdrawer: WITHDRAWER_BLACK,
},
STAKE_ACCOUNT_WHITE => Authorized {
staker: STAKER_WHITE,
withdrawer: WITHDRAWER_WHITE,
},
_ => panic!("expected a hardcoded stake pubkey, got {}", stake_pubkey),
};
let meta = Meta {
#[allow(deprecated)]
rent_exempt_reserve: PSEUDO_RENT_EXEMPT_RESERVE,
authorized,
lockup,
};
let delegation = match stake_status {
StakeStatus::Uninitialized | StakeStatus::Initialized => Delegation::default(),
StakeStatus::Activating => Delegation {
stake,
voter_pubkey,
activation_epoch: EXECUTION_EPOCH,
..Delegation::default()
},
StakeStatus::Active => Delegation {
stake,
voter_pubkey,
activation_epoch: EXECUTION_EPOCH - 1,
..Delegation::default()
},
StakeStatus::Deactivating => Delegation {
stake,
voter_pubkey,
activation_epoch: EXECUTION_EPOCH - 1,
deactivation_epoch: EXECUTION_EPOCH,
..Delegation::default()
},
StakeStatus::Deactive => Delegation {
stake,
voter_pubkey,
activation_epoch: EXECUTION_EPOCH - 2,
deactivation_epoch: EXECUTION_EPOCH - 1,
..Delegation::default()
},
};
match stake_status {
StakeStatus::Uninitialized => StakeStateV2::Uninitialized,
StakeStatus::Initialized => StakeStateV2::Initialized(meta),
_ => StakeStateV2::Stake(
meta,
Stake {
delegation,
..Stake::default()
},
StakeFlags::empty(),
),
}
}
// test all unmodified transactions succeed, to ensure other tests test what they purport to test
#[test]
fn test_all_success() {
let mut env = Env::init();