litesvm 0.11.0

A fast and lightweight Solana VM simulator for testing solana programs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
// ported from https://github.com/solana-program/stake/blob/main/program/tests/program_test.rs

use {
    litesvm::LiteSVM,
    solana_account::{Account, ReadableAccount, WritableAccount},
    solana_address::Address,
    solana_clock::Clock,
    solana_epoch_schedule::EpochSchedule,
    solana_hash::Hash,
    solana_instruction::Instruction,
    solana_keypair::Keypair,
    solana_program_error::{ProgramError, ProgramResult},
    solana_rent::Rent,
    solana_sdk_ids::system_program,
    solana_signer::{signers::Signers, Signer},
    solana_stake_interface::{
        self as stake,
        error::StakeError,
        instruction::{self as ixn, LockupArgs},
        state::{Authorized, Delegation, Lockup, Meta, Stake, StakeAuthorize, StakeStateV2},
    },
    solana_system_interface::instruction as system_instruction,
    solana_transaction::Transaction,
    solana_transaction_error::TransactionError,
    solana_vote_interface::{
        instruction as vote_instruction,
        state::{VoteInit, VoteStateV4, VoteStateVersions},
    },
};

// utility function, used by Stakes, tests
fn from<T: ReadableAccount>(key: &Address, account: &T) -> Option<VoteStateV4> {
    VoteStateV4::deserialize(account.data(), key).ok()
}

// utility function, used by Stakes, tests
fn to<T: WritableAccount>(versioned: &VoteStateVersions, account: &mut T) -> Option<()> {
    VoteStateV4::serialize(versioned, account.data_as_mut_slice()).ok()
}

fn increment_vote_account_credits(
    svm: &mut LiteSVM,
    vote_account_address: Address,
    number_of_credits: u64,
) {
    // generate some vote activity for rewards
    let mut vote_account = svm.get_account(&vote_account_address).unwrap();
    let mut vote_state = from(&vote_account_address, &vote_account).unwrap();

    let epoch = svm.get_sysvar::<Clock>().epoch;
    // Inlined from vote program - maximum number of epoch credits to keep in history
    const MAX_EPOCH_CREDITS_HISTORY: usize = 64;
    for _ in 0..number_of_credits {
        // Inline increment_credits logic from vote program.
        let credits = 1;

        // never seen a credit
        if vote_state.epoch_credits.is_empty() {
            vote_state.epoch_credits.push((epoch, 0, 0));
        } else if epoch != vote_state.epoch_credits.last().unwrap().0 {
            let (_, credits_val, prev_credits) = *vote_state.epoch_credits.last().unwrap();

            if credits_val != prev_credits {
                // if credits were earned previous epoch
                // append entry at end of list for the new epoch
                vote_state
                    .epoch_credits
                    .push((epoch, credits_val, credits_val));
            } else {
                // else just move the current epoch
                vote_state.epoch_credits.last_mut().unwrap().0 = epoch;
            }

            // Remove too old epoch_credits
            if vote_state.epoch_credits.len() > MAX_EPOCH_CREDITS_HISTORY {
                vote_state.epoch_credits.remove(0);
            }
        }

        vote_state.epoch_credits.last_mut().unwrap().1 = vote_state
            .epoch_credits
            .last()
            .unwrap()
            .1
            .saturating_add(credits);
    }
    let versioned = VoteStateVersions::V4(Box::new(vote_state));
    to(&versioned, &mut vote_account).unwrap();
    svm.set_account(vote_account_address, vote_account).unwrap();
}

#[derive(Debug, PartialEq)]
struct Accounts {
    pub validator: Keypair,
    pub voter: Keypair,
    pub withdrawer: Keypair,
    pub vote_account: Keypair,
}

impl Accounts {
    fn initialize(&self, svm: &mut LiteSVM, payer: &Keypair) {
        let epoch_schedule = svm.get_sysvar::<EpochSchedule>();
        let slot = epoch_schedule.first_normal_slot + 1;
        svm.warp_to_slot(slot);

        create_vote(
            svm,
            payer,
            &svm.latest_blockhash(),
            &self.validator,
            &self.voter.pubkey(),
            &self.withdrawer.pubkey(),
            &self.vote_account,
        );
    }
}

impl Default for Accounts {
    fn default() -> Self {
        let vote_account = Keypair::new();

        Self {
            validator: Keypair::new(),
            voter: Keypair::new(),
            withdrawer: Keypair::new(),
            vote_account,
        }
    }
}

