QST Staking Protocol - QuStream


Prepared by:

Halborn Logo

HALBORN

Last Updated 10/07/2025

Date of Engagement: September 18th, 2025 - September 25th, 2025

Summary

100% of all REPORTED Findings have been addressed

All findings

5

Critical

0

High

0

Medium

2

Low

1

Informational

2


1. Introduction

QuStream team engaged Halborn to conduct a security assessment of the qst-staking program from September 18th to September 25th, 2025. The security assessment was scoped to the smart contracts provided in the GitHub repository QuStream; commit hashes and further details can be found in the Scope section of this report.


qst-staking program is a secure, time-locked staking system on Solana designed to incentivize long-term commitment and network participation. Users can stake QST tokens in 25-day lock periods, during which they earn node keys (at a rate of two keys per 200,000 QST, subject to minimum requirements) and may optionally enroll in a bonus program that extends their commitment by an additional 10 days in exchange for enhanced rewards. The protocol incorporates a penalty-sharing mechanism , redistributing penalties collected from early unstakers among bonus enrollees, thereby aligning incentives and reinforcing protocol security.


It should be noted that changes made during the remediation phase that do not directly address the identified issues are considered out of scope for this security assessment.


2. Assessment Summary


Halborn was provided 6 days for the engagement and assigned 1 full-time security engineer to review the security of the Solana Program in scope. The engineer is blockchain and smart contract security expert with advanced smart contract hacking skills, and deep knowledge of multiple blockchain protocols .

The purpose of the assessment is to:

    • Identify potential security issues within the Solana Program.

    • Ensure that smart contract functionality operates as intended.


In summary, Halborn identified some improvements to reduce the likelihood and impact of risks, which have been addressed by the QuStream team. The main ones were the following:

    • Modify the participation window and add additional validation in unstake_tokens in order to prevent unstaking until the stake window has ended.

    • Decouple the withdrawal process into two distinct steps.

    • Remove the ability to restart a staking window or introduce a stake_window_idstored in both pool and user stake accounts.

3. Test Approach and Methodology


Halborn performed a combination of a manual review of the source code and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of the program assessment. While manual testing is recommended to uncover flaws in business logic, processes, and implementation; automated testing techniques help enhance coverage of programs and can quickly identify items that do not follow security best practices.

The following phases and associated tools were used throughout the term of the assessment:

    • Research into the architecture, purpose, and use of the platform.

    • Manual program source code review to identify business logic issues.

    • Mapping out possible attack vectors.

    • Thorough assessment of safety and usage of critical Rust variables and functions in scope that could lead to arithmetic vulnerabilities.

    • Scanning dependencies for known vulnerabilities (cargo audit).

    • Local runtime testing (anchor test and <solana-test-framework).


4. RISK METHODOLOGY

Every vulnerability and issue observed by Halborn is ranked based on two sets of Metrics and a Severity Coefficient. This system is inspired by the industry standard Common Vulnerability Scoring System.
The two Metric sets are: Exploitability and Impact. Exploitability captures the ease and technical means by which vulnerabilities can be exploited and Impact describes the consequences of a successful exploit.
The Severity Coefficients is designed to further refine the accuracy of the ranking with two factors: Reversibility and Scope. These capture the impact of the vulnerability on the environment as well as the number of users and smart contracts affected.
The final score is a value between 0-10 rounded up to 1 decimal place and 10 corresponding to the highest security risk. This provides an objective and accurate rating of the severity of security vulnerabilities in smart contracts.
The system is designed to assist in identifying and prioritizing vulnerabilities based on their level of risk to address the most critical issues in a timely manner.

4.1 EXPLOITABILITY

Attack Origin (AO):
Captures whether the attack requires compromising a specific account.
Attack Cost (AC):
Captures the cost of exploiting the vulnerability incurred by the attacker relative to sending a single transaction on the relevant blockchain. Includes but is not limited to financial and computational cost.
Attack Complexity (AX):
Describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. Includes but is not limited to macro situation, available third-party liquidity and regulatory challenges.
Metrics:
EXPLOITABILITY METRIC (mem_e)METRIC VALUENUMERICAL VALUE
Attack Origin (AO)Arbitrary (AO:A)
Specific (AO:S)
1
0.2
Attack Cost (AC)Low (AC:L)
Medium (AC:M)
High (AC:H)
1
0.67
0.33
Attack Complexity (AX)Low (AX:L)
Medium (AX:M)
High (AX:H)
1
0.67
0.33
Exploitability EE is calculated using the following formula:

