-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathprogram_test.rs
More file actions
2339 lines (2049 loc) · 78 KB
/
program_test.rs
File metadata and controls
2339 lines (2049 loc) · 78 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 {
solana_account::Account as SolanaAccount,
solana_clock::Clock,
solana_instruction::Instruction,
solana_keypair::Keypair,
solana_program_entrypoint::ProgramResult,
solana_program_error::ProgramError,
solana_program_test::*,
solana_pubkey::Pubkey,
solana_rent::Rent,
solana_sdk_ids::{system_program, sysvar},
solana_signer::{signers::Signers, Signer},
solana_stake_interface::{
error::StakeError,
instruction::{self as ixn, LockupArgs},
program::id,
stake_history::StakeHistory,
state::{Authorized, Delegation, Lockup, Meta, Stake, StakeAuthorize, StakeStateV2},
},
solana_system_interface::instruction as system_instruction,
solana_transaction::{Transaction, TransactionError},
solana_vote_interface::{
instruction as vote_instruction,
state::{VoteInit, VoteStateV4},
},
test_case::{test_case, test_matrix},
};
pub const USER_STARTING_LAMPORTS: u64 = 10_000_000_000_000; // 10k sol
pub const NO_SIGNERS: &[Keypair] = &[];
pub fn program_test() -> ProgramTest {
program_test_without_features(&[])
}
pub fn program_test_without_features(feature_ids: &[Pubkey]) -> ProgramTest {
let mut program_test = ProgramTest::default();
program_test.prefer_bpf(true);
for feature_id in feature_ids {
program_test.deactivate_feature(*feature_id);
}
// `solana-program-test` now seeds Stake111... with a vendored Core BPF stake program.
// Load our local `.so` through the late account-override path so the integration tests
// execute this repo's program instead of Agave's bundled one.
program_test.add_program("solana_stake_program", id(), None);
program_test
}
#[derive(Debug, PartialEq)]
pub struct Accounts {
pub validator: Keypair,
pub voter: Keypair,
pub withdrawer: Keypair,
pub vote_account: Keypair,
}
impl Accounts {
pub async fn initialize(&self, context: &mut ProgramTestContext) {
let slot = context.genesis_config().epoch_schedule.first_normal_slot + 1;
context.warp_to_slot(slot).unwrap();
create_vote(
context,
&self.validator,
&self.voter.pubkey(),
&self.withdrawer.pubkey(),
&self.vote_account,
)
.await;
}
}
impl Default for Accounts {
fn default() -> Self {
let vote_account = Keypair::new();
Self {
validator: Keypair::new(),
voter: Keypair::new(),
withdrawer: Keypair::new(),
vote_account,
}
}
}
pub async fn create_vote(
context: &mut ProgramTestContext,
validator: &Keypair,
voter: &Pubkey,
withdrawer: &Pubkey,
vote_account: &Keypair,
) {
let rent = context.banks_client.get_rent().await.unwrap();
let rent_voter = rent.minimum_balance(VoteStateV4::size_of());
let mut instructions = vec![system_instruction::create_account(
&context.payer.pubkey(),
&validator.pubkey(),
rent.minimum_balance(0),
0,
&system_program::id(),
)];
instructions.append(&mut vote_instruction::create_account_with_config(
&context.payer.pubkey(),
&vote_account.pubkey(),
&VoteInit {
node_pubkey: validator.pubkey(),
authorized_voter: *voter,
authorized_withdrawer: *withdrawer,
..VoteInit::default()
},
rent_voter,
vote_instruction::CreateVoteAccountConfig {
space: VoteStateV4::size_of() as u64,
..Default::default()
},
));
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&context.payer.pubkey()),
&[validator, vote_account, &context.payer],
context.last_blockhash,
);
// ignore errors for idempotency
let _ = context.banks_client.process_transaction(transaction).await;
}
pub async fn transfer(context: &mut ProgramTestContext, recipient: &Pubkey, amount: u64) {
let transaction = Transaction::new_signed_with_payer(
&[system_instruction::transfer(
&context.payer.pubkey(),
recipient,
amount,
)],
Some(&context.payer.pubkey()),
&[&context.payer],
context.last_blockhash,
);
context
.banks_client
.process_transaction(transaction)
.await
.unwrap();
}
pub async fn advance_epoch(context: &mut ProgramTestContext) {
refresh_blockhash(context).await;
let root_slot = context.banks_client.get_root_slot().await.unwrap();
let slots_per_epoch = context.genesis_config().epoch_schedule.slots_per_epoch;
context.warp_to_slot(root_slot + slots_per_epoch).unwrap();
}
pub async fn refresh_blockhash(context: &mut ProgramTestContext) {
context.last_blockhash = context
.banks_client
.get_new_latest_blockhash(&context.last_blockhash)
.await
.unwrap();
}
pub async fn get_account(banks_client: &mut BanksClient, pubkey: &Pubkey) -> SolanaAccount {
banks_client
.get_account(*pubkey)
.await
.expect("client error")
.expect("account not found")
}
pub async fn get_stake_account(
banks_client: &mut BanksClient,
pubkey: &Pubkey,
) -> (Meta, Option<Stake>, u64) {
let stake_account = get_account(banks_client, pubkey).await;
let lamports = stake_account.lamports;
match bincode::deserialize::<StakeStateV2>(&stake_account.data).unwrap() {
StakeStateV2::Initialized(meta) => (meta, None, lamports),
StakeStateV2::Stake(meta, stake, _) => (meta, Some(stake), lamports),
StakeStateV2::Uninitialized => panic!("panic: uninitialized"),
_ => unimplemented!(),
}
}
pub async fn get_stake_account_rent(banks_client: &mut BanksClient) -> u64 {
let rent = banks_client.get_rent().await.unwrap();
rent.minimum_balance(std::mem::size_of::<StakeStateV2>())
}
pub async fn get_effective_stake(banks_client: &mut BanksClient, pubkey: &Pubkey) -> u64 {
let clock = banks_client.get_sysvar::<Clock>().await.unwrap();
let stake_history_account = get_account(banks_client, &sysvar::stake_history::id()).await;
let stake_history = bincode::deserialize::<StakeHistory>(&stake_history_account.data).unwrap();
let stake_account = get_account(banks_client, pubkey).await;
match bincode::deserialize::<StakeStateV2>(&stake_account.data).unwrap() {
StakeStateV2::Stake(_, stake, _) => {
stake
.delegation
.stake_activating_and_deactivating(clock.epoch, &stake_history, Some(0))
.effective
}
_ => 0,
}
}
async fn get_minimum_delegation(context: &mut ProgramTestContext) -> u64 {
let transaction = Transaction::new_signed_with_payer(
&[ixn::get_minimum_delegation()],
Some(&context.payer.pubkey()),
&[&context.payer],
context.last_blockhash,
);
let mut data = context
.banks_client
.simulate_transaction(transaction)
.await
.unwrap()
.simulation_details
.unwrap()
.return_data
.unwrap()
.data;
data.resize(8, 0);
data.try_into().map(u64::from_le_bytes).unwrap()
}
pub async fn create_independent_stake_account(
context: &mut ProgramTestContext,
authorized: &Authorized,
stake_amount: u64,
) -> Pubkey {
create_independent_stake_account_with_lockup(
context,
authorized,
&Lockup::default(),
stake_amount,
)
.await
}
pub async fn create_independent_stake_account_with_lockup(
context: &mut ProgramTestContext,
authorized: &Authorized,
lockup: &Lockup,
stake_amount: u64,
) -> Pubkey {
let stake = Keypair::new();
let lamports = get_stake_account_rent(&mut context.banks_client).await + stake_amount;
let instructions = vec![
system_instruction::create_account(
&context.payer.pubkey(),
&stake.pubkey(),
lamports,
std::mem::size_of::<StakeStateV2>() as u64,
&id(),
),
ixn::initialize(&stake.pubkey(), authorized, lockup),
];
let transaction = Transaction::new_signed_with_payer(
&instructions,
Some(&context.payer.pubkey()),
&[&context.payer, &stake],
context.last_blockhash,
);
context
.banks_client
.process_transaction(transaction)
.await
.unwrap();
stake.pubkey()
}
pub async fn create_blank_stake_account(context: &mut ProgramTestContext) -> Pubkey {
let stake = Keypair::new();
create_blank_stake_account_from_keypair(context, &stake, false).await
}
pub async fn create_closed_stake_account(context: &mut ProgramTestContext) -> Pubkey {
let stake = Keypair::new();
create_blank_stake_account_from_keypair(context, &stake, true).await
}
pub async fn create_blank_stake_account_from_keypair(
context: &mut ProgramTestContext,
stake: &Keypair,
is_closed: bool,
) -> Pubkey {
// lamports in a "closed" account is arbitrary, a real one via split/merge/withdraw would have 0
let lamports = get_stake_account_rent(&mut context.banks_client).await;
let transaction = Transaction::new_signed_with_payer(
&[system_instruction::create_account(
&context.payer.pubkey(),
&stake.pubkey(),
lamports,
if is_closed {
0
} else {
StakeStateV2::size_of() as u64
},
&id(),
)],
Some(&context.payer.pubkey()),
&[&context.payer, stake],
context.last_blockhash,
);
context
.banks_client
.process_transaction(transaction)
.await
.unwrap();
stake.pubkey()
}
pub async fn process_instruction<T: Signers + ?Sized>(
context: &mut ProgramTestContext,
instruction: &Instruction,
additional_signers: &T,
) -> ProgramResult {
let mut transaction = Transaction::new_with_payer(
core::slice::from_ref(instruction),
Some(&context.payer.pubkey()),
);
transaction.partial_sign(&[&context.payer], context.last_blockhash);
transaction.sign(additional_signers, context.last_blockhash);
match context.banks_client.process_transaction(transaction).await {
Ok(_) => Ok(()),
Err(e) => {
// banks client error -> transaction error -> instruction error -> program error
match e.unwrap() {
TransactionError::InstructionError(_, e) => Err(e.try_into().unwrap()),
TransactionError::InsufficientFundsForRent { .. } => {
Err(ProgramError::InsufficientFunds)
}
_ => panic!("couldnt convert {:?} to ProgramError", e),
}
}
}
}
pub async fn process_instruction_test_missing_signers(
context: &mut ProgramTestContext,
instruction: &Instruction,
additional_signers: &Vec<&Keypair>,
) {
// remove every signer one by one and ensure we always fail
for i in 0..instruction.accounts.len() {
if instruction.accounts[i].is_signer {
let mut instruction = instruction.clone();
instruction.accounts[i].is_signer = false;
let reduced_signers: Vec<_> = additional_signers
.iter()
.filter(|s| s.pubkey() != instruction.accounts[i].pubkey)
.collect();
let e = process_instruction(context, &instruction, &reduced_signers)
.await
.unwrap_err();
assert_eq!(e, ProgramError::MissingRequiredSignature);
}
}
// now make sure the instruction succeeds
process_instruction(context, instruction, additional_signers)
.await
.unwrap();
}
#[tokio::test]
async fn program_test_stake_checked_instructions() {
let mut context = program_test().start_with_context().await;
let accounts = Accounts::default();
accounts.initialize(&mut context).await;
let staker_keypair = Keypair::new();
let withdrawer_keypair = Keypair::new();
let authorized_keypair = Keypair::new();
let seed_base_keypair = Keypair::new();
let custodian_keypair = Keypair::new();
let staker = staker_keypair.pubkey();
let withdrawer = withdrawer_keypair.pubkey();
let authorized = authorized_keypair.pubkey();
let seed_base = seed_base_keypair.pubkey();
let custodian = custodian_keypair.pubkey();
let seed = "test seed";
let seeded_address = Pubkey::create_with_seed(&seed_base, seed, &system_program::id()).unwrap();
// Test InitializeChecked with non-signing withdrawer
let stake = create_blank_stake_account(&mut context).await;
let instruction = ixn::initialize_checked(&stake, &Authorized { staker, withdrawer });
process_instruction_test_missing_signers(
&mut context,
&instruction,
&vec![&withdrawer_keypair],
)
.await;
// Test AuthorizeChecked with non-signing staker
let stake =
create_independent_stake_account(&mut context, &Authorized { staker, withdrawer }, 0).await;
let instruction =
ixn::authorize_checked(&stake, &staker, &authorized, StakeAuthorize::Staker, None);
process_instruction_test_missing_signers(
&mut context,
&instruction,
&vec![&staker_keypair, &authorized_keypair],
)
.await;
// Test AuthorizeChecked with non-signing withdrawer
let stake =
create_independent_stake_account(&mut context, &Authorized { staker, withdrawer }, 0).await;
let instruction = ixn::authorize_checked(
&stake,
&withdrawer,
&authorized,
StakeAuthorize::Withdrawer,
None,
);
process_instruction_test_missing_signers(
&mut context,
&instruction,
&vec![&withdrawer_keypair, &authorized_keypair],
)
.await;
// Test AuthorizeCheckedWithSeed with non-signing authority
for authority_type in [StakeAuthorize::Staker, StakeAuthorize::Withdrawer] {
let stake =
create_independent_stake_account(&mut context, &Authorized::auto(&seeded_address), 0)
.await;
let instruction = ixn::authorize_checked_with_seed(
&stake,
&seed_base,
seed.to_string(),
&system_program::id(),
&authorized,
authority_type,
None,
);
process_instruction_test_missing_signers(
&mut context,
&instruction,
&vec![&seed_base_keypair, &authorized_keypair],
)
.await;
}
// Test SetLockupChecked with non-signing lockup custodian
let stake =
create_independent_stake_account(&mut context, &Authorized { staker, withdrawer }, 0).await;
let instruction = ixn::set_lockup_checked(
&stake,
&LockupArgs {
unix_timestamp: None,
epoch: Some(1),
custodian: Some(custodian),
},
&withdrawer,
);
process_instruction_test_missing_signers(
&mut context,
&instruction,
&vec![&withdrawer_keypair, &custodian_keypair],
)
.await;
}
#[tokio::test]
async fn program_test_stake_initialize() {
let mut context = program_test().start_with_context().await;
let accounts = Accounts::default();
accounts.initialize(&mut context).await;
let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
let staker_keypair = Keypair::new();
let withdrawer_keypair = Keypair::new();
let custodian_keypair = Keypair::new();
let staker = staker_keypair.pubkey();
let withdrawer = withdrawer_keypair.pubkey();
let custodian = custodian_keypair.pubkey();
let authorized = Authorized { staker, withdrawer };
let lockup = Lockup {
epoch: 1,
unix_timestamp: 0,
custodian,
};
let stake = create_blank_stake_account(&mut context).await;
let instruction = ixn::initialize(&stake, &authorized, &lockup);
// should pass
process_instruction(&mut context, &instruction, NO_SIGNERS)
.await
.unwrap();
// check that we see what we expect
let account = get_account(&mut context.banks_client, &stake).await;
let stake_state: StakeStateV2 = bincode::deserialize(&account.data).unwrap();
assert_eq!(
stake_state,
StakeStateV2::Initialized(Meta {
authorized,
#[allow(deprecated)]
rent_exempt_reserve,
lockup,
}),
);
// 2nd time fails, can't move it from anything other than uninit->init
refresh_blockhash(&mut context).await;
let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
.await
.unwrap_err();
assert_eq!(e, ProgramError::InvalidAccountData);
// not enough balance for rent
let stake = Pubkey::new_unique();
let account = SolanaAccount {
lamports: rent_exempt_reserve / 2,
data: vec![0; StakeStateV2::size_of()],
owner: id(),
executable: false,
rent_epoch: 1000,
};
context.set_account(&stake, &account.into());
let instruction = ixn::initialize(&stake, &authorized, &lockup);
let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
.await
.unwrap_err();
assert_eq!(e, ProgramError::InsufficientFunds);
// incorrect account sizes
let stake_keypair = Keypair::new();
let stake = stake_keypair.pubkey();
let instruction = system_instruction::create_account(
&context.payer.pubkey(),
&stake,
rent_exempt_reserve * 2,
StakeStateV2::size_of() as u64 + 1,
&id(),
);
process_instruction(&mut context, &instruction, &vec![&stake_keypair])
.await
.unwrap();
let instruction = ixn::initialize(&stake, &authorized, &lockup);
let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
.await
.unwrap_err();
assert_eq!(e, ProgramError::InvalidAccountData);
let stake_keypair = Keypair::new();
let stake = stake_keypair.pubkey();
let instruction = system_instruction::create_account(
&context.payer.pubkey(),
&stake,
rent_exempt_reserve,
StakeStateV2::size_of() as u64 - 1,
&id(),
);
process_instruction(&mut context, &instruction, &vec![&stake_keypair])
.await
.unwrap();
let instruction = ixn::initialize(&stake, &authorized, &lockup);
let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
.await
.unwrap_err();
assert_eq!(e, ProgramError::InvalidAccountData);
}
#[tokio::test]
async fn program_test_authorize() {
let mut context = program_test().start_with_context().await;
let accounts = Accounts::default();
accounts.initialize(&mut context).await;
let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
let stakers: [_; 3] = std::array::from_fn(|_| Keypair::new());
let withdrawers: [_; 3] = std::array::from_fn(|_| Keypair::new());
let stake_keypair = Keypair::new();
let stake = create_blank_stake_account_from_keypair(&mut context, &stake_keypair, false).await;
// authorize uninitialized fails
for (authority, authority_type) in [
(&stakers[0], StakeAuthorize::Staker),
(&withdrawers[0], StakeAuthorize::Withdrawer),
] {
let instruction = ixn::authorize(&stake, &stake, &authority.pubkey(), authority_type, None);
let e = process_instruction(&mut context, &instruction, &vec![&stake_keypair])
.await
.unwrap_err();
assert_eq!(e, ProgramError::InvalidAccountData);
}
let authorized = Authorized {
staker: stakers[0].pubkey(),
withdrawer: withdrawers[0].pubkey(),
};
let instruction = ixn::initialize(&stake, &authorized, &Lockup::default());
process_instruction(&mut context, &instruction, NO_SIGNERS)
.await
.unwrap();
// changing authority works
for (old_authority, new_authority, authority_type) in [
(&stakers[0], &stakers[1], StakeAuthorize::Staker),
(&withdrawers[0], &withdrawers[1], StakeAuthorize::Withdrawer),
] {
let instruction = ixn::authorize(
&stake,
&old_authority.pubkey(),
&new_authority.pubkey(),
authority_type,
None,
);
process_instruction_test_missing_signers(&mut context, &instruction, &vec![old_authority])
.await;
let (meta, _, _) = get_stake_account(&mut context.banks_client, &stake).await;
let actual_authority = match authority_type {
StakeAuthorize::Staker => meta.authorized.staker,
StakeAuthorize::Withdrawer => meta.authorized.withdrawer,
};
assert_eq!(actual_authority, new_authority.pubkey());
}
// old authority no longer works
for (old_authority, new_authority, authority_type) in [
(&stakers[0], Pubkey::new_unique(), StakeAuthorize::Staker),
(
&withdrawers[0],
Pubkey::new_unique(),
StakeAuthorize::Withdrawer,
),
] {
let instruction = ixn::authorize(
&stake,
&old_authority.pubkey(),
&new_authority,
authority_type,
None,
);
let e = process_instruction(&mut context, &instruction, &vec![old_authority])
.await
.unwrap_err();
assert_eq!(e, ProgramError::MissingRequiredSignature);
}
// changing authority again works
for (old_authority, new_authority, authority_type) in [
(&stakers[1], &stakers[2], StakeAuthorize::Staker),
(&withdrawers[1], &withdrawers[2], StakeAuthorize::Withdrawer),
] {
let instruction = ixn::authorize(
&stake,
&old_authority.pubkey(),
&new_authority.pubkey(),
authority_type,
None,
);
process_instruction_test_missing_signers(&mut context, &instruction, &vec![old_authority])
.await;
let (meta, _, _) = get_stake_account(&mut context.banks_client, &stake).await;
let actual_authority = match authority_type {
StakeAuthorize::Staker => meta.authorized.staker,
StakeAuthorize::Withdrawer => meta.authorized.withdrawer,
};
assert_eq!(actual_authority, new_authority.pubkey());
}
// changing withdrawer using staker fails
let instruction = ixn::authorize(
&stake,
&stakers[2].pubkey(),
&Pubkey::new_unique(),
StakeAuthorize::Withdrawer,
None,
);
let e = process_instruction(&mut context, &instruction, &vec![&stakers[2]])
.await
.unwrap_err();
assert_eq!(e, ProgramError::MissingRequiredSignature);
// changing staker using withdrawer is fine
let instruction = ixn::authorize(
&stake,
&withdrawers[2].pubkey(),
&stakers[0].pubkey(),
StakeAuthorize::Staker,
None,
);
process_instruction_test_missing_signers(&mut context, &instruction, &vec![&withdrawers[2]])
.await;
let (meta, _, _) = get_stake_account(&mut context.banks_client, &stake).await;
assert_eq!(meta.authorized.staker, stakers[0].pubkey());
// withdraw using staker fails
for staker in stakers {
let recipient = Pubkey::new_unique();
let instruction = ixn::withdraw(
&stake,
&staker.pubkey(),
&recipient,
rent_exempt_reserve,
None,
);
let e = process_instruction(&mut context, &instruction, &vec![&staker])
.await
.unwrap_err();
assert_eq!(e, ProgramError::MissingRequiredSignature);
}
}
#[tokio::test]
async fn program_test_stake_delegate() {
let mut context = program_test().start_with_context().await;
let accounts = Accounts::default();
accounts.initialize(&mut context).await;
let vote_account2 = Keypair::new();
create_vote(
&mut context,
&Keypair::new(),
&Pubkey::new_unique(),
&Pubkey::new_unique(),
&vote_account2,
)
.await;
let staker_keypair = Keypair::new();
let withdrawer_keypair = Keypair::new();
let staker = staker_keypair.pubkey();
let withdrawer = withdrawer_keypair.pubkey();
let authorized = Authorized { staker, withdrawer };
let vote_state_credits = 100;
context.increment_vote_account_credits(&accounts.vote_account.pubkey(), vote_state_credits);
let minimum_delegation = get_minimum_delegation(&mut context).await;
let stake =
create_independent_stake_account(&mut context, &authorized, minimum_delegation).await;
let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
process_instruction_test_missing_signers(&mut context, &instruction, &vec![&staker_keypair])
.await;
// verify that delegate() looks right
let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
let (_, stake_data, _) = get_stake_account(&mut context.banks_client, &stake).await;
assert_eq!(
stake_data.unwrap(),
Stake {
delegation: Delegation {
voter_pubkey: accounts.vote_account.pubkey(),
stake: minimum_delegation,
activation_epoch: clock.epoch,
deactivation_epoch: u64::MAX,
..Delegation::default()
},
credits_observed: vote_state_credits,
}
);
// verify that delegate fails as stake is active and not deactivating
advance_epoch(&mut context).await;
let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap_err();
assert_eq!(e, StakeError::TooSoonToRedelegate.into());
// deactivate
let instruction = ixn::deactivate_stake(&stake, &staker);
process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap();
// verify that delegate to a different vote account fails during deactivation
let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap_err();
assert_eq!(e, StakeError::TooSoonToRedelegate.into());
// verify that delegate succeeds to same vote account when stake is deactivating
refresh_blockhash(&mut context).await;
let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap();
// verify that deactivation has been cleared
let (_, stake_data, _) = get_stake_account(&mut context.banks_client, &stake).await;
assert_eq!(stake_data.unwrap().delegation.deactivation_epoch, u64::MAX);
// verify that delegate to a different vote account fails if stake is still
// active
let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap_err();
assert_eq!(e, StakeError::TooSoonToRedelegate.into());
// delegate still fails after stake is fully activated; redelegate is not
// supported
advance_epoch(&mut context).await;
let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap_err();
assert_eq!(e, StakeError::TooSoonToRedelegate.into());
// delegate to spoofed vote account fails (not owned by vote program)
let mut fake_vote_account =
get_account(&mut context.banks_client, &accounts.vote_account.pubkey()).await;
fake_vote_account.owner = Pubkey::new_unique();
let fake_vote_address = Pubkey::new_unique();
context.set_account(&fake_vote_address, &fake_vote_account.into());
let stake =
create_independent_stake_account(&mut context, &authorized, minimum_delegation).await;
let instruction = ixn::delegate_stake(&stake, &staker, &fake_vote_address);
let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap_err();
assert_eq!(e, ProgramError::IncorrectProgramId);
// delegate stake program-owned non-stake account fails
let rewards_pool_address = Pubkey::new_unique();
let rewards_pool = SolanaAccount {
lamports: get_stake_account_rent(&mut context.banks_client).await,
data: bincode::serialize(&StakeStateV2::RewardsPool)
.unwrap()
.to_vec(),
owner: id(),
executable: false,
rent_epoch: u64::MAX,
};
context.set_account(&rewards_pool_address, &rewards_pool.into());
let instruction = ixn::delegate_stake(
&rewards_pool_address,
&staker,
&accounts.vote_account.pubkey(),
);
let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
.await
.unwrap_err();
assert_eq!(e, ProgramError::InvalidAccountData);
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum StakeLifecycle {
Uninitialized = 0,
Initialized,
Activating,
Active,
Deactivating,
Deactive,
Closed,
}
impl StakeLifecycle {
// (stake, staker, withdrawer)
pub async fn new_stake_account(
self,
context: &mut ProgramTestContext,
vote_account: &Pubkey,
staked_amount: u64,
) -> (Keypair, Keypair, Keypair) {
let stake_keypair = Keypair::new();
let staker_keypair = Keypair::new();
let withdrawer_keypair = Keypair::new();
self.new_stake_account_fully_specified(
context,
vote_account,
staked_amount,
&stake_keypair,
&staker_keypair,
&withdrawer_keypair,
&Lockup::default(),
)
.await;
(stake_keypair, staker_keypair, withdrawer_keypair)
}
#[allow(clippy::too_many_arguments)]
pub async fn new_stake_account_fully_specified(
self,
context: &mut ProgramTestContext,
vote_account: &Pubkey,
staked_amount: u64,
stake_keypair: &Keypair,
staker_keypair: &Keypair,
withdrawer_keypair: &Keypair,
lockup: &Lockup,
) {
let is_closed = self == StakeLifecycle::Closed;
let stake =
create_blank_stake_account_from_keypair(context, stake_keypair, is_closed).await;
if staked_amount > 0 {
transfer(context, &stake, staked_amount).await;
}
if is_closed {
return;
}
let authorized = Authorized {
staker: staker_keypair.pubkey(),
withdrawer: withdrawer_keypair.pubkey(),
};
if self >= StakeLifecycle::Initialized {
let instruction = ixn::initialize(&stake, &authorized, lockup);
process_instruction(context, &instruction, NO_SIGNERS)
.await
.unwrap();
}
if self >= StakeLifecycle::Activating {
let instruction = ixn::delegate_stake(&stake, &staker_keypair.pubkey(), vote_account);
process_instruction(context, &instruction, &vec![staker_keypair])
.await
.unwrap();
}
if self >= StakeLifecycle::Active {
advance_epoch(context).await;
assert_eq!(
get_effective_stake(&mut context.banks_client, &stake).await,
staked_amount,
);
}
if self >= StakeLifecycle::Deactivating {
let instruction = ixn::deactivate_stake(&stake, &staker_keypair.pubkey());
process_instruction(context, &instruction, &vec![staker_keypair])
.await
.unwrap();
}
if self == StakeLifecycle::Deactive {
advance_epoch(context).await;
assert_eq!(
get_effective_stake(&mut context.banks_client, &stake).await,
0,
);
}
}
pub fn minimum_delegation_enforced(&self) -> bool {
match self {
Self::Activating | Self::Active | Self::Deactivating => true,
Self::Uninitialized | Self::Initialized | Self::Deactive | Self::Closed => false,
}
}
}