fn create_vote(
    svm: &mut LiteSVM,
    payer: &Keypair,
    recent_blockhash: &Hash,
    validator: &Keypair,
    voter: &Address,
    withdrawer: &Address,
    vote_account: &Keypair,
) {
    let rent = svm.get_sysvar::<Rent>();
    let rent_voter = rent.minimum_balance(VoteStateV4::size_of());

    let mut instructions = vec![system_instruction::create_account(
        &payer.pubkey(),
        &validator.pubkey(),
        rent.minimum_balance(0),
        0,
        &system_program::id(),
    )];
    instructions.append(&mut vote_instruction::create_account_with_config(
        &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(&payer.pubkey()),
        &[validator, vote_account, payer],
        *recent_blockhash,
    );

    // ignore errors for idempotency
    let _ = svm.send_transaction(transaction);
}

fn advance_epoch(svm: &mut LiteSVM) {
    refresh_blockhash(svm);
    let old_clock = svm.get_sysvar::<Clock>();
    let root_slot = old_clock.slot;
    let slots_per_epoch = svm.get_sysvar::<EpochSchedule>().slots_per_epoch;
    svm.warp_to_slot(root_slot + slots_per_epoch);
    let mut new_clock = old_clock;
    new_clock.epoch += 1;
    svm.set_sysvar::<Clock>(&new_clock)
}

fn refresh_blockhash(svm: &mut LiteSVM) {
    svm.expire_blockhash()
}

fn get_account(svm: &mut LiteSVM, pubkey: &Address) -> Account {
    svm.get_account(pubkey).expect("account not found")
}

fn get_stake_account(svm: &mut LiteSVM, pubkey: &Address) -> (Meta, Option<Stake>, u64) {
    let stake_account = get_account(svm, pubkey);
    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!(),
    }
}

fn get_stake_account_rent(svm: &mut LiteSVM) -> u64 {
    let rent = svm.get_sysvar::<Rent>();
    rent.minimum_balance(std::mem::size_of::<stake::state::StakeStateV2>())
}

fn get_minimum_delegation(svm: &mut LiteSVM, payer: &Keypair) -> u64 {
    let transaction = Transaction::new_signed_with_payer(
        &[stake::instruction::get_minimum_delegation()],
        Some(&payer.pubkey()),
        &[&payer],
        svm.latest_blockhash(),
    );
    let mut data = svm
        .simulate_transaction(transaction)
        .unwrap()
        .meta
        .return_data
        .data;
    data.resize(8, 0);

    data.try_into().map(u64::from_le_bytes).unwrap()
}

fn create_independent_stake_account(
    svm: &mut LiteSVM,
    authorized: &Authorized,
    stake_amount: u64,
    payer: &Keypair,
) -> Address {
    create_independent_stake_account_with_lockup(
        svm,
        authorized,
        &Lockup::default(),
        stake_amount,
        payer,
    )
}

fn create_independent_stake_account_with_lockup(
    svm: &mut LiteSVM,
    authorized: &Authorized,
    lockup: &Lockup,
    stake_amount: u64,
    payer: &Keypair,
) -> Address {
    let stake = Keypair::new();
    let lamports = get_stake_account_rent(svm) + stake_amount;

    let instructions = vec![
        solana_system_interface::instruction::create_account(
            &payer.pubkey(),
            &stake.pubkey(),
            lamports,
            std::mem::size_of::<stake::state::StakeStateV2>() as u64,
            &solana_sdk_ids::stake::id(),
        ),
        stake::instruction::initialize(&stake.pubkey(), authorized, lockup),
    ];

    let transaction = Transaction::new_signed_with_payer(
        &instructions,
        Some(&payer.pubkey()),
        &[payer, &stake],
        svm.latest_blockhash(),
    );

    svm.send_transaction(transaction).unwrap();

    stake.pubkey()
}

fn create_blank_stake_account(svm: &mut LiteSVM, payer: &Keypair) -> Address {
    let stake = Keypair::new();
    create_blank_stake_account_from_keypair(svm, &stake, payer)
}

fn create_blank_stake_account_from_keypair(
    svm: &mut LiteSVM,
    stake: &Keypair,
    payer: &Keypair,
) -> Address {
    let lamports = get_stake_account_rent(svm);

    let transaction = Transaction::new_signed_with_payer(
        &[system_instruction::create_account(
            &payer.pubkey(),
            &stake.pubkey(),
            lamports,
            StakeStateV2::size_of() as u64,
            &solana_sdk_ids::stake::id(),
        )],
        Some(&payer.pubkey()),
        &[&payer, &stake],
        svm.latest_blockhash(),
    );

    svm.send_transaction(transaction).unwrap();

    stake.pubkey()
}