E=meE = \prod m_e

4.2 IMPACT

Confidentiality (C):
Measures the impact to the confidentiality of the information resources managed by the contract due to a successfully exploited vulnerability. Confidentiality refers to limiting access to authorized users only.
Integrity (I):
Measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of data stored and/or processed on-chain. Integrity impact directly affecting Deposit or Yield records is excluded.
Availability (A):
Measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. This metric refers to smart contract features and functionality, not state. Availability impact directly affecting Deposit or Yield is excluded.
Deposit (D):
Measures the impact to the deposits made to the contract by either users or owners.
Yield (Y):
Measures the impact to the yield generated by the contract for either users or owners.
Metrics:
IMPACT METRIC (mIm_I)METRIC VALUENUMERICAL VALUE
Confidentiality (C)None (C:N)
Low (C:L)
Medium (C:M)
High (C:H)
Critical (C:C)
0
0.25
0.5
0.75
1
Integrity (I)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Availability (A)None (A:N)
Low (A:L)
Medium (A:M)
High (A:H)
Critical (A:C)
0
0.25
0.5
0.75
1
Deposit (D)None (D:N)
Low (D:L)
Medium (D:M)
High (D:H)
Critical (D:C)
0
0.25
0.5
0.75
1
Yield (Y)None (Y:N)
Low (Y:L)
Medium (Y:M)
High (Y:H)
Critical (Y:C)
0
0.25
0.5
0.75
1
Impact II is calculated using the following formula:

I=max(mI)+mImax(mI)4I = max(m_I) + \frac{\sum{m_I} - max(m_I)}{4}

4.3 SEVERITY COEFFICIENT

Reversibility (R):
Describes the share of the exploited vulnerability effects that can be reversed. For upgradeable contracts, assume the contract private key is available.
Scope (S):
Captures whether a vulnerability in one vulnerable contract impacts resources in other contracts.
Metrics:
SEVERITY COEFFICIENT (CC)COEFFICIENT VALUENUMERICAL VALUE
Reversibility (rr)None (R:N)
Partial (R:P)
Full (R:F)
1
0.5
0.25
Scope (ss)Changed (S:C)
Unchanged (S:U)
1.25
1
Severity Coefficient CC is obtained by the following product:

C=rsC = rs

The Vulnerability Severity Score SS is obtained by:

S=min(10,EIC10)S = min(10, EIC * 10)

The score is rounded up to 1 decimal places.
SeverityScore Value Range
Critical9 - 10
High7 - 8.9
Medium4.5 - 6.9
Low2 - 4.4
Informational0 - 1.9

5. SCOPE

REPOSITORY
(a) Repository: qst-staking
(b) Assessed Commit ID: 6b5385d
(c) Items in scope:
  • programs/qst-staking/src/lib.rs
  • programs/qst-staking/Cargo.toml
  • programs/qst-staking/src/lib_devnet.rs
Out-of-Scope: Third party dependencies and economic attacks.
Remediation Commit ID:
  • 40b0a25
  • a3ec342
Out-of-Scope: New features/implementations after the remediation commit IDs.

6. Assessment Summary & Findings Overview

Critical

0

High

0

Medium

2

Low

1

Informational

2

Security analysisRisk levelRemediation Date
Restaking During Stake Window Enables Node Key Inflation and OverwriteMediumSolved - 10/07/2025
Potential Inconsistent Bonus Reward Distribution in Staking ProtocolMediumSolved - 10/07/2025
Stake Window Reset Leads to Bonus Enrollment and Early Unstaking BypassLowSolved - 10/04/2025
Lack of Zero Amount Validation in unstake_tokens InstructionInformationalSolved - 10/04/2025
Redundant or Duplicated Validation Checks in Staking InstructionsInformationalPartially Solved - 10/04/2025

7. Findings & Tech Details

7.1 Restaking During Stake Window Enables Node Key Inflation and Overwrite

//

Medium

Description

