From 5c09c765b58312b0b02f7b3bb8ae3601ecbaa63c Mon Sep 17 00:00:00 2001 From: rustopian <96253492+rustopian@users.noreply.github.com> Date: Tue, 4 Nov 2025 09:47:56 +0000 Subject: [PATCH 1/4] InstructionConfig, migrate Initialize tests --- program/tests/helpers/context.rs | 112 ++++++++ program/tests/helpers/instruction_builders.rs | 105 +++++++ program/tests/helpers/lifecycle.rs | 29 ++ program/tests/helpers/mod.rs | 7 + program/tests/helpers/utils.rs | 65 +++++ program/tests/initialize.rs | 261 ++++++++++++++++++ program/tests/program_test.rs | 121 -------- 7 files changed, 579 insertions(+), 121 deletions(-) create mode 100644 program/tests/helpers/context.rs create mode 100644 program/tests/helpers/instruction_builders.rs create mode 100644 program/tests/helpers/lifecycle.rs create mode 100644 program/tests/helpers/mod.rs create mode 100644 program/tests/helpers/utils.rs create mode 100644 program/tests/initialize.rs diff --git a/program/tests/helpers/context.rs b/program/tests/helpers/context.rs new file mode 100644 index 00000000..03713b4d --- /dev/null +++ b/program/tests/helpers/context.rs @@ -0,0 +1,112 @@ +use { + super::{ + instruction_builders::{InstructionConfig, InstructionExecution}, + lifecycle::StakeLifecycle, + utils::{add_sysvars, STAKE_RENT_EXEMPTION}, + }, + mollusk_svm::{result::Check, Mollusk}, + solana_account::AccountSharedData, + solana_instruction::Instruction, + solana_pubkey::Pubkey, + solana_stake_program::id, +}; + +/// Builder for creating stake accounts with customizable parameters +pub struct StakeAccountBuilder { + lifecycle: StakeLifecycle, +} + +impl StakeAccountBuilder { + pub fn build(self) -> (Pubkey, AccountSharedData) { + let stake_pubkey = Pubkey::new_unique(); + let account = self.lifecycle.create_uninitialized_account(); + (stake_pubkey, account) + } +} + +/// Consolidated test context for stake account tests +pub struct StakeTestContext { + pub mollusk: Mollusk, + pub rent_exempt_reserve: u64, + pub staker: Pubkey, + pub withdrawer: Pubkey, +} + +impl StakeTestContext { + /// Create a new test context with all standard setup + pub fn new() -> Self { + let mollusk = Mollusk::new(&id(), "solana_stake_program"); + + Self { + mollusk, + rent_exempt_reserve: STAKE_RENT_EXEMPTION, + staker: Pubkey::new_unique(), + withdrawer: Pubkey::new_unique(), + } + } + + /// Create a stake account builder for the specified lifecycle stage + /// + /// Example: + /// ``` + /// let (stake, account) = ctx + /// .stake_account(StakeLifecycle::Uninitialized) + /// .build(); + /// ``` + pub fn stake_account(&mut self, lifecycle: StakeLifecycle) -> StakeAccountBuilder { + StakeAccountBuilder { lifecycle } + } + + /// Process an instruction + pub fn process_with<'b, C: InstructionConfig>( + &self, + config: C, + ) -> InstructionExecution<'_, 'b> { + InstructionExecution::new( + config.build_instruction(self), + config.build_accounts(), + self, + ) + } + + /// Process an instruction with optional missing signer testing + pub(crate) fn process_instruction_maybe_test_signers( + &self, + instruction: &Instruction, + accounts: Vec<(Pubkey, AccountSharedData)>, + checks: &[Check], + test_missing_signers: bool, + ) -> mollusk_svm::result::InstructionResult { + if test_missing_signers { + use solana_program_error::ProgramError; + + // Test that removing each signer causes failure + for i in 0..instruction.accounts.len() { + if instruction.accounts[i].is_signer { + let mut modified_instruction = instruction.clone(); + modified_instruction.accounts[i].is_signer = false; + + let accounts_with_sysvars = + add_sysvars(&self.mollusk, &modified_instruction, accounts.clone()); + + self.mollusk.process_and_validate_instruction( + &modified_instruction, + &accounts_with_sysvars, + &[Check::err(ProgramError::MissingRequiredSignature)], + ); + } + } + } + + // Process with all signers present + let accounts_with_sysvars = add_sysvars(&self.mollusk, instruction, accounts); + self.mollusk + .process_and_validate_instruction(instruction, &accounts_with_sysvars, checks) + } +} + +impl Default for StakeTestContext { + fn default() -> Self { + Self::new() + } +} diff --git a/program/tests/helpers/instruction_builders.rs b/program/tests/helpers/instruction_builders.rs new file mode 100644 index 00000000..515a72a0 --- /dev/null +++ b/program/tests/helpers/instruction_builders.rs @@ -0,0 +1,105 @@ +use { + super::context::StakeTestContext, + mollusk_svm::result::Check, + solana_account::AccountSharedData, + solana_instruction::Instruction, + solana_pubkey::Pubkey, + solana_stake_interface::{ + instruction as ixn, + state::{Authorized, Lockup}, + }, +}; + +// Trait for instruction configuration that builds instruction and accounts +pub trait InstructionConfig { + fn build_instruction(&self, ctx: &StakeTestContext) -> Instruction; + fn build_accounts(&self) -> Vec<(Pubkey, AccountSharedData)>; +} + +/// Execution builder with validation and signer testing +pub struct InstructionExecution<'a, 'b> { + instruction: Instruction, + accounts: Vec<(Pubkey, AccountSharedData)>, + ctx: &'a StakeTestContext, + checks: Option<&'b [Check<'b>]>, + test_missing_signers: Option, // `None` runs if `Check::success` +} + +impl<'b> InstructionExecution<'_, 'b> { + pub fn checks(mut self, checks: &'b [Check<'b>]) -> Self { + self.checks = Some(checks); + self + } + + pub fn test_missing_signers(mut self, test: bool) -> Self { + self.test_missing_signers = Some(test); + self + } + + /// Executes the instruction. If `checks` is `None` or empty, uses `Check::success()`. + /// Fail-safe default: when `test_missing_signers` is `None`, runs the missing-signers + /// test (`true`). Callers must explicitly opt out with `.test_missing_signers(false)`. + pub fn execute(self) -> mollusk_svm::result::InstructionResult { + let default_checks = [Check::success()]; + let checks = match self.checks { + Some(c) if !c.is_empty() => c, + _ => &default_checks, + }; + + let test_missing_signers = self.test_missing_signers.unwrap_or(true); + + self.ctx.process_instruction_maybe_test_signers( + &self.instruction, + self.accounts, + checks, + test_missing_signers, + ) + } +} + +impl<'a> InstructionExecution<'a, '_> { + pub(crate) fn new( + instruction: Instruction, + accounts: Vec<(Pubkey, AccountSharedData)>, + ctx: &'a StakeTestContext, + ) -> Self { + Self { + instruction, + accounts, + ctx, + checks: None, + test_missing_signers: None, + } + } +} + +pub struct InitializeConfig<'a> { + pub stake: (&'a Pubkey, &'a AccountSharedData), + pub authorized: &'a Authorized, + pub lockup: &'a Lockup, +} + +impl InstructionConfig for InitializeConfig<'_> { + fn build_instruction(&self, _ctx: &StakeTestContext) -> Instruction { + ixn::initialize(self.stake.0, self.authorized, self.lockup) + } + + fn build_accounts(&self) -> Vec<(Pubkey, AccountSharedData)> { + vec![(*self.stake.0, self.stake.1.clone())] + } +} + +pub struct InitializeCheckedConfig<'a> { + pub stake: (&'a Pubkey, &'a AccountSharedData), + pub authorized: &'a Authorized, +} + +impl InstructionConfig for InitializeCheckedConfig<'_> { + fn build_instruction(&self, _ctx: &StakeTestContext) -> Instruction { + ixn::initialize_checked(self.stake.0, self.authorized) + } + + fn build_accounts(&self) -> Vec<(Pubkey, AccountSharedData)> { + vec![(*self.stake.0, self.stake.1.clone())] + } +} diff --git a/program/tests/helpers/lifecycle.rs b/program/tests/helpers/lifecycle.rs new file mode 100644 index 00000000..74e55285 --- /dev/null +++ b/program/tests/helpers/lifecycle.rs @@ -0,0 +1,29 @@ +use { + super::utils::STAKE_RENT_EXEMPTION, solana_account::AccountSharedData, + solana_stake_interface::state::StakeStateV2, solana_stake_program::id, +}; + +/// Lifecycle states for stake accounts in tests +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum StakeLifecycle { + Uninitialized = 0, + Initialized, + Activating, + Active, + Deactivating, + Deactive, + Closed, +} + +impl StakeLifecycle { + /// Create an uninitialized stake account + pub fn create_uninitialized_account(self) -> AccountSharedData { + AccountSharedData::new_data_with_space( + STAKE_RENT_EXEMPTION, + &StakeStateV2::Uninitialized, + StakeStateV2::size_of(), + &id(), + ) + .unwrap() + } +} diff --git a/program/tests/helpers/mod.rs b/program/tests/helpers/mod.rs new file mode 100644 index 00000000..ff09b000 --- /dev/null +++ b/program/tests/helpers/mod.rs @@ -0,0 +1,7 @@ +#![allow(clippy::arithmetic_side_effects)] +#![allow(dead_code)] + +pub mod context; +pub mod instruction_builders; +pub mod lifecycle; +pub mod utils; diff --git a/program/tests/helpers/utils.rs b/program/tests/helpers/utils.rs new file mode 100644 index 00000000..3bc0659b --- /dev/null +++ b/program/tests/helpers/utils.rs @@ -0,0 +1,65 @@ +use { + mollusk_svm::Mollusk, + solana_account::{Account, AccountSharedData}, + solana_instruction::Instruction, + solana_pubkey::Pubkey, + solana_rent::Rent, + solana_stake_interface::{stake_history::StakeHistory, state::StakeStateV2}, + solana_sysvar_id::SysvarId, + std::collections::HashMap, +}; + +// hardcoded for convenience +pub const STAKE_RENT_EXEMPTION: u64 = 2_282_880; + +#[test] +fn assert_stake_rent_exemption() { + assert_eq!( + Rent::default().minimum_balance(StakeStateV2::size_of()), + STAKE_RENT_EXEMPTION + ); +} + +/// Resolve all accounts for an instruction, including sysvars and instruction accounts +/// +/// This function re-serializes the stake history sysvar from mollusk.sysvars.stake_history +/// every time it's called, ensuring that any updates to the stake history are reflected in the accounts. +pub fn add_sysvars( + mollusk: &Mollusk, + instruction: &Instruction, + accounts: Vec<(Pubkey, AccountSharedData)>, +) -> Vec<(Pubkey, Account)> { + // Build a map of provided accounts + let mut account_map: HashMap = accounts + .into_iter() + .map(|(pk, acc)| (pk, acc.into())) + .collect(); + + // Now resolve all accounts from the instruction + let mut result = Vec::new(); + for account_meta in &instruction.accounts { + let key = account_meta.pubkey; + let account = if let Some(acc) = account_map.remove(&key) { + // Use the provided account + acc + } else if Rent::check_id(&key) { + mollusk.sysvars.keyed_account_for_rent_sysvar().1 + } else if solana_clock::Clock::check_id(&key) { + mollusk.sysvars.keyed_account_for_clock_sysvar().1 + } else if solana_epoch_schedule::EpochSchedule::check_id(&key) { + mollusk.sysvars.keyed_account_for_epoch_schedule_sysvar().1 + } else if solana_epoch_rewards::EpochRewards::check_id(&key) { + mollusk.sysvars.keyed_account_for_epoch_rewards_sysvar().1 + } else if StakeHistory::check_id(&key) { + // Re-serialize stake history from mollusk.sysvars.stake_history + mollusk.sysvars.keyed_account_for_stake_history_sysvar().1 + } else { + // Default empty account + Account::default() + }; + + result.push((key, account)); + } + + result +} diff --git a/program/tests/initialize.rs b/program/tests/initialize.rs new file mode 100644 index 00000000..28e189f9 --- /dev/null +++ b/program/tests/initialize.rs @@ -0,0 +1,261 @@ +#![allow(clippy::arithmetic_side_effects)] + +mod helpers; + +use { + helpers::{ + context::StakeTestContext, + instruction_builders::{InitializeCheckedConfig, InitializeConfig}, + lifecycle::StakeLifecycle, + }, + mollusk_svm::result::Check, + solana_account::{AccountSharedData, ReadableAccount}, + solana_program_error::ProgramError, + solana_pubkey::Pubkey, + solana_rent::Rent, + solana_stake_interface::state::{Authorized, Lockup, StakeStateV2}, + solana_stake_program::id, + test_case::test_case, +}; + +#[derive(Debug, Clone, Copy)] +enum InitializeVariant { + Initialize, + InitializeChecked, +} + +#[test_case(InitializeVariant::Initialize; "initialize")] +#[test_case(InitializeVariant::InitializeChecked; "initialize_checked")] +fn test_initialize(variant: InitializeVariant) { + let mut ctx = StakeTestContext::new(); + + let custodian = Pubkey::new_unique(); + + let authorized = Authorized { + staker: ctx.staker, + withdrawer: ctx.withdrawer, + }; + + // InitializeChecked always uses default lockup + let lockup = match variant { + InitializeVariant::Initialize => Lockup { + epoch: 1, + unix_timestamp: 0, + custodian, + }, + InitializeVariant::InitializeChecked => Lockup::default(), + }; + + // Create an uninitialized stake account + let (stake, stake_account) = ctx.stake_account(StakeLifecycle::Uninitialized).build(); + + // Process the Initialize instruction, including testing missing signers + let result = { + let program_id = id(); + let checks = [ + Check::success(), + Check::all_rent_exempt(), + Check::account(&stake) + .lamports(ctx.rent_exempt_reserve) + .owner(&program_id) + .space(StakeStateV2::size_of()) + .build(), + ]; + + let processor = match variant { + InitializeVariant::Initialize => ctx.process_with(InitializeConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + lockup: &lockup, + }), + InitializeVariant::InitializeChecked => ctx.process_with(InitializeCheckedConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + }), + }; + + processor + .checks(&checks) + .test_missing_signers(true) + .execute() + }; + + // Check that we see what we expect + let resulting_account: AccountSharedData = result.resulting_accounts[0].1.clone().into(); + let stake_state: StakeStateV2 = bincode::deserialize(resulting_account.data()).unwrap(); + assert_eq!( + stake_state, + StakeStateV2::Initialized(solana_stake_interface::state::Meta { + authorized, + rent_exempt_reserve: ctx.rent_exempt_reserve, + lockup, + }), + ); + + // Attempting to initialize an already initialized stake account should fail + let processor = match variant { + InitializeVariant::Initialize => ctx.process_with(InitializeConfig { + stake: (&stake, &resulting_account), + authorized: &authorized, + lockup: &lockup, + }), + InitializeVariant::InitializeChecked => ctx.process_with(InitializeCheckedConfig { + stake: (&stake, &resulting_account), + authorized: &authorized, + }), + }; + + processor + .checks(&[Check::err(ProgramError::InvalidAccountData)]) + .test_missing_signers(false) + .execute(); +} + +#[test_case(InitializeVariant::Initialize; "initialize")] +#[test_case(InitializeVariant::InitializeChecked; "initialize_checked")] +fn test_initialize_insufficient_funds(variant: InitializeVariant) { + let ctx = StakeTestContext::new(); + + let custodian = Pubkey::new_unique(); + let authorized = Authorized { + staker: ctx.staker, + withdrawer: ctx.withdrawer, + }; + let lockup = match variant { + InitializeVariant::Initialize => Lockup { + epoch: 1, + unix_timestamp: 0, + custodian, + }, + InitializeVariant::InitializeChecked => Lockup::default(), + }; + + // Create account with insufficient lamports (need to manually create since builder adds rent automatically) + let stake = Pubkey::new_unique(); + let stake_account = AccountSharedData::new_data_with_space( + ctx.rent_exempt_reserve / 2, // Not enough lamports + &StakeStateV2::Uninitialized, + StakeStateV2::size_of(), + &id(), + ) + .unwrap(); + + let processor = match variant { + InitializeVariant::Initialize => ctx.process_with(InitializeConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + lockup: &lockup, + }), + InitializeVariant::InitializeChecked => ctx.process_with(InitializeCheckedConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + }), + }; + + processor + .checks(&[Check::err(ProgramError::InsufficientFunds)]) + .test_missing_signers(false) + .execute(); +} + +#[test_case(InitializeVariant::Initialize; "initialize")] +#[test_case(InitializeVariant::InitializeChecked; "initialize_checked")] +fn test_initialize_incorrect_size_larger(variant: InitializeVariant) { + let ctx = StakeTestContext::new(); + + // Original program_test.rs uses double rent instead of just + // increasing the size by 1. This behavior remains (makes no difference here). + let rent_exempt_reserve = Rent::default().minimum_balance(StakeStateV2::size_of() * 2); + + let custodian = Pubkey::new_unique(); + let authorized = Authorized { + staker: ctx.staker, + withdrawer: ctx.withdrawer, + }; + let lockup = match variant { + InitializeVariant::Initialize => Lockup { + epoch: 1, + unix_timestamp: 0, + custodian, + }, + InitializeVariant::InitializeChecked => Lockup::default(), + }; + + // Create account with wrong size (need to manually create since builder enforces correct size) + let stake = Pubkey::new_unique(); + let stake_account = AccountSharedData::new_data_with_space( + rent_exempt_reserve, + &StakeStateV2::Uninitialized, + StakeStateV2::size_of() + 1, // Too large + &id(), + ) + .unwrap(); + + let processor = match variant { + InitializeVariant::Initialize => ctx.process_with(InitializeConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + lockup: &lockup, + }), + InitializeVariant::InitializeChecked => ctx.process_with(InitializeCheckedConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + }), + }; + + processor + .checks(&[Check::err(ProgramError::InvalidAccountData)]) + .test_missing_signers(false) + .execute(); +} + +#[test_case(InitializeVariant::Initialize; "initialize")] +#[test_case(InitializeVariant::InitializeChecked; "initialize_checked")] +fn test_initialize_incorrect_size_smaller(variant: InitializeVariant) { + let ctx = StakeTestContext::new(); + + // Original program_test.rs uses rent for size instead of + // rent for size - 1. This behavior remains (makes no difference here). + let rent_exempt_reserve = Rent::default().minimum_balance(StakeStateV2::size_of()); + + let custodian = Pubkey::new_unique(); + let authorized = Authorized { + staker: ctx.staker, + withdrawer: ctx.withdrawer, + }; + let lockup = match variant { + InitializeVariant::Initialize => Lockup { + epoch: 1, + unix_timestamp: 0, + custodian, + }, + InitializeVariant::InitializeChecked => Lockup::default(), + }; + + // Create account with wrong size (need to manually create since builder enforces correct size) + let stake = Pubkey::new_unique(); + let stake_account = AccountSharedData::new_data_with_space( + rent_exempt_reserve, + &StakeStateV2::Uninitialized, + StakeStateV2::size_of() - 1, // Too small + &id(), + ) + .unwrap(); + + let processor = match variant { + InitializeVariant::Initialize => ctx.process_with(InitializeConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + lockup: &lockup, + }), + InitializeVariant::InitializeChecked => ctx.process_with(InitializeCheckedConfig { + stake: (&stake, &stake_account), + authorized: &authorized, + }), + }; + + processor + .checks(&[Check::err(ProgramError::InvalidAccountData)]) + .test_missing_signers(false) + .execute(); +} diff --git a/program/tests/program_test.rs b/program/tests/program_test.rs index e1988c7a..4f146806 100644 --- a/program/tests/program_test.rs +++ b/program/tests/program_test.rs @@ -396,17 +396,6 @@ async fn program_test_stake_checked_instructions() { 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; @@ -482,116 +471,6 @@ async fn program_test_stake_checked_instructions() { .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, - 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; From c2acd676d76c84d4be5b9bdbfbb6b85543197ac8 Mon Sep 17 00:00:00 2001 From: rustopian <96253492+rustopian@users.noreply.github.com> Date: Tue, 4 Nov 2025 11:41:55 +0000 Subject: [PATCH 2/4] tweaks --- program/tests/initialize.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/program/tests/initialize.rs b/program/tests/initialize.rs index 28e189f9..75187774 100644 --- a/program/tests/initialize.rs +++ b/program/tests/initialize.rs @@ -46,7 +46,6 @@ fn test_initialize(variant: InitializeVariant) { InitializeVariant::InitializeChecked => Lockup::default(), }; - // Create an uninitialized stake account let (stake, stake_account) = ctx.stake_account(StakeLifecycle::Uninitialized).build(); // Process the Initialize instruction, including testing missing signers @@ -130,7 +129,7 @@ fn test_initialize_insufficient_funds(variant: InitializeVariant) { InitializeVariant::InitializeChecked => Lockup::default(), }; - // Create account with insufficient lamports (need to manually create since builder adds rent automatically) + // Create account with insufficient lamports (manually since builder adds rent automatically) let stake = Pubkey::new_unique(); let stake_account = AccountSharedData::new_data_with_space( ctx.rent_exempt_reserve / 2, // Not enough lamports @@ -163,8 +162,6 @@ fn test_initialize_insufficient_funds(variant: InitializeVariant) { fn test_initialize_incorrect_size_larger(variant: InitializeVariant) { let ctx = StakeTestContext::new(); - // Original program_test.rs uses double rent instead of just - // increasing the size by 1. This behavior remains (makes no difference here). let rent_exempt_reserve = Rent::default().minimum_balance(StakeStateV2::size_of() * 2); let custodian = Pubkey::new_unique(); @@ -214,8 +211,6 @@ fn test_initialize_incorrect_size_larger(variant: InitializeVariant) { fn test_initialize_incorrect_size_smaller(variant: InitializeVariant) { let ctx = StakeTestContext::new(); - // Original program_test.rs uses rent for size instead of - // rent for size - 1. This behavior remains (makes no difference here). let rent_exempt_reserve = Rent::default().minimum_balance(StakeStateV2::size_of()); let custodian = Pubkey::new_unique(); From 14294e284e33c56c6714a1b4d7f2b1ddb342bc96 Mon Sep 17 00:00:00 2001 From: rustopian <96253492+rustopian@users.noreply.github.com> Date: Tue, 4 Nov 2025 11:43:26 +0000 Subject: [PATCH 3/4] migrate Deactivate tests --- Cargo.lock | 1 + program/Cargo.toml | 1 + program/tests/deactivate.rs | 115 ++++++++++++++ program/tests/helpers/context.rs | 132 ++++++++++++++-- program/tests/helpers/instruction_builders.rs | 39 ++++- program/tests/helpers/lifecycle.rs | 147 ++++++++++++++++-- program/tests/helpers/utils.rs | 31 +++- program/tests/program_test.rs | 75 --------- 8 files changed, 442 insertions(+), 99 deletions(-) create mode 100644 program/tests/deactivate.rs diff --git a/Cargo.lock b/Cargo.lock index 2876dd23..eed57071 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7214,6 +7214,7 @@ dependencies = [ "solana-transaction", "solana-vote-interface 4.0.4", "test-case", + "tokio", ] [[package]] diff --git a/program/Cargo.toml b/program/Cargo.toml index e47d083b..96c4346c 100644 --- a/program/Cargo.toml +++ b/program/Cargo.toml @@ -45,6 +45,7 @@ solana-system-interface = { version = "2.0.0", features = ["bincode"] } solana-sysvar-id = "3.0.0" solana-transaction = "3.0.0" test-case = "3.3.1" +tokio = "1" [lib] crate-type = ["cdylib", "lib"] diff --git a/program/tests/deactivate.rs b/program/tests/deactivate.rs new file mode 100644 index 00000000..980edaab --- /dev/null +++ b/program/tests/deactivate.rs @@ -0,0 +1,115 @@ +#![allow(clippy::arithmetic_side_effects)] + +mod helpers; + +use { + helpers::{ + context::StakeTestContext, + instruction_builders::{DeactivateConfig, DelegateConfig}, + lifecycle::StakeLifecycle, + utils::parse_stake_account, + }, + mollusk_svm::result::Check, + solana_program_error::ProgramError, + solana_stake_interface::{error::StakeError, state::StakeStateV2}, + solana_stake_program::id, + test_case::test_case, +}; + +#[test_case(false; "activating")] +#[test_case(true; "active")] +fn test_deactivate(activate: bool) { + let mut ctx = StakeTestContext::with_delegation(); + let min_delegation = ctx.minimum_delegation.unwrap(); + + let (stake, mut stake_account) = ctx + .stake_account(StakeLifecycle::Initialized) + .staked_amount(min_delegation) + .build(); + + // Deactivating an undelegated account fails + ctx.process_with(DeactivateConfig { + stake: (&stake, &stake_account), + override_signer: None, + }) + .checks(&[Check::err(ProgramError::InvalidAccountData)]) + .test_missing_signers(false) + .execute(); + + // Delegate + let result = ctx + .process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: ( + ctx.vote_account.as_ref().unwrap(), + ctx.vote_account_data.as_ref().unwrap(), + ), + }) + .execute(); + stake_account = result.resulting_accounts[0].1.clone().into(); + + if activate { + // Advance epoch to activate + let current_slot = ctx.mollusk.sysvars.clock.slot; + let slots_per_epoch = ctx.mollusk.sysvars.epoch_schedule.slots_per_epoch; + ctx.mollusk.warp_to_slot(current_slot + slots_per_epoch); + } + + // Deactivate with withdrawer fails + ctx.process_with(DeactivateConfig { + stake: (&stake, &stake_account), + override_signer: Some(&ctx.withdrawer), + }) + .checks(&[Check::err(ProgramError::MissingRequiredSignature)]) + .test_missing_signers(false) + .execute(); + + // Deactivate succeeds + let result = ctx + .process_with(DeactivateConfig { + stake: (&stake, &stake_account), + override_signer: None, + }) + .checks(&[ + Check::success(), + Check::all_rent_exempt(), + Check::account(&stake) + .lamports(ctx.rent_exempt_reserve + min_delegation) + .owner(&id()) + .space(StakeStateV2::size_of()) + .build(), + ]) + .test_missing_signers(true) + .execute(); + stake_account = result.resulting_accounts[0].1.clone().into(); + + let clock = ctx.mollusk.sysvars.clock.clone(); + let (_, stake_data, _) = parse_stake_account(&stake_account); + assert_eq!( + stake_data.unwrap().delegation.deactivation_epoch, + clock.epoch + ); + + // Deactivate again fails + ctx.process_with(DeactivateConfig { + stake: (&stake, &stake_account), + override_signer: None, + }) + .checks(&[Check::err(StakeError::AlreadyDeactivated.into())]) + .test_missing_signers(false) + .execute(); + + // Advance epoch + let current_slot = ctx.mollusk.sysvars.clock.slot; + let slots_per_epoch = ctx.mollusk.sysvars.epoch_schedule.slots_per_epoch; + ctx.mollusk.warp_to_slot(current_slot + slots_per_epoch); + + // Deactivate again still fails + ctx.process_with(DeactivateConfig { + stake: (&stake, &stake_account), + override_signer: None, + }) + .checks(&[Check::err(StakeError::AlreadyDeactivated.into())]) + .test_missing_signers(false) + .execute(); +} diff --git a/program/tests/helpers/context.rs b/program/tests/helpers/context.rs index 03713b4d..d0c44350 100644 --- a/program/tests/helpers/context.rs +++ b/program/tests/helpers/context.rs @@ -2,62 +2,172 @@ use { super::{ instruction_builders::{InstructionConfig, InstructionExecution}, lifecycle::StakeLifecycle, - utils::{add_sysvars, STAKE_RENT_EXEMPTION}, + utils::{add_sysvars, create_vote_account, STAKE_RENT_EXEMPTION}, }, mollusk_svm::{result::Check, Mollusk}, solana_account::AccountSharedData, solana_instruction::Instruction, solana_pubkey::Pubkey, + solana_stake_interface::state::Lockup, solana_stake_program::id, }; /// Builder for creating stake accounts with customizable parameters -pub struct StakeAccountBuilder { +pub struct StakeAccountBuilder<'a> { + ctx: &'a mut StakeTestContext, lifecycle: StakeLifecycle, + staked_amount: u64, + stake_authority: Option, + withdraw_authority: Option, + lockup: Option, + vote_account: Option, + stake_pubkey: Option, } -impl StakeAccountBuilder { +impl StakeAccountBuilder<'_> { + /// Set the staked amount (lamports delegated to validator) + pub fn staked_amount(mut self, amount: u64) -> Self { + self.staked_amount = amount; + self + } + + /// Set a custom stake authority (defaults to ctx.staker) + pub fn stake_authority(mut self, authority: &Pubkey) -> Self { + self.stake_authority = Some(*authority); + self + } + + /// Set a custom withdraw authority (defaults to ctx.withdrawer) + pub fn withdraw_authority(mut self, authority: &Pubkey) -> Self { + self.withdraw_authority = Some(*authority); + self + } + + /// Set a custom lockup (defaults to Lockup::default()) + pub fn lockup(mut self, lockup: &Lockup) -> Self { + self.lockup = Some(*lockup); + self + } + + /// Set a custom vote account (defaults to ctx.vote_account) + pub fn vote_account(mut self, vote_account: &Pubkey) -> Self { + self.vote_account = Some(*vote_account); + self + } + + /// Set a specific stake account pubkey (defaults to Pubkey::new_unique()) + pub fn stake_pubkey(mut self, pubkey: &Pubkey) -> Self { + self.stake_pubkey = Some(*pubkey); + self + } + + /// Build the stake account and return (pubkey, account_data) pub fn build(self) -> (Pubkey, AccountSharedData) { - let stake_pubkey = Pubkey::new_unique(); - let account = self.lifecycle.create_uninitialized_account(); + let stake_pubkey = self.stake_pubkey.unwrap_or_else(Pubkey::new_unique); + let account = self.lifecycle.create_stake_account_fully_specified( + &mut self.ctx.mollusk, + &stake_pubkey, + self.vote_account.as_ref().unwrap_or( + self.ctx + .vote_account + .as_ref() + .expect("vote_account required for this lifecycle"), + ), + self.staked_amount, + self.stake_authority.as_ref().unwrap_or(&self.ctx.staker), + self.withdraw_authority + .as_ref() + .unwrap_or(&self.ctx.withdrawer), + self.lockup.as_ref().unwrap_or(&Lockup::default()), + ); (stake_pubkey, account) } } -/// Consolidated test context for stake account tests pub struct StakeTestContext { pub mollusk: Mollusk, pub rent_exempt_reserve: u64, pub staker: Pubkey, pub withdrawer: Pubkey, + pub minimum_delegation: Option, + pub vote_account: Option, + pub vote_account_data: Option, } impl StakeTestContext { - /// Create a new test context with all standard setup - pub fn new() -> Self { + pub fn minimal() -> Self { let mollusk = Mollusk::new(&id(), "solana_stake_program"); + Self { + mollusk, + rent_exempt_reserve: STAKE_RENT_EXEMPTION, + staker: Pubkey::new_unique(), + withdrawer: Pubkey::new_unique(), + minimum_delegation: None, + vote_account: None, + vote_account_data: None, + } + } + pub fn with_delegation() -> Self { + let mollusk = Mollusk::new(&id(), "solana_stake_program"); + let minimum_delegation = solana_stake_program::get_minimum_delegation(); Self { mollusk, rent_exempt_reserve: STAKE_RENT_EXEMPTION, staker: Pubkey::new_unique(), withdrawer: Pubkey::new_unique(), + minimum_delegation: Some(minimum_delegation), + vote_account: Some(Pubkey::new_unique()), + vote_account_data: Some(create_vote_account()), } } + pub fn new() -> Self { + Self::with_delegation() + } + /// Create a stake account builder for the specified lifecycle stage /// /// Example: /// ``` /// let (stake, account) = ctx - /// .stake_account(StakeLifecycle::Uninitialized) + /// .stake_account(StakeLifecycle::Active) + /// .staked_amount(1_000_000) /// .build(); /// ``` pub fn stake_account(&mut self, lifecycle: StakeLifecycle) -> StakeAccountBuilder { - StakeAccountBuilder { lifecycle } + StakeAccountBuilder { + ctx: self, + lifecycle, + staked_amount: 0, + stake_authority: None, + withdraw_authority: None, + lockup: None, + vote_account: None, + stake_pubkey: None, + } + } + + /// Create a lockup that expires in the future + pub fn create_future_lockup(&self, epochs_ahead: u64) -> Lockup { + Lockup { + unix_timestamp: 0, + epoch: self.mollusk.sysvars.clock.epoch + epochs_ahead, + custodian: Pubkey::new_unique(), + } + } + + /// Create a lockup that's currently in force (far future) + pub fn create_in_force_lockup(&self) -> Lockup { + self.create_future_lockup(1_000_000) + } + + /// Create a second vote account (for testing different vote accounts) + pub fn create_second_vote_account(&self) -> (Pubkey, AccountSharedData) { + (Pubkey::new_unique(), create_vote_account()) } - /// Process an instruction + /// Process an instruction with a config-based approach pub fn process_with<'b, C: InstructionConfig>( &self, config: C, diff --git a/program/tests/helpers/instruction_builders.rs b/program/tests/helpers/instruction_builders.rs index 515a72a0..cc700115 100644 --- a/program/tests/helpers/instruction_builders.rs +++ b/program/tests/helpers/instruction_builders.rs @@ -37,8 +37,8 @@ impl<'b> InstructionExecution<'_, 'b> { } /// Executes the instruction. If `checks` is `None` or empty, uses `Check::success()`. - /// Fail-safe default: when `test_missing_signers` is `None`, runs the missing-signers - /// test (`true`). Callers must explicitly opt out with `.test_missing_signers(false)`. + /// When `test_missing_signers` is `None`, runs the missing-signers tests. + /// Callers must explicitly opt out with `.test_missing_signers(false)`. pub fn execute(self) -> mollusk_svm::result::InstructionResult { let default_checks = [Check::success()]; let checks = match self.checks { @@ -103,3 +103,38 @@ impl InstructionConfig for InitializeCheckedConfig<'_> { vec![(*self.stake.0, self.stake.1.clone())] } } + +pub struct DeactivateConfig<'a> { + pub stake: (&'a Pubkey, &'a AccountSharedData), + /// Override signer for testing wrong signer scenarios (defaults to ctx.staker) + pub override_signer: Option<&'a Pubkey>, +} + +impl InstructionConfig for DeactivateConfig<'_> { + fn build_instruction(&self, ctx: &StakeTestContext) -> Instruction { + let signer = self.override_signer.unwrap_or(&ctx.staker); + ixn::deactivate_stake(self.stake.0, signer) + } + + fn build_accounts(&self) -> Vec<(Pubkey, AccountSharedData)> { + vec![(*self.stake.0, self.stake.1.clone())] + } +} + +pub struct DelegateConfig<'a> { + pub stake: (&'a Pubkey, &'a AccountSharedData), + pub vote: (&'a Pubkey, &'a AccountSharedData), +} + +impl InstructionConfig for DelegateConfig<'_> { + fn build_instruction(&self, ctx: &StakeTestContext) -> Instruction { + ixn::delegate_stake(self.stake.0, &ctx.staker, self.vote.0) + } + + fn build_accounts(&self) -> Vec<(Pubkey, AccountSharedData)> { + vec![ + (*self.stake.0, self.stake.1.clone()), + (*self.vote.0, self.vote.1.clone()), + ] + } +} diff --git a/program/tests/helpers/lifecycle.rs b/program/tests/helpers/lifecycle.rs index 74e55285..e094c96f 100644 --- a/program/tests/helpers/lifecycle.rs +++ b/program/tests/helpers/lifecycle.rs @@ -1,6 +1,13 @@ use { - super::utils::STAKE_RENT_EXEMPTION, solana_account::AccountSharedData, - solana_stake_interface::state::StakeStateV2, solana_stake_program::id, + super::utils::{add_sysvars, create_vote_account, STAKE_RENT_EXEMPTION}, + mollusk_svm::Mollusk, + solana_account::{Account, AccountSharedData, WritableAccount}, + solana_pubkey::Pubkey, + solana_stake_interface::{ + instruction as ixn, + state::{Authorized, Lockup, StakeStateV2}, + }, + solana_stake_program::id, }; /// Lifecycle states for stake accounts in tests @@ -16,14 +23,134 @@ pub enum StakeLifecycle { } impl StakeLifecycle { - /// Create an uninitialized stake account - pub fn create_uninitialized_account(self) -> AccountSharedData { - AccountSharedData::new_data_with_space( - STAKE_RENT_EXEMPTION, - &StakeStateV2::Uninitialized, - StakeStateV2::size_of(), - &id(), + /// Create a stake account with full specification of authorities and lockup + #[allow(clippy::too_many_arguments)] + pub fn create_stake_account_fully_specified( + self, + mollusk: &mut Mollusk, + // tracker: &mut StakeTracker, // added in subsequent PR + stake_pubkey: &Pubkey, + vote_account: &Pubkey, + staked_amount: u64, + staker: &Pubkey, + withdrawer: &Pubkey, + lockup: &Lockup, + ) -> AccountSharedData { + let is_closed = self == StakeLifecycle::Closed; + + // Create base account + let mut stake_account = if is_closed { + let mut account = Account::create(STAKE_RENT_EXEMPTION, vec![], id(), false, u64::MAX); + // Add staked_amount even for closed accounts (matches program-test behavior) + if staked_amount > 0 { + account.lamports += staked_amount; + } + account.into() + } else { + Account::create( + STAKE_RENT_EXEMPTION + staked_amount, + vec![0; StakeStateV2::size_of()], + id(), + false, + u64::MAX, + ) + .into() + }; + + if is_closed { + return stake_account; + } + + let authorized = Authorized { + staker: *staker, + withdrawer: *withdrawer, + }; + + // Initialize if needed + if self >= StakeLifecycle::Initialized { + let stake_state = StakeStateV2::Initialized(solana_stake_interface::state::Meta { + rent_exempt_reserve: STAKE_RENT_EXEMPTION, + authorized, + lockup: *lockup, + }); + bincode::serialize_into(stake_account.data_as_mut_slice(), &stake_state).unwrap(); + } + + // Delegate if needed + if self >= StakeLifecycle::Activating { + let instruction = ixn::delegate_stake(stake_pubkey, staker, vote_account); + + let accounts = vec![ + (*stake_pubkey, stake_account.clone()), + (*vote_account, create_vote_account()), + ]; + + // Use add_sysvars to provide clock, stake history, and config accounts + let accounts_with_sysvars = add_sysvars(mollusk, &instruction, accounts); + let result = mollusk.process_instruction(&instruction, &accounts_with_sysvars); + stake_account = result.resulting_accounts[0].1.clone().into(); + + // Track delegation in the tracker + // let activation_epoch = mollusk.sysvars.clock.epoch; + // TODO: uncomment in subsequent PR (add `tracker.track_delegation` here) + // tracker.track_delegation(stake_pubkey, staked_amount, activation_epoch, vote_account); + } + + // Advance epoch to activate if needed (Active and beyond) + if self >= StakeLifecycle::Active { + // With background stake in tracker, just warp 1 epoch + // The background stake provides baseline for instant partial activation + let slots_per_epoch = mollusk.sysvars.epoch_schedule.slots_per_epoch; + let current_slot = mollusk.sysvars.clock.slot; + let target_slot = current_slot + slots_per_epoch; + + // TODO: use `warp_to_slot_with_stake_tracking` here (in subsequent PR) + mollusk.warp_to_slot(target_slot); + } + + // Deactivate if needed + if self >= StakeLifecycle::Deactivating { + let instruction = ixn::deactivate_stake(stake_pubkey, staker); + + let accounts = vec![(*stake_pubkey, stake_account.clone())]; + + // Use add_sysvars to provide clock account + let accounts_with_sysvars = add_sysvars(mollusk, &instruction, accounts); + let result = mollusk.process_instruction(&instruction, &accounts_with_sysvars); + stake_account = result.resulting_accounts[0].1.clone().into(); + + // Track deactivation in the tracker + // let deactivation_epoch = mollusk.sysvars.clock.epoch; + // TODO: uncomment in subsequent PR + // tracker.track_deactivation(stake_pubkey, deactivation_epoch); + } + + // Advance epoch to fully deactivate if needed (Deactive lifecycle) + // Matches program_test.rs line 978-983: advance_epoch once to fully deactivate + if self == StakeLifecycle::Deactive { + // With background stake, advance 1 epoch for deactivation + // Background provides the baseline for instant partial deactivation + let slots_per_epoch = mollusk.sysvars.epoch_schedule.slots_per_epoch; + let current_slot = mollusk.sysvars.clock.slot; + let target_slot = current_slot + slots_per_epoch; + + // TODO: use `warp_to_slot_with_stake_tracking` here (in subsequent PR) + mollusk.warp_to_slot(target_slot); + } + + stake_account + } + + /// Whether this lifecycle stage enforces minimum delegation for split + pub fn split_minimum_enforced(&self) -> bool { + matches!( + self, + Self::Activating | Self::Active | Self::Deactivating | Self::Deactive ) - .unwrap() + } + + /// Whether this lifecycle stage enforces minimum delegation for withdraw + pub fn withdraw_minimum_enforced(&self) -> bool { + matches!(self, Self::Activating | Self::Active | Self::Deactivating) } } diff --git a/program/tests/helpers/utils.rs b/program/tests/helpers/utils.rs index 3bc0659b..3113d245 100644 --- a/program/tests/helpers/utils.rs +++ b/program/tests/helpers/utils.rs @@ -1,11 +1,12 @@ use { mollusk_svm::Mollusk, - solana_account::{Account, AccountSharedData}, + solana_account::{Account, AccountSharedData, ReadableAccount, WritableAccount}, solana_instruction::Instruction, solana_pubkey::Pubkey, solana_rent::Rent, solana_stake_interface::{stake_history::StakeHistory, state::StakeStateV2}, solana_sysvar_id::SysvarId, + solana_vote_interface::state::{VoteStateV4, VoteStateVersions}, std::collections::HashMap, }; @@ -63,3 +64,31 @@ pub fn add_sysvars( result } + +/// Create a vote account with VoteStateV4 +pub fn create_vote_account() -> AccountSharedData { + let space = VoteStateV4::size_of(); + let lamports = Rent::default().minimum_balance(space); + let vote_state = VoteStateVersions::new_v4(VoteStateV4::default()); + let data = bincode::serialize(&vote_state).unwrap(); + + Account::create(lamports, data, solana_sdk_ids::vote::id(), false, u64::MAX).into() +} + +/// Parse a stake account into (Meta, Option, lamports) +pub fn parse_stake_account( + stake_account: &AccountSharedData, +) -> ( + solana_stake_interface::state::Meta, + Option, + u64, +) { + let lamports = stake_account.lamports(); + let stake_state: StakeStateV2 = bincode::deserialize(stake_account.data()).unwrap(); + + match stake_state { + StakeStateV2::Initialized(meta) => (meta, None, lamports), + StakeStateV2::Stake(meta, stake, _) => (meta, Some(stake), lamports), + _ => panic!("Expected initialized or staked account"), + } +} diff --git a/program/tests/program_test.rs b/program/tests/program_test.rs index 4f146806..7c6dc660 100644 --- a/program/tests/program_test.rs +++ b/program/tests/program_test.rs @@ -1206,81 +1206,6 @@ async fn program_test_withdraw_stake(withdraw_source_type: StakeLifecycle) { assert_eq!(e, ProgramError::InvalidAccountData); } -#[test_case(false; "activating")] -#[test_case(true; "active")] -#[tokio::test] -async fn program_test_deactivate(activate: bool) { - let mut context = program_test().start_with_context().await; - let accounts = Accounts::default(); - accounts.initialize(&mut context).await; - - let minimum_delegation = get_minimum_delegation(&mut context).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 stake = - create_independent_stake_account(&mut context, &authorized, minimum_delegation).await; - - // deactivating an undelegated account fails - let instruction = ixn::deactivate_stake(&stake, &staker); - let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair]) - .await - .unwrap_err(); - assert_eq!(e, ProgramError::InvalidAccountData); - - // delegate - let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey()); - process_instruction(&mut context, &instruction, &vec![&staker_keypair]) - .await - .unwrap(); - - if activate { - advance_epoch(&mut context).await; - } else { - refresh_blockhash(&mut context).await; - } - - // deactivate with withdrawer fails - let instruction = ixn::deactivate_stake(&stake, &withdrawer); - let e = process_instruction(&mut context, &instruction, &vec![&withdrawer_keypair]) - .await - .unwrap_err(); - assert_eq!(e, ProgramError::MissingRequiredSignature); - - // deactivate succeeds - let instruction = ixn::deactivate_stake(&stake, &staker); - process_instruction_test_missing_signers(&mut context, &instruction, &vec![&staker_keypair]) - .await; - - let clock = context.banks_client.get_sysvar::().await.unwrap(); - let (_, stake_data, _) = get_stake_account(&mut context.banks_client, &stake).await; - assert_eq!( - stake_data.unwrap().delegation.deactivation_epoch, - clock.epoch - ); - - // deactivate again fails - refresh_blockhash(&mut context).await; - - let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair]) - .await - .unwrap_err(); - assert_eq!(e, StakeError::AlreadyDeactivated.into()); - - advance_epoch(&mut context).await; - - let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair]) - .await - .unwrap_err(); - assert_eq!(e, StakeError::AlreadyDeactivated.into()); -} - // XXX the original test_merge is a stupid test // the real thing is test_merge_active_stake which actively controls clock and // stake_history but im just trying to smoke test rn so lets do something From 7d34dd5f2ee3271ba9086e038b91b393efa11b26 Mon Sep 17 00:00:00 2001 From: rustopian <96253492+rustopian@users.noreply.github.com> Date: Tue, 4 Nov 2025 11:45:41 +0000 Subject: [PATCH 4/4] StakeTracker, migrate Delegate tests --- program/tests/delegate.rs | 214 ++++ program/tests/helpers/context.rs | 13 +- program/tests/helpers/lifecycle.rs | 34 +- program/tests/helpers/mod.rs | 1 + program/tests/helpers/stake_tracker.rs | 168 +++ program/tests/helpers/utils.rs | 16 + program/tests/program_test.rs | 144 +-- program/tests/stake_tracker_equivalence.rs | 1266 ++++++++++++++++++++ 8 files changed, 1700 insertions(+), 156 deletions(-) create mode 100644 program/tests/delegate.rs create mode 100644 program/tests/helpers/stake_tracker.rs create mode 100644 program/tests/stake_tracker_equivalence.rs diff --git a/program/tests/delegate.rs b/program/tests/delegate.rs new file mode 100644 index 00000000..eb65b5dd --- /dev/null +++ b/program/tests/delegate.rs @@ -0,0 +1,214 @@ +#![allow(clippy::arithmetic_side_effects)] + +mod helpers; + +use { + helpers::{ + context::StakeTestContext, + instruction_builders::{DeactivateConfig, DelegateConfig}, + lifecycle::StakeLifecycle, + stake_tracker::MolluskStakeExt, + utils::{create_vote_account, increment_vote_account_credits, parse_stake_account}, + }, + mollusk_svm::result::Check, + solana_account::{AccountSharedData, WritableAccount}, + solana_program_error::ProgramError, + solana_pubkey::Pubkey, + solana_stake_interface::{ + error::StakeError, + state::{Delegation, Stake, StakeStateV2}, + }, + solana_stake_program::id, +}; + +#[test] +fn test_delegate() { + let mut ctx = StakeTestContext::with_delegation(); + let vote_account = *ctx.vote_account.as_ref().unwrap(); + let mut vote_account_data = ctx.vote_account_data.as_ref().unwrap().clone(); + let min_delegation = ctx.minimum_delegation.unwrap(); + + let vote_state_credits = 100u64; + increment_vote_account_credits(&mut vote_account_data, 0, vote_state_credits); + + let (stake, mut stake_account) = ctx + .stake_account(StakeLifecycle::Initialized) + .staked_amount(min_delegation) + .build(); + + // Delegate stake + let result = ctx + .process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&vote_account, &vote_account_data), + }) + .checks(&[ + Check::success(), + Check::all_rent_exempt(), + Check::account(&stake) + .lamports(ctx.rent_exempt_reserve + min_delegation) + .owner(&id()) + .space(StakeStateV2::size_of()) + .build(), + ]) + .test_missing_signers(true) + .execute(); + stake_account = result.resulting_accounts[0].1.clone().into(); + + // Verify that delegate() looks right + let clock = ctx.mollusk.sysvars.clock.clone(); + let (_, stake_data, _) = parse_stake_account(&stake_account); + assert_eq!( + stake_data.unwrap(), + Stake { + delegation: Delegation { + voter_pubkey: vote_account, + stake: min_delegation, + activation_epoch: clock.epoch, + deactivation_epoch: u64::MAX, + ..Delegation::default() + }, + credits_observed: vote_state_credits, + } + ); + + // Advance epoch to activate the stake + let activation_epoch = ctx.mollusk.sysvars.clock.epoch; + ctx.tracker.as_mut().unwrap().track_delegation( + &stake, + min_delegation, + activation_epoch, + &vote_account, + ); + + let slots_per_epoch = ctx.mollusk.sysvars.epoch_schedule.slots_per_epoch; + let current_slot = ctx.mollusk.sysvars.clock.slot; + ctx.mollusk.warp_to_slot_with_stake_tracking( + ctx.tracker.as_ref().unwrap(), + current_slot + slots_per_epoch, + Some(0), + ); + + // Verify that delegate fails as stake is active and not deactivating + ctx.process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&vote_account, ctx.vote_account_data.as_ref().unwrap()), + }) + .checks(&[Check::err(StakeError::TooSoonToRedelegate.into())]) + .test_missing_signers(false) + .execute(); + + // Deactivate + let result = ctx + .process_with(DeactivateConfig { + stake: (&stake, &stake_account), + override_signer: None, + }) + .execute(); + stake_account = result.resulting_accounts[0].1.clone().into(); + + // Create second vote account + let (vote_account2, vote_account2_data) = ctx.create_second_vote_account(); + + // Verify that delegate to a different vote account fails during deactivation + ctx.process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&vote_account2, &vote_account2_data), + }) + .checks(&[Check::err(StakeError::TooSoonToRedelegate.into())]) + .test_missing_signers(false) + .execute(); + + // Verify that delegate succeeds to same vote account when stake is deactivating + let result = ctx + .process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&vote_account, ctx.vote_account_data.as_ref().unwrap()), + }) + .execute(); + stake_account = result.resulting_accounts[0].1.clone().into(); + + // Verify that deactivation has been cleared + let (_, stake_data, _) = parse_stake_account(&stake_account); + assert_eq!(stake_data.unwrap().delegation.deactivation_epoch, u64::MAX); + + // Verify that delegate to a different vote account fails if stake is still active + ctx.process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&vote_account2, &vote_account2_data), + }) + .checks(&[Check::err(StakeError::TooSoonToRedelegate.into())]) + .test_missing_signers(false) + .execute(); + + // Advance epoch again using tracker + let current_slot = ctx.mollusk.sysvars.clock.slot; + let slots_per_epoch = ctx.mollusk.sysvars.epoch_schedule.slots_per_epoch; + ctx.mollusk.warp_to_slot_with_stake_tracking( + ctx.tracker.as_ref().unwrap(), + current_slot + slots_per_epoch, + Some(0), + ); + + // Delegate still fails after stake is fully activated; redelegate is not supported + let (vote_account2, vote_account2_data) = ctx.create_second_vote_account(); + + ctx.process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&vote_account2, &vote_account2_data), + }) + .checks(&[Check::err(StakeError::TooSoonToRedelegate.into())]) + .test_missing_signers(false) + .execute(); +} + +#[test] +fn test_delegate_fake_vote_account() { + let mut ctx = StakeTestContext::with_delegation(); + + // Create fake vote account (not owned by vote program) + let fake_vote_account = Pubkey::new_unique(); + let mut fake_vote_data = create_vote_account(); + fake_vote_data.set_owner(Pubkey::new_unique()); // Wrong owner + + let min_delegation = ctx.minimum_delegation.unwrap(); + let (stake, stake_account) = ctx + .stake_account(StakeLifecycle::Initialized) + .staked_amount(min_delegation) + .build(); + + // Try to delegate to fake vote account + ctx.process_with(DelegateConfig { + stake: (&stake, &stake_account), + vote: (&fake_vote_account, &fake_vote_data), + }) + .checks(&[Check::err(ProgramError::IncorrectProgramId)]) + .test_missing_signers(false) + .execute(); +} + +#[test] +fn test_delegate_non_stake_account() { + let ctx = StakeTestContext::with_delegation(); + + // Create a rewards pool account (program-owned but not a stake account) + let rewards_pool = Pubkey::new_unique(); + let rewards_pool_data = AccountSharedData::new_data_with_space( + ctx.rent_exempt_reserve, + &StakeStateV2::RewardsPool, + StakeStateV2::size_of(), + &id(), + ) + .unwrap(); + + ctx.process_with(DelegateConfig { + stake: (&rewards_pool, &rewards_pool_data), + vote: ( + ctx.vote_account.as_ref().unwrap(), + ctx.vote_account_data.as_ref().unwrap(), + ), + }) + .checks(&[Check::err(ProgramError::InvalidAccountData)]) + .test_missing_signers(false) + .execute(); +} diff --git a/program/tests/helpers/context.rs b/program/tests/helpers/context.rs index d0c44350..4507a7cf 100644 --- a/program/tests/helpers/context.rs +++ b/program/tests/helpers/context.rs @@ -2,6 +2,7 @@ use { super::{ instruction_builders::{InstructionConfig, InstructionExecution}, lifecycle::StakeLifecycle, + stake_tracker::StakeTracker, utils::{add_sysvars, create_vote_account, STAKE_RENT_EXEMPTION}, }, mollusk_svm::{result::Check, Mollusk}, @@ -66,6 +67,10 @@ impl StakeAccountBuilder<'_> { let stake_pubkey = self.stake_pubkey.unwrap_or_else(Pubkey::new_unique); let account = self.lifecycle.create_stake_account_fully_specified( &mut self.ctx.mollusk, + self.ctx + .tracker + .as_mut() + .expect("tracker required for stake account builder"), &stake_pubkey, self.vote_account.as_ref().unwrap_or( self.ctx @@ -84,6 +89,7 @@ impl StakeAccountBuilder<'_> { } } +#[allow(dead_code)] // can be removed once later tests are in pub struct StakeTestContext { pub mollusk: Mollusk, pub rent_exempt_reserve: u64, @@ -92,8 +98,10 @@ pub struct StakeTestContext { pub minimum_delegation: Option, pub vote_account: Option, pub vote_account_data: Option, + pub tracker: Option, } +#[allow(dead_code)] // can be removed once later tests are in impl StakeTestContext { pub fn minimal() -> Self { let mollusk = Mollusk::new(&id(), "solana_stake_program"); @@ -105,12 +113,14 @@ impl StakeTestContext { minimum_delegation: None, vote_account: None, vote_account_data: None, + tracker: None, } } pub fn with_delegation() -> Self { let mollusk = Mollusk::new(&id(), "solana_stake_program"); let minimum_delegation = solana_stake_program::get_minimum_delegation(); + let tracker: StakeTracker = StakeLifecycle::create_tracker_for_test(minimum_delegation); Self { mollusk, rent_exempt_reserve: STAKE_RENT_EXEMPTION, @@ -119,6 +129,7 @@ impl StakeTestContext { minimum_delegation: Some(minimum_delegation), vote_account: Some(Pubkey::new_unique()), vote_account_data: Some(create_vote_account()), + tracker: Some(tracker), } } @@ -127,6 +138,7 @@ impl StakeTestContext { } /// Create a stake account builder for the specified lifecycle stage + /// This is the primary method for creating stake accounts in tests. /// /// Example: /// ``` @@ -214,7 +226,6 @@ impl StakeTestContext { .process_and_validate_instruction(instruction, &accounts_with_sysvars, checks) } } - impl Default for StakeTestContext { fn default() -> Self { Self::new() diff --git a/program/tests/helpers/lifecycle.rs b/program/tests/helpers/lifecycle.rs index e094c96f..67aed6a9 100644 --- a/program/tests/helpers/lifecycle.rs +++ b/program/tests/helpers/lifecycle.rs @@ -1,5 +1,9 @@ use { - super::utils::{add_sysvars, create_vote_account, STAKE_RENT_EXEMPTION}, + super::{ + stake_tracker::MolluskStakeExt, + utils::{add_sysvars, create_vote_account, STAKE_RENT_EXEMPTION}, + }, + crate::helpers::stake_tracker::StakeTracker, mollusk_svm::Mollusk, solana_account::{Account, AccountSharedData, WritableAccount}, solana_pubkey::Pubkey, @@ -23,12 +27,22 @@ pub enum StakeLifecycle { } impl StakeLifecycle { + /// Helper to create tracker with appropriate background stake for tests + /// Returns a tracker seeded with background cluster stake + pub fn create_tracker_for_test(minimum_delegation: u64) -> StakeTracker { + // Use a moderate background stake amount + // This mimics Banks' cluster-wide effective stake from all validators + // Calculation: needs to be >> test stakes to provide stable warmup base + let background_stake = minimum_delegation.saturating_mul(100); + StakeTracker::with_background_stake(background_stake) + } + /// Create a stake account with full specification of authorities and lockup #[allow(clippy::too_many_arguments)] pub fn create_stake_account_fully_specified( self, mollusk: &mut Mollusk, - // tracker: &mut StakeTracker, // added in subsequent PR + tracker: &mut StakeTracker, stake_pubkey: &Pubkey, vote_account: &Pubkey, staked_amount: u64, @@ -91,9 +105,8 @@ impl StakeLifecycle { stake_account = result.resulting_accounts[0].1.clone().into(); // Track delegation in the tracker - // let activation_epoch = mollusk.sysvars.clock.epoch; - // TODO: uncomment in subsequent PR (add `tracker.track_delegation` here) - // tracker.track_delegation(stake_pubkey, staked_amount, activation_epoch, vote_account); + let activation_epoch = mollusk.sysvars.clock.epoch; + tracker.track_delegation(stake_pubkey, staked_amount, activation_epoch, vote_account); } // Advance epoch to activate if needed (Active and beyond) @@ -104,8 +117,7 @@ impl StakeLifecycle { let current_slot = mollusk.sysvars.clock.slot; let target_slot = current_slot + slots_per_epoch; - // TODO: use `warp_to_slot_with_stake_tracking` here (in subsequent PR) - mollusk.warp_to_slot(target_slot); + mollusk.warp_to_slot_with_stake_tracking(tracker, target_slot, Some(0)); } // Deactivate if needed @@ -120,9 +132,8 @@ impl StakeLifecycle { stake_account = result.resulting_accounts[0].1.clone().into(); // Track deactivation in the tracker - // let deactivation_epoch = mollusk.sysvars.clock.epoch; - // TODO: uncomment in subsequent PR - // tracker.track_deactivation(stake_pubkey, deactivation_epoch); + let deactivation_epoch = mollusk.sysvars.clock.epoch; + tracker.track_deactivation(stake_pubkey, deactivation_epoch); } // Advance epoch to fully deactivate if needed (Deactive lifecycle) @@ -134,8 +145,7 @@ impl StakeLifecycle { let current_slot = mollusk.sysvars.clock.slot; let target_slot = current_slot + slots_per_epoch; - // TODO: use `warp_to_slot_with_stake_tracking` here (in subsequent PR) - mollusk.warp_to_slot(target_slot); + mollusk.warp_to_slot_with_stake_tracking(tracker, target_slot, Some(0)); } stake_account diff --git a/program/tests/helpers/mod.rs b/program/tests/helpers/mod.rs index ff09b000..7b85f51d 100644 --- a/program/tests/helpers/mod.rs +++ b/program/tests/helpers/mod.rs @@ -4,4 +4,5 @@ pub mod context; pub mod instruction_builders; pub mod lifecycle; +pub mod stake_tracker; pub mod utils; diff --git a/program/tests/helpers/stake_tracker.rs b/program/tests/helpers/stake_tracker.rs new file mode 100644 index 00000000..6885ef51 --- /dev/null +++ b/program/tests/helpers/stake_tracker.rs @@ -0,0 +1,168 @@ +use { + mollusk_svm::Mollusk, + solana_clock::Epoch, + solana_pubkey::Pubkey, + solana_stake_interface::{ + stake_history::{StakeHistory, StakeHistoryEntry}, + state::Delegation, + }, + std::collections::HashMap, +}; + +// This replicates solana-runtime's Banks behavior where stake history is automatically +// updated at epoch boundaries by aggregating all stake delegations. + +/// Tracks stake delegations for automatic stake history management +#[derive(Default, Clone)] +pub struct StakeTracker { + /// Map of stake account pubkey to its delegation info + pub(crate) delegations: HashMap, +} + +#[derive(Clone)] +pub(crate) struct TrackedDelegation { + pub(crate) stake: u64, + pub(crate) activation_epoch: Epoch, + pub(crate) deactivation_epoch: Epoch, + pub(crate) voter_pubkey: Pubkey, +} + +impl StakeTracker { + pub fn new() -> Self { + Self::default() + } + + /// Create a tracker with background cluster stake (like Banks has) + /// This provides the baseline effective stake that enables instant activation/deactivation + pub fn with_background_stake(background_stake: u64) -> Self { + let mut tracker = Self::new(); + + // Add a synthetic background stake that's been active forever (bootstrap stake) + // This mimics Banks' cluster-wide effective stake + tracker.delegations.insert( + Pubkey::new_unique(), // Synthetic background stake pubkey + TrackedDelegation { + stake: background_stake, + activation_epoch: u64::MAX, // Bootstrap = instantly effective + deactivation_epoch: u64::MAX, + voter_pubkey: Pubkey::new_unique(), + }, + ); + + tracker + } + + /// Track a new stake delegation (called after delegate instruction) + pub fn track_delegation( + &mut self, + stake_pubkey: &Pubkey, + stake_amount: u64, + activation_epoch: Epoch, + voter_pubkey: &Pubkey, + ) { + self.delegations.insert( + *stake_pubkey, + TrackedDelegation { + stake: stake_amount, + activation_epoch, + deactivation_epoch: u64::MAX, + voter_pubkey: *voter_pubkey, + }, + ); + } + + /// Mark a stake as deactivating (called after deactivate instruction) + pub fn track_deactivation(&mut self, stake_pubkey: &Pubkey, deactivation_epoch: Epoch) { + if let Some(delegation) = self.delegations.get_mut(stake_pubkey) { + delegation.deactivation_epoch = deactivation_epoch; + } + } + + /// Calculate aggregate stake history for an epoch (replicates Stakes::activate_epoch) + fn calculate_epoch_entry( + &self, + epoch: Epoch, + stake_history: &StakeHistory, + new_rate_activation_epoch: Option, + ) -> StakeHistoryEntry { + self.delegations + .values() + .map(|tracked| { + let delegation = Delegation { + voter_pubkey: tracked.voter_pubkey, + stake: tracked.stake, + activation_epoch: tracked.activation_epoch, + deactivation_epoch: tracked.deactivation_epoch, + ..Delegation::default() + }; + + delegation.stake_activating_and_deactivating( + epoch, + stake_history, + new_rate_activation_epoch, + ) + }) + .fold(StakeHistoryEntry::default(), |acc, status| { + StakeHistoryEntry { + effective: acc.effective + status.effective, + activating: acc.activating + status.activating, + deactivating: acc.deactivating + status.deactivating, + } + }) + } +} + +/// Extension trait that adds stake-aware warping to Mollusk +pub trait MolluskStakeExt { + /// Warp to a slot and automatically update stake history at epoch boundaries + /// + /// This replicates Banks' behavior from solana-runtime: + /// - Bank::warp_from_parent() advances slot + /// - Stakes::activate_epoch() aggregates delegations + /// - Bank::update_stake_history() writes sysvar + fn warp_to_slot_with_stake_tracking( + &mut self, + tracker: &StakeTracker, + target_slot: u64, + new_rate_activation_epoch: Option, + ); +} + +impl MolluskStakeExt for Mollusk { + fn warp_to_slot_with_stake_tracking( + &mut self, + tracker: &StakeTracker, + target_slot: u64, + new_rate_activation_epoch: Option, + ) { + let current_epoch = self.sysvars.clock.epoch; + let current_slot = self.sysvars.clock.slot; + + if target_slot <= current_slot { + panic!( + "Cannot warp backwards: current_slot={}, target_slot={}", + current_slot, target_slot + ); + } + + // Advance the clock (Mollusk's warp_to_slot only updates Clock sysvar) + self.warp_to_slot(target_slot); + + let new_epoch = self.sysvars.clock.epoch; + + // If we crossed epoch boundaries, update stake history for EACH epoch + // StakeHistorySysvar requires contiguous history with no gaps + // This replicates Bank::update_stake_history() + Stakes::activate_epoch() + if new_epoch != current_epoch { + for epoch in current_epoch..new_epoch { + let entry = tracker.calculate_epoch_entry( + epoch, + &self.sysvars.stake_history, + new_rate_activation_epoch, + ); + + self.sysvars.stake_history.add(epoch, entry); + } + } + } +} diff --git a/program/tests/helpers/utils.rs b/program/tests/helpers/utils.rs index 3113d245..c83886cf 100644 --- a/program/tests/helpers/utils.rs +++ b/program/tests/helpers/utils.rs @@ -1,6 +1,7 @@ use { mollusk_svm::Mollusk, solana_account::{Account, AccountSharedData, ReadableAccount, WritableAccount}, + solana_clock::Epoch, solana_instruction::Instruction, solana_pubkey::Pubkey, solana_rent::Rent, @@ -92,3 +93,18 @@ pub fn parse_stake_account( _ => panic!("Expected initialized or staked account"), } } + +/// Increment vote account credits +pub fn increment_vote_account_credits( + vote_account: &mut AccountSharedData, + epoch: Epoch, + credits: u64, +) { + let mut vote_state: VoteStateVersions = bincode::deserialize(vote_account.data()).unwrap(); + + if let VoteStateVersions::V4(ref mut v4) = vote_state { + v4.epoch_credits.push((epoch, credits, 0)); + } + + vote_account.set_data(bincode::serialize(&vote_state).unwrap()); +} diff --git a/program/tests/program_test.rs b/program/tests/program_test.rs index 7c6dc660..09c826ca 100644 --- a/program/tests/program_test.rs +++ b/program/tests/program_test.rs @@ -17,7 +17,7 @@ use { instruction::{self as ixn, LockupArgs}, program::id, stake_history::StakeHistory, - state::{Authorized, Delegation, Lockup, Meta, Stake, StakeAuthorize, StakeStateV2}, + state::{Authorized, Lockup, Meta, Stake, StakeAuthorize, StakeStateV2}, }, solana_system_interface::instruction as system_instruction, solana_transaction::{Signers, Transaction, TransactionError}, @@ -619,148 +619,6 @@ async fn program_test_authorize() { } } -#[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::().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, diff --git a/program/tests/stake_tracker_equivalence.rs b/program/tests/stake_tracker_equivalence.rs new file mode 100644 index 00000000..15af084e --- /dev/null +++ b/program/tests/stake_tracker_equivalence.rs @@ -0,0 +1,1266 @@ +#![allow(clippy::arithmetic_side_effects)] + +//! Equivalence tests proving StakeTracker (Mollusk) matches BanksClient (solana-program-test) +//! +//! These tests run identical stake operations through both implementations and compare results +//! to ensure 1:1 behavioral equivalence in stake history tracking. +use { + mollusk_svm::Mollusk, + solana_account::{AccountSharedData, ReadableAccount, WritableAccount}, + solana_clock::Clock, + solana_keypair::Keypair, + solana_program_test::{ProgramTest, ProgramTestContext}, + solana_pubkey::Pubkey, + solana_signer::Signer, + solana_stake_interface::{ + instruction as ixn, + stake_history::StakeHistory, + state::{Authorized, Lockup, StakeStateV2}, + }, + solana_stake_program::id, + solana_system_interface::instruction as system_instruction, + solana_transaction::Transaction, + test_case::test_case, +}; + +mod helpers; +use helpers::{ + stake_tracker::{MolluskStakeExt, StakeTracker}, + utils::{add_sysvars, create_vote_account, STAKE_RENT_EXEMPTION}, +}; + +// Constants for testing +const MINIMUM_DELEGATION: u64 = 1; + +/// Dual context holding both BanksClient and Mollusk paths +struct DualContext { + // BanksClient path + program_test_ctx: ProgramTestContext, + + // Mollusk path + mollusk: Mollusk, + tracker: StakeTracker, + + // Shared test data + vote_account: Pubkey, + vote_account_data: AccountSharedData, + background_stake: u64, +} + +impl DualContext { + /// Create both contexts with matching initial state + async fn new() -> Self { + // Initialize program test (BanksClient path) + let mut program_test = ProgramTest::default(); + program_test.prefer_bpf(true); + program_test.add_upgradeable_program_to_genesis("solana_stake_program", &id()); + let mut program_test_ctx = program_test.start_with_context().await; + + // Warp to first normal slot on Banks + let slot = program_test_ctx + .genesis_config() + .epoch_schedule + .first_normal_slot + + 1; + program_test_ctx.warp_to_slot(slot).unwrap(); + + // Initialize Mollusk and sync to the same epoch as Banks + let mut mollusk = Mollusk::new(&id(), "solana_stake_program"); + // Banks and Mollusk have different epoch schedules, so we need to get to same epoch + let banks_clock = program_test_ctx + .banks_client + .get_sysvar::() + .await + .unwrap(); + let banks_epoch = banks_clock.epoch; + + // Warp Mollusk to the same epoch by calculating the corresponding slot + let mollusk_slot_for_epoch = mollusk + .sysvars + .epoch_schedule + .get_first_slot_in_epoch(banks_epoch); + mollusk.warp_to_slot(mollusk_slot_for_epoch); + + // Extract BanksClient's actual background stake from its genesis stake history + // This ensures Mollusk uses the same background stake for identical history + let banks_stake_history = program_test_ctx + .banks_client + .get_sysvar::() + .await + .unwrap(); + + let epoch_0_entry = banks_stake_history.get(0).cloned().unwrap_or_default(); + let background_stake = epoch_0_entry.effective; + + let tracker = StakeTracker::with_background_stake(background_stake); + + // Initialize Mollusk's stake history to match BanksClient + // Banks may not have history for all intermediate epochs when warped directly, + // so we'll generate them using the tracker (which only has background stake initially) + for epoch in 0..banks_epoch { + if let Some(entry) = banks_stake_history.get(epoch).cloned() { + // Use Banks' actual entry if it exists + mollusk.sysvars.stake_history.add(epoch, entry); + } else { + // Generate entry with just background stake for missing epochs + // This matches what would happen if we had advanced through these epochs naturally + mollusk + .sysvars + .stake_history + .add(epoch, epoch_0_entry.clone()); + } + } + + // Create shared vote account + let vote_account = Pubkey::new_unique(); + let vote_account_data = create_vote_account(); + + // Add vote account to BanksClient (clone to keep original) + program_test_ctx.set_account(&vote_account, &vote_account_data.clone()); + + Self { + program_test_ctx, + mollusk, + tracker, + vote_account, + vote_account_data, + background_stake, + } + } + + /// Create a blank stake account on both paths + async fn create_blank_stake_account(&mut self) -> Pubkey { + let stake_keypair = Keypair::new(); + let stake = stake_keypair.pubkey(); + + // BanksClient path + let transaction = Transaction::new_signed_with_payer( + &[system_instruction::create_account( + &self.program_test_ctx.payer.pubkey(), + &stake, + STAKE_RENT_EXEMPTION, + StakeStateV2::size_of() as u64, + &id(), + )], + Some(&self.program_test_ctx.payer.pubkey()), + &[&self.program_test_ctx.payer, &stake_keypair], + self.program_test_ctx.last_blockhash, + ); + self.program_test_ctx + .banks_client + .process_transaction(transaction) + .await + .unwrap(); + + // Mollusk path - just track that we'll add it when needed + // (Mollusk accounts are passed per-instruction, not stored globally) + + stake + } + + /// Initialize a stake account on both paths + async fn initialize_stake_account( + &mut self, + stake: &Pubkey, + authorized: &Authorized, + lockup: &Lockup, + ) -> AccountSharedData { + let instruction = ixn::initialize(stake, authorized, lockup); + + // BanksClient path + let transaction = Transaction::new_signed_with_payer( + &[instruction.clone()], + Some(&self.program_test_ctx.payer.pubkey()), + &[&self.program_test_ctx.payer], + self.program_test_ctx.last_blockhash, + ); + self.program_test_ctx + .banks_client + .process_transaction(transaction) + .await + .unwrap(); + + // Get account from BanksClient + let banks_account = self + .program_test_ctx + .banks_client + .get_account(*stake) + .await + .unwrap() + .unwrap(); + + // Mollusk path - create matching account + let mut mollusk_account = + AccountSharedData::new(STAKE_RENT_EXEMPTION, StakeStateV2::size_of(), &id()); + + let accounts = vec![(*stake, mollusk_account.clone())]; + let accounts_with_sysvars = add_sysvars(&self.mollusk, &instruction, accounts); + let result = self + .mollusk + .process_instruction(&instruction, &accounts_with_sysvars); + assert!(result.program_result.is_ok()); + mollusk_account = result.resulting_accounts[0].1.clone().into(); + + // Verify accounts match + assert_eq!(banks_account.data, mollusk_account.data()); + assert_eq!(banks_account.lamports, mollusk_account.lamports()); + + mollusk_account + } + + /// Delegate stake on both paths to a specific vote account + async fn delegate_stake_to( + &mut self, + stake: &Pubkey, + stake_account: &mut AccountSharedData, + staker_keypair: &Keypair, + vote_account: &Pubkey, + vote_account_data: &AccountSharedData, + ) { + let instruction = ixn::delegate_stake(stake, &staker_keypair.pubkey(), vote_account); + + // BanksClient path + let transaction = Transaction::new_signed_with_payer( + &[instruction.clone()], + Some(&self.program_test_ctx.payer.pubkey()), + &[&self.program_test_ctx.payer, staker_keypair], + self.program_test_ctx.last_blockhash, + ); + self.program_test_ctx + .banks_client + .process_transaction(transaction) + .await + .unwrap(); + + // Mollusk path + let accounts = vec![ + (*stake, stake_account.clone()), + (*vote_account, vote_account_data.clone()), + ]; + let accounts_with_sysvars = add_sysvars(&self.mollusk, &instruction, accounts); + let result = self + .mollusk + .process_instruction(&instruction, &accounts_with_sysvars); + assert!(result.program_result.is_ok()); + *stake_account = result.resulting_accounts[0].1.clone().into(); + + // Track delegation in Mollusk tracker + let stake_state: StakeStateV2 = bincode::deserialize(stake_account.data()).unwrap(); + if let StakeStateV2::Stake(_, stake_data, _) = stake_state { + self.tracker.track_delegation( + stake, + stake_data.delegation.stake, + stake_data.delegation.activation_epoch, + vote_account, + ); + } + } + + /// Delegate stake on both paths (uses default vote account) + async fn delegate_stake( + &mut self, + stake: &Pubkey, + stake_account: &mut AccountSharedData, + staker_keypair: &Keypair, + ) { + let vote_account = self.vote_account; + let vote_account_data = self.vote_account_data.clone(); + self.delegate_stake_to( + stake, + stake_account, + staker_keypair, + &vote_account, + &vote_account_data, + ) + .await; + } + + /// Deactivate stake on both paths + async fn deactivate_stake( + &mut self, + stake: &Pubkey, + stake_account: &mut AccountSharedData, + staker_keypair: &Keypair, + ) { + let instruction = ixn::deactivate_stake(stake, &staker_keypair.pubkey()); + + // BanksClient path + let transaction = Transaction::new_signed_with_payer( + &[instruction.clone()], + Some(&self.program_test_ctx.payer.pubkey()), + &[&self.program_test_ctx.payer, staker_keypair], + self.program_test_ctx.last_blockhash, + ); + self.program_test_ctx + .banks_client + .process_transaction(transaction) + .await + .unwrap(); + + // Mollusk path + let accounts = vec![(*stake, stake_account.clone())]; + let accounts_with_sysvars = add_sysvars(&self.mollusk, &instruction, accounts); + let result = self + .mollusk + .process_instruction(&instruction, &accounts_with_sysvars); + assert!(result.program_result.is_ok()); + *stake_account = result.resulting_accounts[0].1.clone().into(); + + // Track deactivation + let deactivation_epoch = self.mollusk.sysvars.clock.epoch; + self.tracker.track_deactivation(stake, deactivation_epoch); + } + + /// Advance epoch on both paths with default new_rate_activation_epoch (Some(0)) + async fn advance_epoch(&mut self) { + self.advance_epoch_with_rate(Some(0)).await; + } + + /// Advance epoch on both paths with custom new_rate_activation_epoch + /// Pass None to use old warmup rate behavior + async fn advance_epoch_with_rate(&mut self, new_rate_activation_epoch: Option) { + // Refresh blockhash for BanksClient by advancing slot slightly first + let current_slot = self + .program_test_ctx + .banks_client + .get_root_slot() + .await + .unwrap(); + self.program_test_ctx + .warp_to_slot(current_slot + 1) + .unwrap(); + self.program_test_ctx.last_blockhash = self + .program_test_ctx + .banks_client + .get_latest_blockhash() + .await + .unwrap(); + + // BanksClient path - advance epoch + let root_slot = self + .program_test_ctx + .banks_client + .get_root_slot() + .await + .unwrap(); + let slots_per_epoch = self + .program_test_ctx + .genesis_config() + .epoch_schedule + .slots_per_epoch; + self.program_test_ctx + .warp_to_slot(root_slot + slots_per_epoch) + .unwrap(); + + // Mollusk path - advance epoch with stake tracking + let current_slot = self.mollusk.sysvars.clock.slot; + let mollusk_slots_per_epoch = self.mollusk.sysvars.epoch_schedule.slots_per_epoch; + let target_slot = current_slot + mollusk_slots_per_epoch; + self.mollusk.warp_to_slot_with_stake_tracking( + &self.tracker, + target_slot, + new_rate_activation_epoch, + ); + } + + /// Fast-forward multiple epochs without full validation (for performance) + /// This advances both paths in bulk to avoid excessive async operations + #[allow(dead_code)] + async fn advance_epochs_fast(&mut self, num_epochs: u64) { + if num_epochs == 0 { + return; + } + + // BanksClient: advance in one big jump + let root_slot = self + .program_test_ctx + .banks_client + .get_root_slot() + .await + .unwrap(); + let slots_per_epoch = self + .program_test_ctx + .genesis_config() + .epoch_schedule + .slots_per_epoch; + let target_slot = root_slot + (slots_per_epoch * num_epochs); + self.program_test_ctx.warp_to_slot(target_slot).unwrap(); + self.program_test_ctx.last_blockhash = self + .program_test_ctx + .banks_client + .get_latest_blockhash() + .await + .unwrap(); + + // Mollusk: advance in one big jump + for _ in 0..num_epochs { + let current_slot = self.mollusk.sysvars.clock.slot; + let mollusk_slots_per_epoch = self.mollusk.sysvars.epoch_schedule.slots_per_epoch; + let target_slot = current_slot + mollusk_slots_per_epoch; + self.mollusk + .warp_to_slot_with_stake_tracking(&self.tracker, target_slot, Some(0)); + } + } + + /// Get stake history from BanksClient + async fn get_banks_stake_history(&mut self) -> StakeHistory { + self.program_test_ctx + .banks_client + .get_sysvar::() + .await + .unwrap() + } + + /// Get stake history from Mollusk + fn get_mollusk_stake_history(&self) -> &StakeHistory { + &self.mollusk.sysvars.stake_history + } + + /// Get effective stake from BanksClient + async fn get_banks_effective_stake(&mut self, stake: &Pubkey) -> u64 { + let clock = self + .program_test_ctx + .banks_client + .get_sysvar::() + .await + .unwrap(); + let stake_history = self.get_banks_stake_history().await; + let account = self + .program_test_ctx + .banks_client + .get_account(*stake) + .await + .unwrap() + .unwrap(); + + match bincode::deserialize::(&account.data).unwrap() { + StakeStateV2::Stake(_, stake_data, _) => { + stake_data + .delegation + .stake_activating_and_deactivating(clock.epoch, &stake_history, Some(0)) + .effective + } + _ => 0, + } + } + + /// Get effective stake from Mollusk + fn get_mollusk_effective_stake(&self, stake_account: &AccountSharedData) -> u64 { + let clock = &self.mollusk.sysvars.clock; + let stake_history = &self.mollusk.sysvars.stake_history; + + match bincode::deserialize::(stake_account.data()).unwrap() { + StakeStateV2::Stake(_, stake_data, _) => { + stake_data + .delegation + .stake_activating_and_deactivating(clock.epoch, stake_history, Some(0)) + .effective + } + _ => 0, + } + } + + /// Compare stake history entries between both implementations + /// Verifies all components: effective, activating, and deactivating + async fn compare_stake_history(&mut self, epoch: u64) { + let banks_history = self + .program_test_ctx + .banks_client + .get_sysvar::() + .await + .unwrap(); + let mollusk_history = &self.mollusk.sysvars.stake_history; + + let banks_entry = banks_history.get(epoch); + let mollusk_entry = mollusk_history.get(epoch); + + assert_eq!( + banks_entry, mollusk_entry, + "Stake history mismatch at epoch {}: BanksClient={:?}, Mollusk={:?}", + epoch, banks_entry, mollusk_entry + ); + } + + /// Verify background stake is preserved in stake history across implementations + async fn verify_background_stake_preservation(&mut self, epoch: u64, expected_background: u64) { + let banks_history = self + .program_test_ctx + .banks_client + .get_sysvar::() + .await + .unwrap(); + let mollusk_history = &self.mollusk.sysvars.stake_history; + + if let Some(banks_entry) = banks_history.get(epoch) { + assert!( + banks_entry.effective >= expected_background, + "Epoch {}: Banks effective stake {} should include background {}", + epoch, + banks_entry.effective, + expected_background + ); + } + + if let Some(mollusk_entry) = mollusk_history.get(epoch) { + assert!( + mollusk_entry.effective >= expected_background, + "Epoch {}: Mollusk effective stake {} should include background {}", + epoch, + mollusk_entry.effective, + expected_background + ); + } + } + + /// Compare account state between both paths + async fn compare_account_state(&mut self, stake: &Pubkey, mollusk_account: &AccountSharedData) { + let banks_account = self + .program_test_ctx + .banks_client + .get_account(*stake) + .await + .unwrap() + .unwrap(); + + assert_eq!( + banks_account.lamports, + mollusk_account.lamports(), + "Lamports mismatch" + ); + + let banks_state: StakeStateV2 = bincode::deserialize(&banks_account.data).unwrap(); + let mollusk_state: StakeStateV2 = bincode::deserialize(mollusk_account.data()).unwrap(); + + match (banks_state, mollusk_state) { + (StakeStateV2::Stake(b_meta, b_stake, _), StakeStateV2::Stake(m_meta, m_stake, _)) => { + assert_eq!(b_meta.authorized, m_meta.authorized); + assert_eq!(b_meta.lockup, m_meta.lockup); + assert_eq!(b_stake.delegation.stake, m_stake.delegation.stake); + assert_eq!( + b_stake.delegation.activation_epoch, + m_stake.delegation.activation_epoch + ); + assert_eq!( + b_stake.delegation.deactivation_epoch, + m_stake.delegation.deactivation_epoch + ); + } + (StakeStateV2::Initialized(b_meta), StakeStateV2::Initialized(m_meta)) => { + assert_eq!(b_meta.authorized, m_meta.authorized); + assert_eq!(b_meta.lockup, m_meta.lockup); + } + _ => { + panic!( + "State type mismatch: banks={:?}, mollusk={:?}", + banks_state, mollusk_state + ); + } + } + } + + /// Advance one epoch and compare stake account state between implementations + async fn advance_and_compare_stake( + &mut self, + stake: &Pubkey, + stake_account: &AccountSharedData, + ) { + self.advance_and_compare_stake_with_rate(stake, stake_account, Some(0)) + .await; + } + + /// Advance one epoch with custom warmup rate and compare stake account state + async fn advance_and_compare_stake_with_rate( + &mut self, + stake: &Pubkey, + stake_account: &AccountSharedData, + new_rate_activation_epoch: Option, + ) { + self.advance_epoch_with_rate(new_rate_activation_epoch) + .await; + let epoch = self.mollusk.sysvars.clock.epoch; + self.compare_stake_history(epoch - 1).await; + + let banks_effective = self.get_banks_effective_stake(stake).await; + let mollusk_effective = self.get_mollusk_effective_stake(stake_account); + assert_eq!( + banks_effective, mollusk_effective, + "Epoch {}: effective stake mismatch", + epoch + ); + self.compare_account_state(stake, stake_account).await; + } + + /// Advance epochs until stake is fully activated (effective == delegated amount) + /// Returns number of epochs advanced. Panics if not activated within max_epochs. + async fn advance_until_fully_activated( + &mut self, + stake: &Pubkey, + stake_account: &AccountSharedData, + max_epochs: u64, + ) -> u64 { + let stake_state: StakeStateV2 = bincode::deserialize(stake_account.data()).unwrap(); + let target_amount = match stake_state { + StakeStateV2::Stake(_, stake_data, _) => stake_data.delegation.stake, + _ => panic!("Stake account not in delegated state"), + }; + + let mut epochs_advanced = 0; + loop { + self.advance_and_compare_stake(stake, stake_account).await; + epochs_advanced += 1; + + let banks_effective = self.get_banks_effective_stake(stake).await; + if banks_effective == target_amount { + return epochs_advanced; + } + + assert!( + epochs_advanced < max_epochs, + "Stake did not fully activate within {} epochs", + max_epochs + ); + } + } + + /// Advance epochs until stake is fully deactivated (effective == 0) + /// Returns number of epochs advanced. Panics if not deactivated within max_epochs. + async fn advance_until_fully_deactivated( + &mut self, + stake: &Pubkey, + stake_account: &AccountSharedData, + max_epochs: u64, + ) -> u64 { + let mut epochs_advanced = 0; + loop { + self.advance_and_compare_stake(stake, stake_account).await; + epochs_advanced += 1; + + let banks_effective = self.get_banks_effective_stake(stake).await; + if banks_effective == 0 { + return epochs_advanced; + } + + assert!( + epochs_advanced < max_epochs, + "Stake did not fully deactivate within {} epochs", + max_epochs + ); + } + } + + /// Advance one epoch and compare multiple stake accounts between implementations + async fn advance_and_compare_stakes(&mut self, stakes: &[(&Pubkey, &AccountSharedData)]) { + self.advance_and_compare_stakes_with_rate(stakes, Some(0)) + .await; + } + + /// Advance one epoch with custom warmup rate and compare multiple stake accounts + async fn advance_and_compare_stakes_with_rate( + &mut self, + stakes: &[(&Pubkey, &AccountSharedData)], + new_rate_activation_epoch: Option, + ) { + self.advance_epoch_with_rate(new_rate_activation_epoch) + .await; + let epoch = self.mollusk.sysvars.clock.epoch; + self.compare_stake_history(epoch - 1).await; + + for (stake, stake_account) in stakes { + let banks_effective = self.get_banks_effective_stake(stake).await; + let mollusk_effective = self.get_mollusk_effective_stake(stake_account); + assert_eq!( + banks_effective, mollusk_effective, + "Epoch {}: stake {} mismatch", + epoch, stake + ); + self.compare_account_state(stake, stake_account).await; + } + } + + /// Fund a stake account on BanksClient side + async fn fund_stake_account(&mut self, stake: &Pubkey, amount: u64) { + let fund_ix = + system_instruction::transfer(&self.program_test_ctx.payer.pubkey(), stake, amount); + let transaction = Transaction::new_signed_with_payer( + &[fund_ix], + Some(&self.program_test_ctx.payer.pubkey()), + &[&self.program_test_ctx.payer], + self.program_test_ctx.last_blockhash, + ); + self.program_test_ctx + .banks_client + .process_transaction(transaction) + .await + .unwrap(); + } + + /// Create, initialize, and fund a stake account + /// Returns (stake pubkey, stake account, staker keypair) + async fn create_and_fund_stake( + &mut self, + staked_amount: u64, + lockup: &Lockup, + ) -> (Pubkey, AccountSharedData, Keypair) { + let stake = self.create_blank_stake_account().await; + let staker = Keypair::new(); + let authorized = Authorized { + staker: staker.pubkey(), + withdrawer: Pubkey::new_unique(), + }; + + let mut stake_account = self + .initialize_stake_account(&stake, &authorized, lockup) + .await; + + stake_account.set_lamports(stake_account.lamports() + staked_amount); + self.fund_stake_account(&stake, staked_amount).await; + + (stake, stake_account, staker) + } + + /// Create and register a new vote account on BanksClient + /// Returns (vote account pubkey, vote account data) + fn create_vote_account(&mut self) -> (Pubkey, AccountSharedData) { + let vote_account = Pubkey::new_unique(); + let vote_account_data = create_vote_account(); + self.program_test_ctx + .set_account(&vote_account, &vote_account_data.clone()); + (vote_account, vote_account_data) + } + + /// Create multiple stakes with minimal funding (for testing multiple simultaneous operations) + /// Returns (stakes, stake_accounts, stakers) + async fn create_multiple_stakes( + &mut self, + count: usize, + staked_amount: u64, + ) -> (Vec, Vec, Vec) { + let mut stakes = Vec::new(); + let mut stake_accounts = Vec::new(); + let mut stakers = Vec::new(); + + for _ in 0..count { + let stake = self.create_blank_stake_account().await; + let staker = Keypair::new(); + let authorized = Authorized { + staker: staker.pubkey(), + withdrawer: Pubkey::new_unique(), + }; + + let mut stake_account = self + .initialize_stake_account(&stake, &authorized, &Lockup::default()) + .await; + + stake_account.set_lamports(stake_account.lamports() + staked_amount); + self.fund_stake_account(&stake, staked_amount).await; + + stakes.push(stake); + stake_accounts.push(stake_account); + stakers.push(staker); + } + + (stakes, stake_accounts, stakers) + } + + /// Verify background stake preservation across a range of epochs + async fn verify_background_stake_across_epochs( + &mut self, + num_epochs: u64, + expected_background: u64, + ) { + for epoch_offset in 0..num_epochs { + let epoch = self.mollusk.sysvars.clock.epoch - num_epochs + epoch_offset; + self.verify_background_stake_preservation(epoch, expected_background) + .await; + } + } +} + +// Test single delegation activation over various epoch counts +// +// Uses bulk fast-forward + sampling for large epoch counts to prove equivalence +// without excessive runtime. +#[test_case(5, 1 ; "five_epochs")] +#[test_case(10, 1 ; "ten_epochs")] +#[test_case(20, 1 ; "twenty_epochs")] +#[test_case(50, 1 ; "fifty_epochs")] +#[test_case(182, 2 ; "one_year")] +#[test_case(515, 5 ; "beyond_depth")] +#[test_case(1820, 50 ; "ten_years")] +#[tokio::test] +async fn test_single_delegation_activation(ending_epoch: u64, sample_rate: u64) { + let mut ctx = DualContext::new().await; + + // Create, initialize, and fund stake account + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + // Delegate stake + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + const BOUNDARY: u64 = 10; + + for i in 0..ending_epoch { + let is_warmup_boundary = i < BOUNDARY; + let is_end_boundary = i >= ending_epoch.saturating_sub(BOUNDARY); + let is_sample = i % sample_rate == 0; + + if is_warmup_boundary || is_end_boundary || is_sample { + // Full validation at boundaries and sample points + ctx.advance_and_compare_stake(&stake, &stake_account).await; + + // Periodic background stake checks + let check_frequency = if ending_epoch <= 50 { 10 } else { 50 }; + if i % check_frequency == 0 || i == ending_epoch - 1 { + let epoch = ctx.mollusk.sysvars.clock.epoch; + ctx.verify_background_stake_preservation(epoch - 1, ctx.background_stake) + .await; + } + } else { + ctx.advance_epoch().await; + } + } +} + +// Test deactivation at different points in lifecycle: immediately, during warmup, or after activation +#[test_case(0 ; "immediate_same_epoch")] +#[test_case(1 ; "early_warmup")] +#[test_case(2 ; "mid_warmup")] +#[test_case(3 ; "late_warmup")] +#[test_case(5 ; "after_activation")] +#[tokio::test] +async fn test_deactivation_timing(epochs_before_deactivate: u64) { + let mut ctx = DualContext::new().await; + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + for _ in 0..epochs_before_deactivate { + ctx.advance_and_compare_stake(&stake, &stake_account).await; + } + + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + + ctx.advance_until_fully_deactivated(&stake, &stake_account, 20) + .await; +} + +// Test various stake amounts through full lifecycle: activation + deactivation +// Verifies warmup/cooldown rates work correctly for minimum, small, and large stakes +#[test_case(MINIMUM_DELEGATION ; "minimum_delegation")] +#[test_case(MINIMUM_DELEGATION * 100 ; "small_amount")] +#[test_case(250_000 * 1_000_000_000 ; "large_amount")] +#[tokio::test] +async fn test_stake_amounts_full_lifecycle(staked_amount: u64) { + let mut ctx = DualContext::new().await; + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(staked_amount, &Lockup::default()) + .await; + + // Activate + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + ctx.advance_until_fully_activated(&stake, &stake_account, 50) + .await; + + // Deactivate + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + + ctx.advance_until_fully_deactivated(&stake, &stake_account, 50) + .await; +} + +// Test multiple stakes delegating simultaneously, optionally to multiple vote accounts +#[test_case(5, 1 ; "five_stakes_one_vote")] +#[test_case(10, 1 ; "ten_stakes_one_vote")] +#[test_case(20, 1 ; "twenty_stakes_one_vote")] +#[test_case(4, 2 ; "four_stakes_two_votes")] +#[tokio::test] +async fn test_multiple_simultaneous_delegations(num_stakes: usize, num_vote_accounts: usize) { + let mut ctx = DualContext::new().await; + + // Create additional vote accounts if needed + let mut vote_accounts = vec![(ctx.vote_account, ctx.vote_account_data.clone())]; + for _ in 1..num_vote_accounts { + vote_accounts.push(ctx.create_vote_account()); + } + + let (stakes, mut stake_accounts, stakers) = ctx + .create_multiple_stakes(num_stakes, MINIMUM_DELEGATION) + .await; + + // Delegate all stakes (alternating vote accounts if multiple) + for i in 0..num_stakes { + let (vote_account, vote_account_data) = &vote_accounts[i % num_vote_accounts]; + ctx.delegate_stake_to( + &stakes[i], + &mut stake_accounts[i], + &stakers[i], + vote_account, + vote_account_data, + ) + .await; + } + + for _ in 0..10 { + let stake_refs: Vec<_> = stakes.iter().zip(stake_accounts.iter()).collect(); + ctx.advance_and_compare_stakes(&stake_refs).await; + } +} + +#[tokio::test] +async fn test_concurrent_activation_and_deactivation() { + let mut ctx = DualContext::new().await; + + let (stake_a, mut stake_account_a, staker_a) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + let (stake_b, mut stake_account_b, staker_b) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + ctx.delegate_stake(&stake_b, &mut stake_account_b, &staker_b) + .await; + ctx.advance_epoch().await; + + ctx.deactivate_stake(&stake_b, &mut stake_account_b, &staker_b) + .await; + ctx.delegate_stake(&stake_a, &mut stake_account_a, &staker_a) + .await; + + let epoch = ctx.mollusk.sysvars.clock.epoch; + + for _ in 0..5 { + ctx.advance_epoch().await; + let current_epoch = ctx.mollusk.sysvars.clock.epoch; + ctx.compare_stake_history(current_epoch - 1).await; + + let banks_effective_a = ctx.get_banks_effective_stake(&stake_a).await; + let mollusk_effective_a = ctx.get_mollusk_effective_stake(&stake_account_a); + assert_eq!(banks_effective_a, mollusk_effective_a); + ctx.compare_account_state(&stake_a, &stake_account_a).await; + + let banks_effective_b = ctx.get_banks_effective_stake(&stake_b).await; + let mollusk_effective_b = ctx.get_mollusk_effective_stake(&stake_account_b); + assert_eq!(banks_effective_b, mollusk_effective_b); + ctx.compare_account_state(&stake_b, &stake_account_b).await; + } + + let banks_history = ctx.get_banks_stake_history().await; + let mollusk_history = ctx.get_mollusk_stake_history(); + + let banks_entry = banks_history.get(epoch).unwrap(); + let mollusk_entry = mollusk_history.get(epoch).unwrap(); + + assert_eq!(banks_entry.activating, mollusk_entry.activating); + assert_eq!(banks_entry.deactivating, mollusk_entry.deactivating); +} + +#[tokio::test] +async fn test_reactivation_after_deactivation() { + let mut ctx = DualContext::new().await; + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + for _ in 0..2 { + ctx.advance_and_compare_stake(&stake, &stake_account).await; + } + + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + + ctx.advance_until_fully_deactivated(&stake, &stake_account, 20) + .await; + + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + ctx.advance_until_fully_activated(&stake, &stake_account, 20) + .await; +} + +#[tokio::test] +async fn test_staggered_delegations_over_epochs() { + let mut ctx = DualContext::new().await; + + let (stakes, mut stake_accounts, stakers) = + ctx.create_multiple_stakes(5, MINIMUM_DELEGATION).await; + + // Stagger delegations across epochs (0, 5, 10, 15, 20) + for (idx, target_epoch) in [0, 5, 10, 15, 20].iter().enumerate() { + // Advance to target epoch + while ctx.mollusk.sysvars.clock.epoch < *target_epoch { + ctx.advance_epoch().await; + } + + // Delegate at this epoch + ctx.delegate_stake(&stakes[idx], &mut stake_accounts[idx], &stakers[idx]) + .await; + } + + // Advance and compare until epoch 30 + while ctx.mollusk.sysvars.clock.epoch < 30 { + let stake_refs: Vec<_> = stakes.iter().zip(stake_accounts.iter()).collect(); + ctx.advance_and_compare_stakes(&stake_refs).await; + } +} + +#[tokio::test] +async fn test_mixed_lifecycle_stress() { + let mut ctx = DualContext::new().await; + + let (stakes, mut stake_accounts, stakers) = + ctx.create_multiple_stakes(20, MINIMUM_DELEGATION).await; + + // Create various lifecycle states: + // 5 activating (delegate in epoch 0) + for i in 0..5 { + ctx.delegate_stake(&stakes[i], &mut stake_accounts[i], &stakers[i]) + .await; + } + + ctx.advance_epoch().await; // Epoch 1 + + // 5 more activating (delegate in epoch 1) + for i in 5..10 { + ctx.delegate_stake(&stakes[i], &mut stake_accounts[i], &stakers[i]) + .await; + } + + ctx.advance_epoch().await; // Epoch 2 + + // 5 deactivating + for i in 0..5 { + ctx.deactivate_stake(&stakes[i], &mut stake_accounts[i], &stakers[i]) + .await; + } + + // Advance and observe mixed states + for _ in 0..10 { + let stake_refs: Vec<_> = stakes.iter().zip(stake_accounts.iter()).collect(); + ctx.advance_and_compare_stakes(&stake_refs).await; + } +} + +// Test repeated cycles of delegation and deactivation with full transitions +#[test_case(2 ; "two_cycles")] +#[test_case(3 ; "three_cycles")] +#[tokio::test] +async fn test_repeated_delegation_cycles(num_cycles: usize) { + let mut ctx = DualContext::new().await; + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + for _ in 0..num_cycles { + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + ctx.advance_until_fully_activated(&stake, &stake_account, 20) + .await; + + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + ctx.advance_until_fully_deactivated(&stake, &stake_account, 20) + .await; + } +} + +// Test re-delegating to a different validator at various points during deactivation +// +// RedelegationTiming: +// - AfterFullActivation: Deactivate after full activation, then redelegate after full deactivation +// - DuringWarmup: Deactivate during warmup (after 2 epochs), then redelegate after full deactivation +// - DuringCooldown: Deactivate after full activation, then redelegate during cooldown (after 2 epochs) +#[test_case("AfterFullActivation" ; "after_full_deactivation")] +#[test_case("DuringWarmup" ; "after_deactivation_during_warmup")] +#[test_case("DuringCooldown" ; "during_deactivation_cooldown")] +#[tokio::test] +async fn test_redelegation_to_different_validator(timing: &str) { + let mut ctx = DualContext::new().await; + + let (vote_account_b, vote_account_b_data) = ctx.create_vote_account(); + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + // Initial delegation + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + // Setup based on timing + match timing { + "AfterFullActivation" => { + ctx.advance_until_fully_activated(&stake, &stake_account, 20) + .await; + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + ctx.advance_until_fully_deactivated(&stake, &stake_account, 20) + .await; + } + "DuringWarmup" => { + ctx.advance_and_compare_stake(&stake, &stake_account).await; + ctx.advance_and_compare_stake(&stake, &stake_account).await; + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + ctx.advance_until_fully_deactivated(&stake, &stake_account, 20) + .await; + } + "DuringCooldown" => { + ctx.advance_until_fully_activated(&stake, &stake_account, 20) + .await; + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + ctx.advance_and_compare_stake(&stake, &stake_account).await; + ctx.advance_and_compare_stake(&stake, &stake_account).await; + } + _ => panic!("Invalid timing"), + } + + // Redelegate to different validator + ctx.delegate_stake_to( + &stake, + &mut stake_account, + &staker, + &vote_account_b, + &vote_account_b_data, + ) + .await; + + // Verify immediate state after redelegation + ctx.compare_account_state(&stake, &stake_account).await; + let banks_effective = ctx.get_banks_effective_stake(&stake).await; + let mollusk_effective = ctx.get_mollusk_effective_stake(&stake_account); + assert_eq!( + banks_effective, mollusk_effective, + "Effective stake mismatch immediately after redelegation" + ); + + // Complete activation with new validator + ctx.advance_until_fully_activated(&stake, &stake_account, 20) + .await; +} + +// Test old warmup rate behavior (pre-SIMD-0093) with full lifecycle +#[tokio::test] +async fn test_old_warmup_rate_full_lifecycle() { + let mut ctx = DualContext::new().await; + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + // Activate with old warmup rate + for _ in 0..10 { + ctx.advance_and_compare_stake_with_rate(&stake, &stake_account, None) + .await; + } + + // Deactivate with old warmup rate + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + + for _ in 0..10 { + ctx.advance_and_compare_stake_with_rate(&stake, &stake_account, None) + .await; + } +} + +#[tokio::test] +async fn test_warmup_rate_transition() { + let mut ctx = DualContext::new().await; + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(MINIMUM_DELEGATION, &Lockup::default()) + .await; + + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + for _ in 0..5 { + ctx.advance_and_compare_stake_with_rate(&stake, &stake_account, None) + .await; + } + + let transition_epoch = ctx.mollusk.sysvars.clock.epoch; + + for _ in 0..10 { + ctx.advance_and_compare_stake_with_rate(&stake, &stake_account, Some(transition_epoch)) + .await; + } +} + +// Test massive stake (50% of background) through full lifecycle +// This verifies that warmup/cooldown rates work correctly when new stake significantly +// impacts the existing effective stake, and ensures background stake is preserved +#[tokio::test] +async fn test_massive_stake_full_lifecycle() { + let mut ctx = DualContext::new().await; + + // Get the background stake - use epoch 0's effective stake as the baseline + let banks_stake_history = ctx.get_banks_stake_history().await; + let background_effective = banks_stake_history + .get(0) + .map(|entry| entry.effective) + .expect("Epoch 0 must have background stake"); + + // Stake 50% of background effective stake - this is MASSIVE and will significantly + // affect warmup rates (warmup is limited by new_stake relative to existing effective) + let staked_amount = background_effective / 2; + + if staked_amount < MINIMUM_DELEGATION { + panic!( + "Bad test: background stake {} too small (need at least {})", + background_effective, + MINIMUM_DELEGATION * 2 + ); + } + + let (stake, mut stake_account, staker) = ctx + .create_and_fund_stake(staked_amount, &Lockup::default()) + .await; + + // Activate + ctx.delegate_stake(&stake, &mut stake_account, &staker) + .await; + + let epochs_to_activate = ctx + .advance_until_fully_activated(&stake, &stake_account, 50) + .await; + + // Verify background stake preserved during activation + ctx.verify_background_stake_across_epochs(epochs_to_activate, background_effective) + .await; + + // Deactivate + ctx.deactivate_stake(&stake, &mut stake_account, &staker) + .await; + + let epochs_to_deactivate = ctx + .advance_until_fully_deactivated(&stake, &stake_account, 50) + .await; + + // Verify background stake preserved during deactivation + ctx.verify_background_stake_across_epochs(epochs_to_deactivate, background_effective) + .await; +}