Rust Fund

AI First Flight #9
Beginner FriendlyRust
EXP
View results
Submission Details
Severity: high
Valid

`contribute` does not update `contribution.amount`; refund returns 0

rustfund::lib::contribute · Confidence: 75 (capped from 92 by criteria-divergence) · Severity: High

Validation summary

Stage Verdict Note
2 — Audit candidate at High, conf 95 Invariant, Math Precision, Execution Trace, First Principles
3 — PoC ADVANCE Tier 2 (TS test using a distinct contributor wallet, exposing the bug masked by the project's own test)
4 — Adversarial Pass D calibrated High (CONFIRMED) Challenge 2 ("project's own test passes") is itself evidence — the test masks the bug by reusing the creator wallet as contributor
5 — Platform ADVANCE at High, score 92/100 aligns with CodeHawks "High"
6 — Program in-scope same scope chain as F-01
7 — Duplication no hard duplicates same baseline as F-01

Root cause

contribute (programs/rustfund/src/lib.rs:25-52) increments fund.amount_raised += amount on the Fund-side accounting but never increments the matching contribution.amount field on the Contribution-side accounting. Since refund reads contribution.amount as the lamport debit amount, the contributor's recovery path is structurally severed.

Location

  • rustfund::lib::contributeprograms/rustfund/src/lib.rs:25-52 (specifically the absent increment between lib.rs:48 and lib.rs:50)

  • (impact site) rustfund::lib::refundprograms/rustfund/src/lib.rs:68

Exploit path

  1. Contributor calls contribute(500_000_000). Fund PDA receives the 0.5 SOL via system_program::transfer; fund.amount_raised = 500_000_000.

  2. The init-branch of contribute (entered on the contributor's first call) writes contribution.amount = 0 (lib.rs:37). No subsequent line writes a non-zero value.

  3. Contributor calls refund. The function reads let amount = ctx.accounts.contribution.amount; // = 0; debits Fund lamports by 0; credits contributor lamports by 0; resets contribution.amount = 0. The contributor receives nothing.

  4. The contributor's 0.5 SOL is permanently stranded inside the Fund PDA. Combined with F-01, the creator can sweep it; standalone (with F-01 fixed), the contributor still cannot retrieve it.

Proof of concept

  • tier: 2 (TS integration test using a fresh Keypair.generate() contributor — the project's existing test reuses creator.publicKey for both creator and contributor, which is why this bug was not caught by the harness)

  • file: argus/20260504T004143Z/3-poc/F-02/poc.ts

  • reproduction: argus/20260504T004143Z/3-poc/F-02/repro.md

  • proven impact: After contribute(0.5 SOL), fund.amountRaised = 0.5 SOL but contributionAccount.amount = 0. After refund, the contributor's wallet balance is strictly less than before (paid tx fees, recovered nothing); the Fund PDA still holds 0.5 SOL.

F-02 reproduction

// PoC for F-02 — `contribute` does not update `contribution.amount`,
// so `refund` returns 0 lamports and contributors cannot recover funds.
//
// Drop in `tests/poc-F-02.ts` and run `anchor test`.
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Rustfund } from "../target/types/rustfund";
import { PublicKey, Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js";
import { expect } from "chai";
describe("F-02 contribute does not update contribution.amount", () => {
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
const program = anchor.workspace.Rustfund as Program<Rustfund>;
const creator = provider.wallet;
const contributor = Keypair.generate();
const fundName = "F-02-broken-refund-fund";
const description = "F-02 demonstrates contribution.amount=0 bug";
const goal = new anchor.BN(10 * LAMPORTS_PER_SOL);
const contribution = new anchor.BN(0.5 * LAMPORTS_PER_SOL);
let fundPDA: PublicKey;
let contributionPDA: PublicKey;
before(async () => {
const sig = await provider.connection.requestAirdrop(contributor.publicKey, 2 * LAMPORTS_PER_SOL);
await provider.connection.confirmTransaction(sig);
[fundPDA] = await PublicKey.findProgramAddress(
[Buffer.from(fundName), creator.publicKey.toBuffer()],
program.programId
);
[contributionPDA] = await PublicKey.findProgramAddress(
[fundPDA.toBuffer(), contributor.publicKey.toBuffer()],
program.programId
);
});
it("after contribute(0.5 SOL), contribution.amount is still 0", async () => {
await program.methods
.fundCreate(fundName, description, goal)
.accounts({
fund: fundPDA,
creator: creator.publicKey,
systemProgram: SystemProgram.programId,
})
.rpc();
// Contributor sends 0.5 SOL.
await program.methods
.contribute(contribution)
.accounts({
fund: fundPDA,
contributor: contributor.publicKey,
contribution: contributionPDA,
systemProgram: SystemProgram.programId,
})
.signers([contributor])
.rpc();
const fund = await program.account.fund.fetch(fundPDA);
const contributionAccount = await program.account.contribution.fetch(contributionPDA);
// Sanity: SOL transfer happened (Fund-side accounting incremented).
expect(fund.amountRaised.toNumber()).to.equal(0.5 * LAMPORTS_PER_SOL);
// Bug: contribution-side accounting did NOT increment.
expect(contributionAccount.amount.toNumber()).to.equal(0);
// The two views of "how much was contributed" disagree.
expect(fund.amountRaised.toNumber()).to.not.equal(contributionAccount.amount.toNumber());
});
it("refund returns 0 lamports because contribution.amount is 0", async () => {
// Fund's deadline is 0 (never set), so the deadline guard short-circuits
// and refund executes regardless. (This is also F-04.)
const contributorBefore = await provider.connection.getBalance(contributor.publicKey);
await program.methods
.refund()
.accounts({
fund: fundPDA,
contribution: contributionPDA,
contributor: contributor.publicKey,
systemProgram: SystemProgram.programId,
})
.signers([contributor])
.rpc();
const contributorAfter = await provider.connection.getBalance(contributor.publicKey);
// The contributor's balance went DOWN (because of tx fees for the refund call)
// — they did NOT recover the 0.5 SOL they contributed.
expect(contributorAfter).to.be.lessThanOrEqual(contributorBefore);
// Fund still holds the 0.5 SOL contribution.
const fundLamports = await provider.connection.getBalance(fundPDA);
expect(fundLamports).to.be.greaterThan(0.49 * LAMPORTS_PER_SOL);
});
});

Setup

Same as F-01 — install the Solana / Anchor toolchain and run yarn install from the repo root.

Steps

  1. Copy argus/20260504T004143Z/3-poc/F-02/poc.ts to tests/poc-F-02.ts.

  2. Run anchor test.

  3. Observe both it(...) blocks PASS — proving the bug fires.

Expected output (buggy code)

F-02 contribute does not update contribution.amount
✔ after contribute(0.5 SOL), contribution.amount is still 0
✔ refund returns 0 lamports because contribution.amount is 0

Expected output (with suggested fix applied)

Add to programs/rustfund/src/lib.rs:50 (immediately after the existing fund.amount_raised += amount;):

contribution.amount = contribution.amount
.checked_add(amount)
.ok_or(ErrorCode::CalculationOverflow)?;

After the fix:

  • The first it block FAILS — its assertion contributionAccount.amount.toNumber() === 0 no longer holds (it equals 0.5 SOL).

  • The second it block FAILS — contributorAfter is now strictly greater than contributorBefore (the refund actually moves SOL).

Impact

Permanent loss of every contributor's principal. Direct fund-impact under CodeHawks "High". Compounds with F-01 (creator absorbs the stranded funds).

Recommendation

// Transfer SOL from contributor to fund account
let cpi_context = CpiContext::new(
ctx.accounts.system_program.to_account_info(),
system_program::Transfer {
from: ctx.accounts.contributor.to_account_info(),
to: fund.to_account_info(),
},
);
system_program::transfer(cpi_context, amount)?;
fund.amount_raised += amount;
+ contribution.amount = contribution.amount
+ .checked_add(amount)
+ .ok_or(ErrorCode::CalculationOverflow)?;
Ok(())
}
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge 8 days ago
Submission Judgement Published
Validated
Assigned finding tags:

[H-03] Permanent Loss of Contributor Funds: Missing Update to contribution.amount in the contribute() rustfund Contract

## Description The `rustfund` contract contains a logical error in the `contribute()` function that prevents `contribution.amount` from updating after a user makes a donation. Even though the code increments `fund.amount_raised`, the individual contributor’s record is never updated. As a result, the refund mechanism relies on a zeroed `contribution.amount`, preventing contributors from recovering the correct amount of funds. This issue disrupts the expected crowdfunding flow, undermines the integrity of individual contributions, and ultimately breaks the refund logic for users who should be entitled to their donated lamports if a project does not reach its goal. ## Vulnerability Details The `rustfund` contract fails to update the `contribution.amount` field in the `contribute()` function. While `fund.amount_raised` reflects the total lamports contributed, individual contributors’ amounts remain at zero, effectively breaking the logic for refunds. This oversight compromises the contract’s guarantee that users can retrieve their funds if the project does not succeed or if they become eligible for a refund. In its current state, once a user initiates a valid contribution, there is no proper record of their deposit aside from the aggregated fund total. Any subsequent `refund()` call will use the uninitialized `contribution.amount` (which remains zero), meaning contributors are unable to recover their deposits. Although this issue does not inherently enable an external attacker to steal funds directly, it causes loss of user funds through an incomplete or misleading refund process. ## Impact This logic flaw undermines the contract’s refund mechanism, potentially causing permanent loss of contributed funds. Contributors are led to believe they can retrieve their deposits if the crowdfunding goal is not met or the deadline passes; however, because `contribution.amount` never reflects the actual amount contributed, no valid refund can occur. This defect results in a direct financial impact for users who cannot recover their funds, and it diminishes trust in the contract’s overall integrity. ## Likelihood Explanation This vulnerability manifests whenever contributors interact with the `contribute()` and `refund()` functions in a real-world scenario. Because the missing code update is consistent across all calls, **every** contribution will fail to correctly record the contributor’s amount. Consequently, any refund operation will lead to the same zero-amount issue. This makes the flaw highly likely to occur and reliably reproducible for every user who attempts to donate and then request a refund. ## Proof of Concept The logical error lies in the `contribute()` function, where the `amount` is transferred to the `fund` and `fund.amount_raised` is incremented, yet `contribution.amount` remains unchanged. As a result, if `refund()` is called later, the contributed funds are not reimbursed because `contribution.amount` remains at zero. ### Code Analysis - [lib.rs -](https://github.com/CodeHawks-Contests/2025-03-rustfund/blob/main/programs/rustfund/src/lib.rs#L34-L52) [`contribute`](https://github.com/CodeHawks-Contests/2025-03-rustfund/blob/main/programs/rustfund/src/lib.rs#L34-L51) Below is an abridged version of the `contribute()` function focusing on the relevant sections: ```Rust pub fn contribute(ctx: Context<FundContribute>, amount: u64) -> Result<()> { // ... Preliminary code ... // Initialize or update contribution record if contribution.contributor == Pubkey::default() { contribution.contributor = ctx.accounts.contributor.key(); contribution.fund = fund.key(); contribution.amount = 0; } // (!) The amount is transferred but 'contribution.amount' is never updated let cpi_context = CpiContext::new( ctx.accounts.system_program.to_account_info(), system_program::Transfer { from: ctx.accounts.contributor.to_account_info(), to: fund.to_account_info(), }, ); system_program::transfer(cpi_context, amount)?; fund.amount_raised += amount; Ok(()) } ``` After `system_program::transfer(...)`, the update to `contribution.amount` is missing. The required line should be: ```rust contribution.amount = contribution.amount.checked_add(amount) .ok_or(ErrorCode::CalculationOverflow)?; ``` ### Explanation Since `contribution.amount` never increments during a contribution, the contract correctly records the transferred amount in `fund.amount_raised` but fails to mirror that amount in the contribution account. Consequently, `refund()` relies on a `contribution.amount` that remains zero, preventing users from retrieving their funds. ### Vulnerable Scenario 1. Alice creates a new fund using `fund_create()`. 2. Alice contributes 0.5 SOL via `contribute()`. Internally, `fund.amount_raised` increments, but `contribution.amount` remains at 0. 3. The fund’s deadline passes, and `refund()` is called. 4. The `refund()` function attempts to return the amount stored in `contribution.amount`, which is 0, so Alice does not get her 0.5 SOL back. ### Test and Result This test aims to verify that when a user contributes a specific amount to the fund, both `contribution.amount` and `fund.amountRaised` are updated accordingly. After invoking the `contribute()` method and fetching the relevant on-chain accounts, the test checks if the recorded amounts match the expected value. In the provided output, `contribution.amount` remains at zero instead of reflecting the correct 500000000 lamports, confirming that the code to increment this field is missing or not executed, resulting in the failing assertion. - Add the following test to `tests/rustfund.ts` after of the function test Contributes to fund ```TypeScript it("Contributes to fund", async () => {}); it("should update the contribution amount when a user contributes", async () => { // Derive the PDA for the contribution account [contributionPDA, contributionBump] = await PublicKey.findProgramAddress( [fundPDA.toBuffer(), provider.wallet.publicKey.toBuffer()], program.programId ); // Invoke the 'contribute' function to transfer the specified amount await program.methods .contribute(contribution) .accounts({ fund: fundPDA, contributor: provider.wallet.publicKey, contribution: contributionPDA, systemProgram: anchor.web3.SystemProgram.programId, }) .rpc(); // Fetch the updated 'fund' and 'contribution' accounts to validate changes const fundAccount = await program.account.fund.fetch(fundPDA); const contributionAccount = await program.account.contribution.fetch( contributionPDA ); // Confirm that 'contribution.amount' correctly reflects the contributed amount expect(contributionAccount.amount.toNumber()).to.equal( contribution.toNumber(), "The contribution.amount was not correctly updated" ); // Verify that 'fund.amountRaised' also matches the newly contributed amount expect(fundAccount.amountRaised.toNumber()).to.equal( contribution.toNumber(), "The fund.amountRaised was not correctly updated" ); }); it("Refunds contribution", async () => {}); ``` ```bash 1) rustfund should update the contribution amount when a user contributes: The contribution.amount was not correctly updated + expected - actual -0 +500000000 ``` ### Confirmation This flaw is confirmed by observing that `contribution.amount` never increases after a contribution. Its persistent zero value leads to `refund()` failing to return the appropriate funds. A safe and effective fix is to update `contribution.amount` within `contribute()`, for example by using `checked_add` to avoid overflow. ## Recommendations Include a line to increment the `contribution.amount` within the `contribute()` function, ensuring it tracks each user's donation amount. Use a safe addition operation to prevent overflow: ```rust contribution.amount = contribution.amount.checked_add(amount) .ok_or(ErrorCode::CalculationOverflow)?; ``` This change ensures the refund mechanism properly returns the correct amount to contributors.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!