The stake_tokens instruction allows users to lock QST tokens during a 14-day stake window. Once a user stakes its tokens, they are subject to a 25-day principal unlock period from its last staking action, during which withdrawals are restricted.


Users may perform early unstakes at the cost of a penalty: 20% if the unlock period will expire in less than 10 days, or 30% if it will expire in less than 20 days.


However, this design creates a temporal overlap between the 14-day stake window and the early-unstake period. As a result, a user who staked near the beginning of the window can prematurely unstake (e.g., 5 days later from staking), while the stake window is still open. This overlap enables the user to immediately restake, leading to two vulnerabilities:

  • Node Key Inflation via Partial Restake: If a user partially unstakes and then restakes the unstaked tokens, the program incorrectly increases the number of node keys associated with their stake account. This allows users to gain additional node keys for the same tokens, violating intended economic incentives.

  • Node Key Overwrite via Full Restake: If a user fully unstakes and then restakes all the obtained tokens, the program treats the stake account as “new” (since its recorded amount becomes zero). This causes the node_keys_earned field to be overwritten, erasing node keys that should be permanent and preserved across staking and withdrawal events.


programs/qst-staking/src/lib.rs

 pub fn unstake_tokens(ctx: Context<UnstakeTokens>, amount: u64) -> Result<()> {
        let stake_account = &mut ctx.accounts.stake_account;
        let staking_pool = &mut ctx.accounts.staking_pool;

        require!(stake_account.amount >= amount, ErrorCode::InsufficientStakeBalance);

        // Block unstaking completely for bonus enrolled users
        require!(!stake_account.enrolled_in_bonus, ErrorCode::BonusEnrolledCannotUnstake);

        let current_time = Clock::get()?.unix_timestamp;
        let time_until_unlock = stake_account.principal_unlock_time - current_time;

        // Early exit options (relative to current principal unlock date)
        let (penalty_amount, net_amount) = if time_until_unlock <= 0 {
            // Unlocked: No penalty
            (0u64, amount)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_1 {
            // 10—0 days remaining: 20% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_LATE as u128) / 100u128) as u64;
            (penalty, amount - penalty)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_2 {
            // 20—10 days remaining: 30% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_EARLY as u128) / 100u128) as u64;
            (penalty, amount - penalty)

const EARLY_UNSTAKE_THRESHOLD_1: i64 = 10 * 24 * 60 * 60; // 10 days
const EARLY_UNSTAKE_THRESHOLD_2: i64 = 20 * 24 * 60 * 60; // 20 days

// === PENALTIES ===
const PENALTY_RATE_EARLY: u64 = 30; // 30% penalty for 20—10 days remaining
const PENALTY_RATE_LATE: u64 = 20;  // 20% penalty for 10—0 days remaining

        require!(
            current_time <= staking_pool.stake_window_end,
            ErrorCode::StakeWindowClosed
        );
        msg!("✅ Stake window is active");

        // Calculate number of keys based on stake amount
        let stake_multiplier = amount / MINIMUM_STAKE_AMOUNT;
        
        // Use checked math and try_from to prevent overflow/truncation
let raw_keys = stake_multiplier
            .checked_mul(KEYS_PER_STAKE as u64)
            .ok_or(ErrorCode::NumericOverflow)?;
        let node_keys_earned = u32::try_from(raw_keys).map_err(|_| ErrorCode::NumericOverflow)?;
        
        msg!("Node keys to earn: {}", node_keys_earned);

        // Transfer tokens from user to pool
        msg!("🔄 Starting token transfer");
        let cpi_accounts = Transfer {
            from: user_token_account.to_account_info(),
            to: pool_token_account.to_account_info(),
            authority: ctx.accounts.user.to_account_info(),
        };
        let cpi_program = ctx.accounts.token_program.to_account_info();
        let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
        token::transfer(cpi_ctx, amount)?;
        msg!("✅ Token transfer completed");

        // Initialize or update stake account
        if stake_account.amount == 0 {
            msg!("🆕 Initializing new stake account");
            stake_account.user = ctx.accounts.user.key();
            stake_account.amount = amount;
            stake_account.node_keys_earned = node_keys_earned;

            // Reset lock model - unlock time based on current stake time
            stake_account.principal_unlock_time = current_time + PRINCIPAL_LOCK_PERIOD;

            // Not enrolled by default; bonus unlock remains 0 until enroll
            stake_account.bonus_unlock_time = 0;
            stake_account.enrolled_in_bonus = false;
            stake_account.bump = ctx.bumps.stake_account;
        } else {
            msg!("📈 Updating existing stake account");
            stake_account.amount = stake_account
                .amount
                .checked_add(amount)
                .ok_or(ErrorCode::NumericOverflow)?;
            stake_account.node_keys_earned = stake_account
                .node_keys_earned
                .checked_add(node_keys_earned)
                .ok_or(ErrorCode::NumericOverflow)?;

            // Reset lock model - set unlock to current_time + 25 days
            stake_account.principal_unlock_time = current_time + PRINCIPAL_LOCK_PERIOD;

The root cause of this issue lies in the overlapping timelines between the stake window and the principal unlock period, combined with logic that determines whether an account is “new” solely by checking if its stake_amount == 0. Together, these flaws allow users to either inflate or lose node keys through unintended restaking behavior.

BVSS
Recommendation

To address this issue, it is recommended to modify the participation window and add additional validation in unstake_tokens in order to prevent unstaking until the stake window has ended. Consider replacing the verification to check if the participation account user is the default public key.

Remediation Comment

SOLVED: The QuStream team solved this issue by:

  • Reducing the stake window duration.

  • Reducing EARLY_UNSTAKE_THRESHOLD_1 and EARLY_UNSTAKE_THRESHOLD_2.

  • Adding validation to prevent unstaking prior to stake window closure.



Remediation Hash
40b0a254351ca04573893de84566cdd002af06d2

7.2 Potential Inconsistent Bonus Reward Distribution in Staking Protocol

//

Medium

Description

The start_stake_window instruction initiates a staking window where:

  • The window remains open for 14 days from activation, during which users can stake tokens.

  • A 48-hour enrollment period is enforced from the beginning of the window for users who wish to participate in the bonus program.

  • Users who stake can withdraw their principal only 25 days after their last stake action.

  • Bonus-enrolled users must wait an additional 10 days beyond the principal unlock period before withdrawal.


Additional mechanics are as follows:

  • Early Unstake for Non-Bonus Users: Non-bonus users are permitted to unstake early by paying a penalty (30% if 20–10 days remain before unlock; 20% if within 10 days).

  • Penalty Redistribution: Penalties collected from premature unstakers are redistributed to bonus-enrolled users when those users withdraw after completing their full lock period.


An inconsistency in reward distribution was identified. The following scenario illustrates the issue:

  • Day 0: Staking window opens.

  • Day 1: Alice and Bob stake and enroll in the bonus program. Their withdrawal eligibility is at Day 36 (1 + 25 + 10).

  • Day 5: Alice stakes again, extending her withdrawal eligibility to Day 40 (5 + 25 + 10).

  • Day 14: Tom stakes without enrolling in the bonus program. His withdrawal eligibility is at Day 39 (14 + 25).

  • Day 36: Bob withdraws and receives only his staked amount because no penalties have been collected yet.

  • Day 37: Tom performs an early unstake and is charged the applicable penalty.

  • Day 40: Alice withdraws and receives her staked tokens plus the penalties collected from Tom.


This behavior produces a reward distribution inconsistency: Bob, who complied with the bonus program’s extended lock-up, receives no share of penalties because withdrawal occurred before penalties were generated. Conversely, Alice, who staked later and extended her lock-up, receives the full penalty redistribution even though Bob was also a qualifying bonus participant.


The outcome results in a misalignment between participant expectations and reward mechanics. Bonus-enrolled users who fulfill the extended lock-up may not receive redistributed penalties depending on the timing of other participants’ early unstakes. This undermines perceived fairness in the bonus reward system and may discourage participation in the bonus program.


programs/qst-staking/src/lib.rs

        let principal_amount = stake_account.amount;
        let mut bonus_rewards = 0u64;

        // Calculate bonus rewards if enrolled and bonus period ended
        if stake_account.enrolled_in_bonus && current_time >= stake_account.bonus_unlock_time {
            if staking_pool.total_enrolled_stake > 0 && staking_pool.penalty_vault_amount > 0 {
                // Use u128 to prevent overflow in proportional calculation
                let pv = staking_pool.penalty_vault_amount as u128;
                let user_amt = stake_account.amount as u128;
                let total = staking_pool.total_enrolled_stake as u128;
                bonus_rewards = if total > 0 { ((pv * user_amt) / total) as u64 } else { 0 };
                
                staking_pool.penalty_vault_amount =
                    staking_pool.penalty_vault_amount.saturating_sub(bonus_rewards);
            }
        }

        let total_withdrawal = principal_amount + bonus_rewards;


  // Initialize or update stake account
        if stake_account.amount == 0 {
            msg!("🆕 Initializing new stake account");
            stake_account.user = ctx.accounts.user.key();
            stake_account.amount = amount;
            stake_account.node_keys_earned = node_keys_earned;

            // Reset lock model - unlock time based on current stake time
            stake_account.principal_unlock_time = current_time + PRINCIPAL_LOCK_PERIOD;

            // Not enrolled by default; bonus unlock remains 0 until enroll
            stake_account.bonus_unlock_time = 0;
            stake_account.enrolled_in_bonus = false;
            stake_account.bump = ctx.bumps.stake_account;
        } else {
            msg!("📈 Updating existing stake account");
            stake_account.amount = stake_account
                .amount
                .checked_add(amount)
                .ok_or(ErrorCode::NumericOverflow)?;
            stake_account.node_keys_earned = stake_account
                .node_keys_earned
                .checked_add(node_keys_earned)
                .ok_or(ErrorCode::NumericOverflow)?;

            // Reset lock model - set unlock to current_time + 25 days
            stake_account.principal_unlock_time = current_time + PRINCIPAL_LOCK_PERIOD;

            // If already enrolled, bonus unlock follows principal (principal + 10d)
            if stake_account.enrolled_in_bonus {
                stake_account.bonus_unlock_time = stake_account.principal_unlock_time + BONUS_LOCK_PERIOD;
            }
        }

BVSS
Recommendation

To address this issue, it is recommended to implement one of the following measures:

  • Force that it can only be withdrawn once the period of possible premature unstakes has passed ensuring that bonus-enrolled users can only withdraw once the early-unstake period has fully expired.

  • Decouple the withdrawal process into two distinct steps:

    • Withdrawal of Principal Staked Tokens: Bonus-enrolled users should be able to withdraw their original staked tokens once their principal unlock period (plus any additional bonus lock-up period) has expired, ensuring that the withdrawal of staked tokens is independent of any penalties collected from early unstakers.

    • Withdrawal of Proportional Bonus Penalties: A separate instruction should allow bonus-enrolled users to withdraw their share of redistributed penalties at a later point, once penalties have been collected from early unstakers.


Remediation Comment

SOLVED: The QuStream team solved this issue by splitting the withdrawal flow into two instructions, withdraw_all and withdraw_bonus. Under the implemented design, deposits may be withdrawn after the corresponding bonus lock period has expired, and the share of bonus penalties may be withdrawn later once any applicable penalties have been applied.

Remediation Hash
40b0a254351ca04573893de84566cdd002af06d2

7.3 Stake Window Reset Leads to Bonus Enrollment and Early Unstaking Bypass

//

Low

Description

The emergency_pause instruction allows the staking pool administrator to pause the active staking window by setting both stake_window_end and bonus_enrollment_deadline to zero. Conversely, the start_stake_window instruction enables the administrator to start a new staking window, provided it is the first activation or the previous stake_window_end has elapsed.


programs/qst-staking/src/lib.rs

pub fn start_stake_window(ctx: Context<StartStakeWindow>) -> Result<()> {
        let staking_pool = &mut ctx.accounts.staking_pool;

        // Add admin access control
        require!(
            ctx.accounts.admin.key() == staking_pool.authority, 
            ErrorCode::Unauthorized
        );

        // Prevent restarting an active window (optional policy)
        require!(
            staking_pool.first_stake_timestamp == 0 || Clock::get()?.unix_timestamp > staking_pool.stake_window_end,
            ErrorCode::StakeWindowAlreadyActive
        );

        let current_time = Clock::get()?.unix_timestamp;
        staking_pool.first_stake_timestamp = current_time;
        staking_pool.stake_window_end = current_time + STAKE_WINDOW_PERIOD;
        staking_pool.bonus_enrollment_deadline = current_time + BONUS_ENROLLMENT_PERIOD;

This design introduces a potential vulnerability if the administrator executes emergency_pause immediately followed by start_stake_window in an attempt to reset the staking window. Under this scenario, users who staked during the prior (now inactive) window may interact incorrectly with the newly created window:

  • Bonus Enrollment Bypass: A user who staked before the reset can still call enroll_in_bonus during the new window, even if they never enrolled in the bonus program of the original (expired) window. This occurs because enroll_in_bonus validates only the current bonus_enrollment_deadline against the current timestamp, without considering the staking window in which the user originally staked.

  • Premature Unstaking: Similarly, a user who staked before the reset can call unstake_tokens based on the principal_unlock_time recorded in their stake account. Since this value was derived from the expired window, the user may be able to withdraw their staked tokens earlier than expected relative to the requirements of the newly active staking window.


As a result, resetting the staking window via emergency_pause and start_stake_window can lead to inconsistent staking state across users, allowing them to bypass intended restrictions on bonus eligibility and early unstaking.


programs/qst-staking/src/lib.rs

pub fn enroll_in_bonus(ctx: Context<EnrollInBonus>) -> Result<()> {
        let staking_pool = &mut ctx.accounts.staking_pool;
        let stake_account = &mut ctx.accounts.stake_account;

        let current_time = Clock::get()?.unix_timestamp;

        // Check if bonus enrollment is still open
        require!(
            current_time <= staking_pool.bonus_enrollment_deadline,
            ErrorCode::BonusEnrollmentClosed
        );

pub fn unstake_tokens(ctx: Context<UnstakeTokens>, amount: u64) -> Result<()> {
        let stake_account = &mut ctx.accounts.stake_account;
        let staking_pool = &mut ctx.accounts.staking_pool;

        require!(stake_account.amount >= amount, ErrorCode::InsufficientStakeBalance);

        // Block unstaking completely for bonus enrolled users
        require!(!stake_account.enrolled_in_bonus, ErrorCode::BonusEnrolledCannotUnstake);

        let current_time = Clock::get()?.unix_timestamp;
        let time_until_unlock = stake_account.principal_unlock_time - current_time;

        // Early exit options (relative to current principal unlock date)
        let (penalty_amount, net_amount) = if time_until_unlock <= 0 {
            // Unlocked: No penalty
            (0u64, amount)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_1 {
 // 10—0 days remaining: 20% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_LATE as u128) / 100u128) as u64;
            (penalty, amount - penalty)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_2 {

Furthermore, it is important to note that the start_stake_window instruction only checks whether staking_pool.first_stake_timestamp == 0 || Clock::get()?.unix_timestamp > staking_pool.stake_window_end before allowing execution. This also permits restarting the staking window once the original period has elapsed. Since the intended design goal is to enforce a unique, single-use staking window, this behavior introduces inconsistencies and potential vulnerabilities by allowing multiple windows to exist sequentially when only one should ever be valid.

BVSS
Recommendation

To address this issue and prevent inconsistent staking states caused by combining emergency_pause and start_stake_window, it is recommended to implement one of the following measures:

  • Remove the ability to restart a staking window, eliminating checks where the stake_window_end is validated to be exceeded. In this case, consider removing the emergency_pause instruction as well, if it is not needed or expected to be used.

  • If a restart is required, introduce a stake_window_id stored in both pool and user stake accounts, ensuring enroll_in_bonus and unstake_tokens validate against the correct window ID.

This ensures users cannot bypass bonus eligibility or early-unstake rules when windows are reset.

Remediation Comment

SOLVED: The QuStream team solved this issue by removing the emergency_pause instruction and by removing the check in start_stake_window that required stake_window_end to have been exceeded.


Remediation Hash
a3ec34265d5fdd12c28197cc6963da47caec27f4

7.4 Lack of Zero Amount Validation in unstake_tokens Instruction

//

Informational

Description

The unstake_tokens instruction allows users who have previously staked tokens without enrolling in the bonus program to withdraw their stake. If the unstake is performed before the principal unlock date, a penalty is applied: 20% if the unlock time is within 10 days, or 30% if it is within 20 days.


The instruction requires the user to specify the amount to be unstaked and correctly enforces an upper bound check to ensure that this amount does not exceed the user’s recorded stake. However, it does not enforce a lower bound check to guarantee that the amount is greater than zero. As a result, users can submit an unstake request with a value of 0.


While this has no effect on their stake balance, the transaction still executes successfully, unnecessarily consuming compute resources and forcing the user to pay transaction fees without any meaningful outcome.


programs/qst-staking/src/lib.rs

pub fn unstake_tokens(ctx: Context<UnstakeTokens>, amount: u64) -> Result<()> {
        let stake_account = &mut ctx.accounts.stake_account;
        let staking_pool = &mut ctx.accounts.staking_pool;

        require!(stake_account.amount >= amount, ErrorCode::InsufficientStakeBalance);

        // Block unstaking completely for bonus enrolled users
        require!(!stake_account.enrolled_in_bonus, ErrorCode::BonusEnrolledCannotUnstake);

        let current_time = Clock::get()?.unix_timestamp;
        let time_until_unlock = stake_account.principal_unlock_time - current_time;

        // Early exit options (relative to current principal unlock date)
        let (penalty_amount, net_amount) = if time_until_unlock <= 0 {
            // Unlocked: No penalty
            (0u64, amount)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_1 {
            // 10—0 days remaining: 20% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_LATE as u128) / 100u128) as u64;
            (penalty, amount - penalty)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_2 {
            // 20—10 days remaining: 30% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_EARLY as u128) / 100u128) as u64;
            (penalty, amount - penalty)
        } else {
            // More than 20 days remaining: Unstake blocked
            return Err(ErrorCode::UnstakeBlocked.into());
        };

BVSS
Recommendation

To address this issue, it is recommended to add a validation to ensure the zero value amount cannot be unstaked.

Remediation Comment

SOLVED: The QuStream team solved this issue by introducing a validation to require that the provided amount value is greater than 0.

Remediation Hash
a3ec34265d5fdd12c28197cc6963da47caec27f4

7.5 Redundant or Duplicated Validation Checks in Staking Instructions

//

Informational

Description

Several fragments of code in the staking program contain redundant or duplicated validations. For instance, the second check (bonus_enrollment_deadline > 0) in the enroll_in_bonus instruction is unnecessary because it is implicitly guaranteed by the first condition: if current_time <= bonus_enrollment_deadline, then bonus_enrollment_deadline must be greater than zero (given that current_time cannot be negative in this context).


programs/qst-staking/src/lib.rs

pub fn enroll_in_bonus(ctx: Context<EnrollInBonus>) -> Result<()> {
        let staking_pool = &mut ctx.accounts.staking_pool;
        let stake_account = &mut ctx.accounts.stake_account;

        let current_time = Clock::get()?.unix_timestamp;

        // Check if bonus enrollment is still open
        require!(
            current_time <= staking_pool.bonus_enrollment_deadline,
            ErrorCode::BonusEnrollmentClosed
        );
        require!(
            staking_pool.bonus_enrollment_deadline > 0,
            ErrorCode::StakeWindowNotStarted
        );

Similar redundant validations have been detected in other instructions, such as withdraw_all, get_stake_info and unstake_tokens.


While this does not introduce a functional vulnerability, the redundancy increases code complexity and maintenance overhead.

let mut bonus_rewards = 0u64;

        // Calculate bonus rewards if enrolled and bonus period ended
        if stake_account.enrolled_in_bonus && current_time >= stake_account.bonus_unlock_time {
            if staking_pool.total_enrolled_stake > 0 && staking_pool.penalty_vault_amount > 0 {
                // Use u128 to prevent overflow in proportional calculation
                let pv = staking_pool.penalty_vault_amount as u128;
                let user_amt = stake_account.amount as u128;
                let total = staking_pool.total_enrolled_stake as u128;
                bonus_rewards = if total > 0 { ((pv * user_amt) / total) as u64 } else { 0 };
                
                staking_pool.penalty_vault_amount =
                    staking_pool.penalty_vault_amount.saturating_sub(bonus_rewards);
            }

  pub fn get_stake_info(ctx: Context<GetStakeInfo>) -> Result<StakeInfo> {
        let stake_account = &ctx.accounts.stake_account;
        let staking_pool = &ctx.accounts.staking_pool;

        // Calculate potential bonus (simple pro-rata preview)
        let potential_bonus = if stake_account.enrolled_in_bonus && staking_pool.total_enrolled_stake > 0 {
            let pv = staking_pool.penalty_vault_amount as u128;
            let user_amt = stake_account.amount as u128;
            let total = staking_pool.total_enrolled_stake as u128;
            if total > 0 { ((pv * user_amt) / total) as u64 } else { 0 }
        } else {
            0
        };

        require!(!stake_account.enrolled_in_bonus, ErrorCode::BonusEnrolledCannotUnstake);

        let current_time = Clock::get()?.unix_timestamp;
        let time_until_unlock = stake_account.principal_unlock_time - current_time;

        // Early exit options (relative to current principal unlock date)
        let (penalty_amount, net_amount) = if time_until_unlock <= 0 {
            // Unlocked: No penalty
            (0u64, amount)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_1 {
            // 10—0 days remaining: 20% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_LATE as u128) / 100u128) as u64;
            (penalty, amount - penalty)
        } else if time_until_unlock <= EARLY_UNSTAKE_THRESHOLD_2 {
            // 20—10 days remaining: 30% penalty
            let penalty = ((amount as u128) * (PENALTY_RATE_EARLY as u128) / 100u128) as u64;
            (penalty, amount - penalty)
        } else {
            // More than 20 days remaining: Unstake blocked
            return Err(ErrorCode::UnstakeBlocked.into());
        };

        let user_token_account = &ctx.accounts.user_token_account;
        let pool_token_account = &ctx.accounts.pool_token_account;

        // Setup PDA signer
        let authority_seed = b"staking_pool";
        let bump_bytes = [staking_pool.bump];
        let signer_seeds = &[authority_seed.as_ref(), bump_bytes.as_ref()];
        let signer = &[signer_seeds.as_ref()];

        // Transfer net amount to user
        if net_amount > 0 {
            let cpi_accounts = Transfer {
                from: pool_token_account.to_account_info(),
                to: user_token_account.to_account_info(),
                authority: staking_pool.to_account_info(),
            };
            let cpi_program = ctx.accounts.token_program.to_account_info();
            let cpi_ctx = CpiContext::new_with_signer(cpi_program, cpi_accounts, signer);
            token::transfer(cpi_ctx, net_amount)?;
        }

        // Add penalty to the penalty vault (stays in pool for enrolled users)
        if penalty_amount > 0 {
            staking_pool.penalty_vault_amount = staking_pool
                .penalty_vault_amount
                .checked_add(penalty_amount)
                .ok_or(ErrorCode::NumericOverflow)?;
        }

        // If enrolled, reduce the enrolled pool weight by the amount being unstaked
        if stake_account.enrolled_in_bonus {
            staking_pool.total_enrolled_stake = staking_pool
                .total_enrolled_stake
                .saturating_sub(amount);
        }

BVSS
Recommendation

To address this issue, consider removing redundant validations and maintaining only the necessary checks.

Remediation Comment

PARTIALLY SOLVED: The QuStream team partially solved this issue by removing the redundant parts found in enroll_in_bonus and get_stake_info instructions.

Remediation Hash
a3ec34265d5fdd12c28197cc6963da47caec27f4

8. Automated Testing

Static Analysis Report

Description

Halborn used automated security scanners to assist with the detection of well-known security issues and vulnerabilities. Among the tools used was cargo-audit, a security scanner for vulnerabilities reported to the RustSec Advisory Database. All vulnerabilities published in https://crates.io are stored in a repository named The RustSec Advisory Database. cargo audit is a human-readable version of the advisory database which performs a scanning on Cargo.lock. Security Detections are only in scope. All vulnerabilities shown here were already disclosed in the above report. However, to better assist the developers maintaining this code, the reviewers are including the output with the dependencies tree, and this is included in the cargo audit output to better know the dependencies affected by unmaintained and vulnerable crates.


Results

ID

package

Short Description

RUSTSEC-2024-0344

curve25519-dalek

Timing variability in curve25519-dalek's Scalar29::sub/Scalar52::sub

RUSTSEC-2022-0093

ed25519-dalek

Double Public Key Signing Function Oracle Attack on ed25519-dalek



Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.

© Halborn 2025. All rights reserved.