fn process_instruction<T: Signers + ?Sized>(
    svm: &mut LiteSVM,
    instruction: &Instruction,
    additional_signers: &T,
    payer: &Keypair,
) -> ProgramResult {
    let mut transaction =
        Transaction::new_with_payer(std::slice::from_ref(instruction), Some(&payer.pubkey()));

    transaction.partial_sign(&[&payer], svm.latest_blockhash());
    transaction.sign(additional_signers, svm.latest_blockhash());

    match svm.send_transaction(transaction) {
        Ok(_) => Ok(()),
        Err(e) => {
            // banks client error -> transaction error -> instruction error -> program error
            match e.err {
                TransactionError::InstructionError(_, e) => Err(e.try_into().unwrap()),
                TransactionError::InsufficientFundsForRent { .. } => {
                    Err(ProgramError::InsufficientFunds)
                }
                _ => panic!("couldnt convert {e:?} to ProgramError"),
            }
        }
    }
}

fn test_instruction_with_missing_signers(
    svm: &mut LiteSVM,
    instruction: &Instruction,
    additional_signers: &Vec<&Keypair>,
    payer: &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(svm, &instruction, &reduced_signers, payer).unwrap_err();
            assert_eq!(e, ProgramError::MissingRequiredSignature);
        }
    }

    // now make sure the instruction succeeds
    process_instruction(svm, instruction, additional_signers, payer).unwrap();
}

#[test]
fn test_stake_checked_instructions() {
    let mut svm = LiteSVM::new();
    let accounts = Accounts::default();
    let payer = Keypair::new();
    svm.airdrop(&payer.pubkey(), 1_000_000_000_000).unwrap();
    accounts.initialize(&mut svm, &payer);

    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 =
        Address::create_with_seed(&seed_base, seed, &system_program::id()).unwrap();

    // Test InitializeChecked with non-signing withdrawer
    let stake = create_blank_stake_account(&mut svm, &payer);
    let instruction = ixn::initialize_checked(&stake, &Authorized { staker, withdrawer });

    test_instruction_with_missing_signers(
        &mut svm,
        &instruction,
        &vec![&withdrawer_keypair],
        &payer,
    );

    // Test AuthorizeChecked with non-signing staker
    let stake =
        create_independent_stake_account(&mut svm, &Authorized { staker, withdrawer }, 0, &payer);
    let instruction =
        ixn::authorize_checked(&stake, &staker, &authorized, StakeAuthorize::Staker, None);

    test_instruction_with_missing_signers(
        &mut svm,
        &instruction,
        &vec![&staker_keypair, &authorized_keypair],
        &payer,
    );

    // Test AuthorizeChecked with non-signing withdrawer
    let stake =
        create_independent_stake_account(&mut svm, &Authorized { staker, withdrawer }, 0, &payer);
    let instruction = ixn::authorize_checked(
        &stake,
        &withdrawer,
        &authorized,
        StakeAuthorize::Withdrawer,
        None,
    );

    test_instruction_with_missing_signers(
        &mut svm,
        &instruction,
        &vec![&withdrawer_keypair, &authorized_keypair],
        &payer,
    );

    // Test AuthorizeCheckedWithSeed with non-signing authority
    for authority_type in [StakeAuthorize::Staker, StakeAuthorize::Withdrawer] {
        let stake = create_independent_stake_account(
            &mut svm,
            &Authorized::auto(&seeded_address),
            0,
            &payer,
        );
        let instruction = ixn::authorize_checked_with_seed(
            &stake,
            &seed_base,
            seed.to_string(),
            &system_program::id(),
            &authorized,
            authority_type,
            None,
        );

        test_instruction_with_missing_signers(
            &mut svm,
            &instruction,
            &vec![&seed_base_keypair, &authorized_keypair],
            &payer,
        );
    }

    // Test SetLockupChecked with non-signing lockup custodian
    let stake =
        create_independent_stake_account(&mut svm, &Authorized { staker, withdrawer }, 0, &payer);
    let instruction = ixn::set_lockup_checked(
        &stake,
        &LockupArgs {
            unix_timestamp: None,
            epoch: Some(1),
            custodian: Some(custodian),
        },
        &withdrawer,
    );

    test_instruction_with_missing_signers(
        &mut svm,
        &instruction,
        &vec![&withdrawer_keypair, &custodian_keypair],
        &payer,
    );
}

