```
   ██████╗ ██████╗ ██╗███╗   ██╗    ███████╗ ██████╗ █████╗ ███╗   ██╗
  ██╔═══██╗██╔══██╗██║████╗  ██║    ██╔════╝██╔════╝██╔══██╗████╗  ██║
  ██║   ██║██║  ██║██║██╔██╗ ██║    ███████╗██║     ███████║██╔██╗ ██║
  ██║   ██║██║  ██║██║██║╚██╗██║    ╚════██║██║     ██╔══██║██║╚██╗██║
  ╚██████╔╝██████╔╝██║██║ ╚████║    ███████║╚██████╗██║  ██║██║ ╚████║
   ╚═════╝ ╚═════╝ ╚═╝╚═╝  ╚═══╝    ╚══════╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═══╝
```

---

## 📋 Overview

**📁 Repository:** [bank_two (Solana Developer Bootcamp)](https://github.com/solana-developers/developer-bootcamp-2024/tree/main/project-12-attack-the-bank/bank_two)
**📅 Analysis Date:** 2026-09-02T16:10:44 UTC
**🔧 Analyzer Version:** 0.5.2
**📌 Commit:** `8aa304d1`
**⚡ Analysis Engine:** Odin Scan Core

## 📊 Security Summary

### 🎯 Findings Overview

**Total Security Issues Found:** `6`

| Severity Level | Count | Status |
|---------------|-------|---------|
| 🔴 **Critical** | **2** | ⚠️ Immediate Action Required |
| 🟠 **High** | **2** | ⚠️ Priority Fix Needed |
| 🟡 **Medium** | **1** | ⚠️ Should Be Addressed |
| 🟢 **Low** | **1** | 💡 Consider Fixing |
| 🔵 **Informational** | **0** | ✅ None Found |

---

## 🔍 Detailed Security Findings

### 🔴 1. Missing Signer Verification in update_authority [Critical]

**Description:**
The `UpdateAuthority` accounts struct declares `authority` as `SystemAccount` instead of `Signer`. Combined with `has_one = authority`, this allows any user to invoke the instruction by including the current authority's public key as a non-signer account in the transaction. The `has_one` constraint is satisfied without requiring an actual signature from the authority wallet, enabling anyone to change the bank authority to an address they control and subsequently drain funds.

**Location:** `src/lib.rs:78-88`

**Severity:** `Critical`
**Confidence:** `Medium`
**Category:** `AccessControl`

**Verification Note:** Verifier confirmed the finding: `authority` is passed as a non-signer account and `has_one` only checks key equality, so any wallet can call `updateAuthority`.

**References:**
- [SlowMist Solana smart contract security best practices](https://github.com/slowmist/solana-smart-contract-security-best-practices)

**Remediation:**
Change `authority: SystemAccount` to `authority: Signer` in `UpdateAuthority` and keep the `has_one` constraint. The Signer constraint makes Anchor require the current bank authority's signature, so only the true owner can rotate it.

**Proof of Concept:**
```
await program.methods.updateAuthority().accounts({ newAuthority: attacker }).instruction();
await program.methods.withdraw(new anchor.BN(amount)).accounts({ authority: attacker }).instruction();
```

### 🔴 2. First Depositor Can Become Bank Authority [Critical]

**Description:**
The `deposit` instruction uses `init_if_needed` and, when `is_initialized` is false, sets `bank.authority` to the caller's public key. Any user can become the bank authority simply by being the first to deposit (e.g., with 1 lamport). Once in control, combined with the missing signer check in `update_authority` and the unrestricted `withdraw` instruction, an attacker can drain all funds from the bank.

**Location:** `src/lib.rs:10-32`

**Severity:** `Critical`
**Confidence:** `Medium`
**Category:** `AccessControl`

**References:**
- [SlowMist Solana smart contract security best practices](https://github.com/slowmist/solana-smart-contract-security-best-practices)

**Remediation:**
Replace `init_if_needed` with `init` plus an explicit initialization check, or use `init_if_needed` only when the account is guaranteed fresh. Alternatively, only honor the `is_initialized` flag when it was set by a genuine initializer (e.g., require the first depositor's signature once, via a dedicated `initialize` instruction).

### 🟠 3. Unchecked Arithmetic Operations on bank_balance [High]

**Description:**
The `bank_balance` field is modified using unchecked `+=` and `-=` operators in `deposit` and `withdraw`. While the Solana runtime reverts on overflow/underflow, using checked arithmetic (`checked_add`, `checked_sub`) is recommended for financial code to provide explicit error handling and clearer error reporting instead of relying on runtime panics.

**Location:** `src/lib.rs:12-35`

**Severity:** `High`
**Confidence:** `Medium`
**Category:** `NumericalIssue`

**References:**
- [SlowMist Solana smart contract security best practices](https://github.com/slowmist/solana-smart-contract-security-best-practices)

**Remediation:**
Use checked arithmetic: `bank.bank_balance = bank.bank_balance.checked_add(amount) .ok_or(BankError::Overflow)?` in `deposit`, and checked_sub in `withdraw`.

### 🟠 4. Missing Balance Validation in withdraw [High]

**Description:**
The `withdraw` instruction does not verify that `bank_balance >= amount` before performing the subtraction and the lamport transfer. This allows users to attempt withdrawals larger than the available balance, causing transaction failures at the arithmetic underflow step, wasting compute and producing a poor user experience. The lamport transfer via `sub_lamports` would also fail if insufficient balance exists.

**Location:** `src/lib.rs:34-40`

**Severity:** `High`
**Confidence:** `Medium`
**Category:** `InputValidation`

**References:**
- [SlowMist Solana smart contract security best practices](https://github.com/slowmist/solana-smart-contract-security-best-practices)

**Remediation:**
Add `require!(bank.balance >= amount, BankError::InsufficientFunds)` before the subtraction and transfer, and map the error to a user-friendly failure.

### 🟡 5. Missing Zero-Amount Validation in deposit and withdraw [Medium]

**Description:**
Neither `deposit` nor `withdraw` validates that the `amount` parameter is greater than zero. Zero-amount operations are accepted, which wastes compute, pollutes on-chain state and event logs (via `msg!`), and can confuse off-chain indexers and UIs that track deposits and withdrawals.

**Location:** `src/lib.rs:10-40`

**Severity:** `Medium`
**Confidence:** `Medium`
**Category:** `InputValidation`

**References:**
- [SlowMist Solana smart contract security best practices](https://github.com/slowmist/solana-smart-contract-security-best-practices)

**Remediation:**
Add `require!(amount > 0, BankError::ZeroAmount)` to both `deposit` and `withdraw`.

### 🟢 6. State Update Before External Transfer in deposit [Low]

**Description:**
In the `deposit` instruction, `bank_balance += amount` is executed before the CPI `transfer` of lamports to the bank PDA. Although Solana transactions are atomic (a CPI failure reverts all state changes), modifying internal state before performing the external interaction violates the checks-effects-interactions pattern and is considered risky practice. If any non-CPI failure path were introduced later, the state could become desynchronized from actual lamport holdings.

**Location:** `src/lib.rs:11-30`

**Severity:** `Low`
**Confidence:** `Medium`
**Category:** `StateManagement`

**References:**
- [SlowMist Solana smart contract security best practices](https://github.com/slowmist/solana-smart-contract-security-best-practices)

**Remediation:**
Perform the CPI transfer first, then update `bank_balance` (checks-effects-interactions).

---

## 🎯 Conclusion & Recommendations

### Overall Risk Assessment: 🔴 **HIGH RISK**

### 🛡️ About This Analysis

This comprehensive security report was generated by **Odin Scan**, an AI-enhanced smart contract security analyzer.
Our analysis combines:
- 🔍 **Static Code Analysis** - Pattern matching and vulnerability detection
- 🤖 **AI-Powered Detection** - Machine learning models trained on security vulnerabilities
- 📊 **Risk Assessment** - Contextual severity and confidence scoring
- 🔧 **Actionable Remediation** - Specific guidance and code examples

### 📋 Next Steps

🚨 **IMMEDIATE ACTION REQUIRED**
1. 🔴 Address all **Critical** findings before deployment
2. 🟠 Fix **High** severity issues as priority
3. 🟡 Review and address **Medium** severity findings
4. 🔄 Re-run Odin Scan after implementing fixes

---

**🛡️ Secured by Odin Scan**

*AI-Enhanced Smart Contract Security Analysis*

📧 Contact: [security@odinscan.ai](mailto:security@odinscan.ai) | 🌐 Web: [odinscan.ai](https://odinscan.ai)