#[test]
fn test_stake_initialize() {
    let mut svm = LiteSVM::new();
    let accounts = Accounts::default();
    let payer = Keypair::new();
    svm.airdrop(&payer.pubkey(), 1_000_000_000_000).unwrap();
    accounts.initialize(&mut svm, &payer);

    let rent_exempt_reserve = get_stake_account_rent(&mut svm);
    let no_signers: [&Keypair; 0] = [];

    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 svm, &payer);
    let instruction = ixn::initialize(&stake, &authorized, &lockup);

    // should pass
    process_instruction(&mut svm, &instruction, &no_signers, &payer).unwrap();

    // check that we see what we expect
    let account = get_account(&mut svm, &stake);
    let stake_state: StakeStateV2 = bincode::deserialize(&account.data).unwrap();
    assert_eq!(
        stake_state,
        StakeStateV2::Initialized(Meta {
            authorized,
            rent_exempt_reserve,
            lockup,
        }),
    );

    // 2nd time fails, can't move it from anything other than uninit->init
    refresh_blockhash(&mut svm);
    let e = process_instruction(&mut svm, &instruction, &no_signers, &payer).unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);

    // not enough balance for rent
    let stake = Address::new_unique();
    let account = Account {
        lamports: rent_exempt_reserve / 2,
        data: vec![0; StakeStateV2::size_of()],
        owner: solana_sdk_ids::stake::id(),
        executable: false,
        rent_epoch: 1000,
    };
    svm.set_account(stake, account).unwrap();

    let instruction = ixn::initialize(&stake, &authorized, &lockup);
    let e = process_instruction(&mut svm, &instruction, &no_signers, &payer).unwrap_err();
    assert_eq!(e, ProgramError::InsufficientFunds);

    // incorrect account sizes
    let stake_keypair = Keypair::new();
    let stake = stake_keypair.pubkey();
    let payer = Keypair::new();
    svm.airdrop(&payer.pubkey(), 1_000_000_000_000).unwrap();

    let instruction = solana_system_interface::instruction::create_account(
        &payer.pubkey(),
        &stake,
        rent_exempt_reserve * 2,
        StakeStateV2::size_of() as u64 + 1,
        &solana_sdk_ids::stake::id(),
    );
    process_instruction(&mut svm, &instruction, &vec![&stake_keypair], &payer).unwrap();

    let instruction = ixn::initialize(&stake, &authorized, &lockup);
    let e = process_instruction(&mut svm, &instruction, &no_signers, &payer).unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);

    let stake_keypair = Keypair::new();
    let stake = stake_keypair.pubkey();

    let instruction = solana_system_interface::instruction::create_account(
        &payer.pubkey(),
        &stake,
        rent_exempt_reserve,
        StakeStateV2::size_of() as u64 - 1,
        &solana_sdk_ids::stake::id(),
    );
    process_instruction(&mut svm, &instruction, &vec![&stake_keypair], &payer).unwrap();

    let instruction = ixn::initialize(&stake, &authorized, &lockup);
    let e = process_instruction(&mut svm, &instruction, &no_signers, &payer).unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);
}

#[test]
fn test_authorize() {
    let mut svm = LiteSVM::new();
    let payer = Keypair::new();
    svm.airdrop(&payer.pubkey(), 1_000_000_000_000).unwrap();
    let accounts = Accounts::default();
    accounts.initialize(&mut svm, &payer);

    let rent_exempt_reserve = get_stake_account_rent(&mut svm);
    let no_signers: [&Keypair; 0] = [];

    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 svm, &stake_keypair, &payer);

    // 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 svm, &instruction, &vec![&stake_keypair], &payer).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 svm, &instruction, &no_signers, &payer).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,
        );
        test_instruction_with_missing_signers(&mut svm, &instruction, &vec![old_authority], &payer);

        let (meta, _, _) = get_stake_account(&mut svm, &stake);
        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], Address::new_unique(), StakeAuthorize::Staker),
        (
            &withdrawers[0],
            Address::new_unique(),
            StakeAuthorize::Withdrawer,
        ),
    ] {
        let instruction = ixn::authorize(
            &stake,
            &old_authority.pubkey(),
            &new_authority,
            authority_type,
            None,
        );
        let e =
            process_instruction(&mut svm, &instruction, &vec![old_authority], &payer).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,
        );
        test_instruction_with_missing_signers(&mut svm, &instruction, &vec![old_authority], &payer);

        let (meta, _, _) = get_stake_account(&mut svm, &stake);
        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(),
        &Address::new_unique(),
        StakeAuthorize::Withdrawer,
        None,
    );
    let e = process_instruction(&mut svm, &instruction, &vec![&stakers[2]], &payer).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,
    );
    test_instruction_with_missing_signers(&mut svm, &instruction, &vec![&withdrawers[2]], &payer);

    let (meta, _, _) = get_stake_account(&mut svm, &stake);
    assert_eq!(meta.authorized.staker, stakers[0].pubkey());

    // withdraw using staker fails
    for staker in stakers {
        let recipient = Address::new_unique();
        let instruction = ixn::withdraw(
            &stake,
            &staker.pubkey(),
            &recipient,
            rent_exempt_reserve,
            None,
        );
        let e = process_instruction(&mut svm, &instruction, &vec![&staker], &payer).unwrap_err();
        assert_eq!(e, ProgramError::MissingRequiredSignature);
    }
}

#[test]
#[ignore]
fn test_stake_delegate() {
    let mut svm = LiteSVM::new();
    let accounts = Accounts::default();
    let payer = Keypair::new();
    svm.airdrop(&payer.pubkey(), 1_000_000_000_000).unwrap();
    accounts.initialize(&mut svm, &payer);

    let vote_account2 = Keypair::new();
    let latest_blockhash = svm.latest_blockhash();
    create_vote(
        &mut svm,
        &payer,
        &latest_blockhash,
        &Keypair::new(),
        &Address::new_unique(),
        &Address::new_unique(),
        &vote_account2,
    );

    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;
    increment_vote_account_credits(&mut svm, accounts.vote_account.pubkey(), vote_state_credits);
    let minimum_delegation = get_minimum_delegation(&mut svm, &payer);

    let stake = create_independent_stake_account(&mut svm, &authorized, minimum_delegation, &payer);
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());

    test_instruction_with_missing_signers(&mut svm, &instruction, &vec![&staker_keypair], &payer);

    // verify that delegate() looks right
    let clock = svm.get_sysvar::<Clock>();
    let (_, stake_data, _) = get_stake_account(&mut svm, &stake);
    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 svm);
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
    let e =
        process_instruction(&mut svm, &instruction, &vec![&staker_keypair], &payer).unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());

    // deactivate
    let instruction = ixn::deactivate_stake(&stake, &staker);
    process_instruction(&mut svm, &instruction, &vec![&staker_keypair], &payer).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 svm, &instruction, &vec![&staker_keypair], &payer).unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());

    // verify that delegate succeeds to same vote account when stake is deactivating
    refresh_blockhash(&mut svm);
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
    process_instruction(&mut svm, &instruction, &vec![&staker_keypair], &payer).unwrap();

    // verify that deactivation has been cleared
    let (_, stake_data, _) = get_stake_account(&mut svm, &stake);
    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 svm, &instruction, &vec![&staker_keypair], &payer).unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());
    // delegate still fails after stake is fully activated; redelegate is not supported
    advance_epoch(&mut svm);
    let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
    let e =
        process_instruction(&mut svm, &instruction, &vec![&staker_keypair], &payer).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 svm, &accounts.vote_account.pubkey());
    fake_vote_account.owner = Address::new_unique();
    let fake_vote_address = Address::new_unique();
    svm.set_account(fake_vote_address, fake_vote_account)
        .unwrap();

    let stake = create_independent_stake_account(&mut svm, &authorized, minimum_delegation, &payer);
    let instruction = ixn::delegate_stake(&stake, &staker, &fake_vote_address);

    let e =
        process_instruction(&mut svm, &instruction, &vec![&staker_keypair], &payer).unwrap_err();
    assert_eq!(e, ProgramError::IncorrectProgramId);

    // delegate stake program-owned non-stake account fails
    let rewards_pool_address = Address::new_unique();
    let rewards_pool = Account {
        lamports: get_stake_account_rent(&mut svm),
        data: bincode::serialize(&StakeStateV2::RewardsPool)
            .unwrap()
            .to_vec(),
        owner: solana_sdk_ids::stake::id(),
        executable: false,
        rent_epoch: u64::MAX,
    };
    svm.set_account(rewards_pool_address, rewards_pool).unwrap();

    let instruction = ixn::delegate_stake(
        &rewards_pool_address,
        &staker,
        &accounts.vote_account.pubkey(),
    );

    let e =
        process_instruction(&mut svm, &instruction, &vec![&staker_keypair], &payer).unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);
}