Majority Attack Slides Security Protocol 01
Majority Attack & Game Theory
Analyzing the vulnerabilities of Proof-of-Work consensus and the cost of rewriting history.
SESSION_01
The Cost of Deception
"If you could rent enough computing power for one hour to rewrite history, would the profit outweigh the cost?"
The Goal
Double-spend millions of dollars by orphaning the legitimate chain.
The Requirement
Control >50% of the network's total hashing power (Hashrate).
The Result
Network consensus breaks. Immutable becomes mutable.
Anatomy of a 51% Attack
1
Secret Mining
The attacker begins mining a private fork of the blockchain without broadcasting blocks.
2
The Double Spend
The attacker sends coins to an exchange on the public chain and withdraws fiat/other coins.
3
The Reveal
Once the secret fork is longer than the public chain, it is broadcast. Nodes switch to the longer chain.
NETWORK_TOPOLOGY.EXE
B1
B2
B3
Public Chain (Honest)
A2
A3
A4
Private Fork (Attacker)
Nodes follow the Longest Chain Rule (technically Heavy Chain). A4 > B3. History is overwritten.
Case Study: Ethereum Classic (ETC)
Real World Re-org
In August 2020, Ethereum Classic suffered multiple 51% attacks.
Over 7,000 blocks were reorganized (over 2 days of history).
Attackers double-spent millions of ETC on exchanges.
The attack was executed by renting hashrate from NiceHash.
Vulnerability Profile
Hashrate Security CRITICAL
ETC share of Ethash total hashrate was < 5%.
Cost of Attack (1 Hour) $12,000 - $18,000
Extremely low compared to market cap.
Game Theory: Mining Incentives
Honest Strategy
"I mine to secure the network and earn block rewards + fees."
+ Long-term value of coins
Attacker Strategy
"I mine to double-spend. I don't care about the long-term coin value."
+ Immediate profit from exploit
When does Game Theory fail?
Rentable Hashrate: Attackers don't need to buy hardware.
PoW Monoculture: GPUs/ASICs can easily switch from a big chain to a small one.
The "Lindy Effect": Younger, smaller chains lack the cumulative security of Bitcoin.
The Red Team Equation
Profitability Condition for a 51% Attack:
\[ P > C_{rent} \times T + O \]
P Potential Double Spend Profit
C_rent Cost to rent 51% Hashrate / Hour
T Attack Duration (Confirmation Time)
O Opportunity Cost / Risk of Failure
Activity: You are the attacker. Calculate the target.
Attack Cost Worksheet Security Dossier: Operation 51
Blockchain Security Audit | Lesson 01: Majority Attacks
Classification: Restricted
Auditor Name
Date
Mission Objective
You are a "Red Team" security auditor tasked with evaluating the reorganization risk of "LegacyCoin" , a Proof-of-Work blockchain. Use the provided network data to calculate the cost and potential profit of a 51% attack. Determine if the current security threshold is sufficient to deter rational attackers.
Phase 1: Network Intelligence
Target Network Data
Current Network Hashrate: 250 TH/s
Block Reward + Fees: 50 LC
Market Price per LC: $120.00
Block Time: 10 Minutes
Exchange Confirmations: 12 Blocks
Adversary Resources
Rental Cost (100 TH/s): $4,500 / Hour
Attacker Initial Hash: 10 TH/s (Owned)
Target Double Spend: 20,000 LC
Phase 2: Vulnerability Analysis
1. Calculate the required hashrate to control 51% of the new network total. Show your work.
Result (TH/s): ___________
2. To reach the 51% threshold, how much hashrate must the attacker rent? (Subtract their owned 10 TH/s from the requirement in Q1).
Rental Amount Needed: ___________
3. Determine the duration (in hours) required for the attack. The attacker must out-mine the honest chain for the duration of the exchange confirmation window (12 blocks).
Duration (T): ___________
4. Calculate the Total Cost of the attack (C_rent * T). Ignore electricity for the owned 10 TH/s for this model.
Total Attack Cost: ___________
Phase 3: Final Security Report
5. Potential Profit: Calculate the USD value of the 20,000 LC double-spend. Add the block rewards the attacker would earn during the re-org window (assuming they win all blocks in their private fork).
Potential Gross Profit: ___________
Conclusion & Recommendation
Compare the Profit vs. Cost. Is this attack rational? What should the network developers do to increase security? (Think: Confirmation times, difficulty adjustment, or consensus change).
Secured by Proof-of-Work Logic
HASH_VERIFICATION: 0x8f2a...3e91
Mining Monopoly Teacher Guide Teacher Guide: Majority Attacks
Blockchain Security Audit | Lesson 01 Facilitation
Instructional Strategy
This lesson moves students from the theoretical concept of "immutability" to the practical reality of "consensus security." The goal is for students to realize that blockchain security is not magic—it is a financial trade-off.
The "Aha!" Moment: "A blockchain is only as secure as the cost to rewrite it." If the profit from an attack exceeds the cost, the network is fundamentally broken, regardless of the cryptography used.
Lesson Specs
Duration: 60-90 Min
Difficulty: Advanced
Math Prep: Algebra
Worksheet Answer Key: Operation 51
Q1: Target Hashrate for 51%
The attacker must add enough hash so they control > 50% of the *new* total.
Let X = Attacker Hashrate. X / (250 TH/s + X) > 0.51 X > 0.51(250 + X) -> X > 127.5 + 0.51X -> 0.49X > 127.5 X ≈ 260.2 TH/s
Q2: Hashrate to Rent
Total needed (260.2) - Owned (10).
Result: 250.2 TH/s must be rented.
Q3: Duration (T)
12 blocks at 10 minutes each = 120 minutes.
Result: 2 Hours.
Q4: Total Cost
Cost to rent 100 TH/s is $4,500/hr. So 250.2 TH/s is $11,259/hr.
Hourly Cost = (250.2 / 100) * $4,500 = $11,259 Total Cost = $11,259 * 2 Hours = $22,518
Q5: Potential Profit
Double spend (20,000 LC * $120) + Block Rewards (12 blocks * 50 LC * $120).
Double Spend Value = $2,400,000 Rewards = 600 LC * $120 = $72,000 Total Gross Profit = $2,472,000
Facilitation Guide & Discussion
Key Debrief Questions
Is this chain secure? No. The profit ($2.4M) vastly outweighs the cost (~$22k). An attacker would take this deal every time.
What about hardware? Remind students that rental services like NiceHash make this attack "low capex." You don't need to buy the rigs.
Countermeasures: Why don't exchanges just require 100 confirmations? Discuss the trade-off between user experience (fast trades) and security (deep re-org protection).
Deep Dive: Re-org Depth
In the Ethereum Classic attack, the attacker didn't just re-org 12 blocks; they re-orged thousands.
Challenge the students: If a chain is attacked once, does its value drop to zero? Why did ETC survive? (Discuss community resilience, checkpointing, and hard-forking as social consensus).
Common Misconceptions
Reentrancy Slides function withdraw() public {
uint bal = balances[msg.sender];
require(bal > 0);
(bool sent, ) = msg.sender.call{value: bal}("");
require(sent);
balances[msg.sender] = 0;
}
/* RECURSIVE CALL DETECTED... RECURSIVE CALL DETECTED... */
Vulnerability Lab 02
Reentrancy Attacks
Deconstructing the DAO hack and mastering the Checks-Effects-Interactions pattern.
The Infinite ATM
"How can a hacker drain a bank account by asking to withdraw $1 over and over again before the bank updates its balance?"
In June 2016, "The DAO" (Decentralized Autonomous Organization) was exploited for 3.6 million ETH (approx $60M at the time, billions today).
The attacker didn't steal a private key. They just exploited a race condition in the code.
$60M+
Loss in 24 Hours
The "Withdraw" Vulnerability
Vulnerable Code
1 function withdraw() public {
2 uint bal = userBalance[msg.sender];
3 require(bal > 0);
4 (bool sent, ) = msg.sender.call{value: bal}("");
5 require(sent, "Transfer failed");
6 userBalance[msg.sender] = 0; <-- TOO LATE!
7 }
Critical Flaw: The contract sends the money before updating the internal accounting.
!
External calls transfer control to the recipient. If the recipient is another contract, it can execute its own code.
!!
The recipient contract's "fallback" function calls withdraw() again before line 6 ever executes.
The Reentrancy Loop
Vault Contract
Check Balance
Send Funds
Update Balance
1. .call{value: X}
2. re-enter withdraw()
Attacker Contract
receive() fallback
Call Withdraw
The balance update is trapped in the call stack, never reached until the Vault is empty.
Defense: Checks-Effects-Interactions
1. Checks
Verify all conditions (require, access control).
2. Effects
Update the internal state (balances, mapping) BEFORE interacting.
3. Interactions
Perform external calls (transfer, call, external contract methods).
/* SECURE VERSION */
Code Audit Lab Worksheet Security Audit Lab: Reentrancy
Auditor Task: Identifying State Race Conditions
REF: LAB-REENT-02
Junior Auditor
Audit Date
Audit Target A: The Simple Vault
This contract allows users to deposit ETH and withdraw it at any time. Review the function below for vulnerabilities.
1 contract SimpleVault {
2 mapping(address => uint) public balances;
3
4 function deposit() public payable {
5 balances[msg.sender] += msg.value;
6 }
7
8 function withdrawAll() public {
9 uint amount = balances[msg.sender];
10 require(amount > 0, "Insufficient balance");
11
12 (bool success, ) = msg.sender.call{value: amount}("");
13 require(success, "Transfer failed");
14
15 balances[msg.sender] = 0;
16 }
17 }
1. Vulnerability Analysis: Identify the specific line(s) where the state is updated incorrectly relative to the external interaction.
2. Exploit Mechanics: Briefly explain how an attacker contract could "loop" this withdrawal to drain funds.
Audit Target B: The Multi-Sig Reward Distributer
This contract distributes rewards based on a voting mechanism. Is it susceptible to reentrancy even if the balance update happens "before" the call but in the wrong order?
1 function claimReward(address target) public {
2 require(rewards[target] > 0, "No reward");
3
4 // Intent: Prevent double claiming
5 uint rewardToPay = rewards[target];
6 rewards[target] = 0;
7
8 // Interaction
9 (bool success, ) = target.call{value: rewardToPay}("");
10 require(success, "Transfer failed");
11
12 totalPaidOut += rewardToPay;
13 }
3. Auditor Recommendation: Does Target B follow the CEI pattern correctly? Why or why not?
Refactor Task: Hardened Implementation
Rewrite the withdrawAll function from Target A using the Checks-Effects-Interactions (CEI) pattern to ensure security.
function withdrawAll() public {
// Your secure code here...
}
End of Audit Lab | Classified Secure Development Protocol
Reentrancy Teacher Guide Teacher Guide: Reentrancy Attacks
Exploiting and Securing Smart Contract State
Historical Context: The DAO
The DAO hack wasn't just a technical failure; it was a philosophical crisis for Ethereum. It led to the hard fork between Ethereum (ETH) and Ethereum Classic (ETC) .
Teaching Narrative Explain to students that the code was "audited" by experts, but reentrancy was a relatively unknown pattern at the time. This illustrates the "Red Queen's Race" in security: as soon as a new defense is built, a new attack is discovered.
Lab Answer Key
Target A: Simple Vault
Vulnerability: Line 15 (balances[msg.sender] = 0;) happens *after* the external call on Line 12.
Exploit: The attacker contract's receive() function calls withdrawAll(). Since the balance hasn't been set to 0 yet, the require on Line 10 passes again. This repeats until the Vault's ETH is depleted.
Target B: Reward Distributer
Analysis: This contract is secure against reentrancy for the individual reward. Line 6 updates the state (setting reward to 0) *before* the call on Line 9. If the contract re-enters, Line 2 will fail because the reward is now 0.
Nuance: However, note that totalPaidOut (Line 12) is updated *after* the call. While not a direct money-drain bug, it means the contract's internal tracking of total funds paid might be incorrect if reentrancy occurs (a "read-only" reentrancy risk or state inconsistency).
The CEI Facilitation
C
Checks
Validate conditions first.
E
Effects
Update state second.
I
Interactions
External calls last.
Student Q&A: Why not just use .transfer()?
Students may know that .transfer() and .send() only provide 2300 gas, which is not enough for the recipient to make another call (preventing reentrancy by gas exhaustion).
The Answer: Gas costs in Ethereum change (EIPs like EIP-1884). Relying on 2300 gas is now considered bad practice . Use .call() and the CEI pattern or a ReentrancyGuard. Security should not depend on gas prices.
MEV Slides Protocol Analysis 03
The Dark Forest: MEV
Exploring front-running, sandwich attacks, and the predatory landscape of the mempool.
The Visible Secret
"In the split second before your trade is confirmed, predatory bots can see it, buy before you, and sell to you at a higher price."
The Mempool
A public waiting room for pending transactions. Before a transaction is in a block, it is visible to everyone—including bots.
Priority Fees
Bots use higher gas fees to "cut in line" and ensure their transaction is processed before yours.
What is MEV?
M.E.V.
Maximal Extractable Value
The total value that can be extracted from block production in excess of the standard block reward and gas fees by including, excluding, and re-ordering transactions.
Power Shift
Formerly "Miner Extractable Value," now applies to validators in PoS systems.
Arbitrage (Healthy Extraction)
Liquidations (System Health)
Front-running / Sandwiching
The Sandwich Attack
FRONT Bot Buy
$1,000.00 | High Gas
USER User Buy (Market Order)
$1,005.00 (Price Slippage)
Slippage Tolerance Exhausted
BACK Bot Sell
$1,010.00 | Instant Profit
The bot "sandwiches" the user's trade, extracting the slippage tolerance as pure profit.
Architectural Defense
Private RPCs
Services like Flashbots Protect send transactions directly to validators, bypassing the public mempool.
Commit-Reveal Schemes
Users commit a hash of their trade first, then reveal it later. Bots can't see what they're front-running.
Discussion Point:
"Is MEV a tax on users, or an essential incentive for keepers and liquidators to keep DeFi running?"
Fairness vs. Efficiency
Sandwich Attack Handout Anatomy of a Sandwich Attack
Blockchain Security Audit | Lesson 03: MEV Mechanics
The Vulnerability: Slippage Tolerance
When swapping tokens on a Decentralized Exchange (DEX), users set a Slippage Tolerance (e.g., 0.5%). This means the transaction will execute as long as the final price is within 0.5% of the quoted price. MEV bots exploit this "wiggle room" to extract value.
The Execution Sequence
1. Bot Detects Transaction
The bot monitors the public mempool for a large pending swap (e.g., swapping 100 ETH for DAI).
1
{ pending: "swapETHforDAI", amount: 100, maxSlippage: 0.01 }
TX_FRONT: buyDAI(50 ETH) | Gas: 500 Gwei
2
2. The Front-Run
The bot broadcasts a "Buy" transaction with a higher gas fee. It executes first, slightly raising the price of DAI on the DEX.
3. The Victim's Trade
The user's trade executes second. Because the bot already raised the price, the user buys DAI at the absolute limit of their slippage tolerance.
3
TX_USER: buyDAI(100 ETH) | Gas: 50 Gwei
TX_BACK: sellDAI() | Gas: 500 Gwei
4
4. The Back-Run
The bot sells the DAI it bought in Step 2. Since the user's large trade in Step 3 further inflated the price, the bot sells for a profit.
Glossary
Gwei: A denomination of ETH used to pay gas. 1 Gwei = 0.000000001 ETH.
Gas War: When bots bid increasingly high gas fees to ensure their position in a block.
Bundle: A group of transactions sent to a validator that must be executed in a specific order.
Prevention
Set Low Slippage: Lowering tolerance (e.g. 0.1%) makes the "sandwich" too thin to be profitable after gas costs.
Private RPC: Send trades to validators via private relays so they never hit the public mempool.
Limit Orders: Use protocols that match trades off-chain before settling on-chain.
Confidential Auditor Resource | Do Not Distribute to Mempool Bots
MEV Discussion Guide Teacher Guide: MEV & The Dark Forest
Navigating the Ethics and Architecture of Frontend Extraction
Essential Question
"Is Maximal Extractable Value an inherent flaw in blockchain design, or is it a necessary market force for network efficiency?"
Instructional Guidance
Students often view MEV as "cheating" or "hacking." Your goal is to move them toward a more nuanced Systems Thinking perspective. MEV is a byproduct of permissionless systems and public mempools.
"Good" MEV (Benign)
Arbitrage that keeps prices equal across different exchanges (DEXs). Liquidations that protect lending protocols from bad debt.
Impact: Healthy Markets
"Bad" MEV (Adversarial)
Sandwich attacks that steal slippage from retail users. Re-ordering transactions to steal NFT mints or front-run liquidations.
Impact: User "Tax"
Guided Classroom Debate
1
Visibility vs. Privacy
The mempool is public by design for transparency. But transparency enables predation. Should mempools be private? What are the trade-offs (e.g., censorship risk)?
2
The "Tax" Argument
If MEV adds a 1% cost to every retail trade, will users eventually leave for centralized exchanges? How does MEV threaten the long-term adoption of DeFi?
3
Incentive Alignment
Flashbots and MEV-Boost allow validators to share in the MEV profit. If we didn't have these, would validators start running their own secret bots, leading to network centralization?
Active Learning: The Mempool Bot
Split the class into Users (trying to swap) and Searchers (the bots).
Give the Users a target swap price. Give the Searchers the ability to see the "mempool" (a board where users write their trades) and bid "gas" (tokens) to re-order the board. Observe how quickly prices inflate and who ends up with the profit.
Blockchain Audit Sequence | Lesson 3 Guide
Ethics Material 03A
Flash Loan Slides Advanced DeFi Security 04
Flash Loans & Oracles
Analyzing uncollateralized atomic debt and the fragility of external data feeds.
Infinite Leverage
"How can someone with $0 borrow $100 million for 15 seconds to manipulate a market price and walk away with a profit?"
$0
Collateral Required
Atomic
Single Block Execution
∞
Potential Impact
The Flash Loan Lifecycle
1
BORROW
Take massive loan from a lending pool (Aave, Uniswap).
2
OPERATE
Use funds for arbitrage, liquidations, or exploits.
3
REPAY
Return the principal plus a small fee (e.g., 0.09%).
4
ATOMICITY
If Step 3 fails, the entire transaction reverts. No risk to lender.
if (balanceBefore == balanceAfter + fee) COMMIT else REVERT
The Oracle Problem
Smart contracts can't see the real world. They rely on Oracles (data feeds) for asset prices.
Vulnerability: Low Liquidity Feeds
If a contract uses a single DEX pool (like Uniswap v2 ETH/DAI) as its price source, an attacker can use a flash loan to artificially inflate or crash that price.
Exploit Mechanics
1. Flash loan 50,000 ETH
2. Dump ETH into Oracle pool (Price crashes)
3. Target lending protocol sees "cheap" ETH
4. Attacker buys cheap collateral / drains vault
Hardening Oracles
1. Decentralized Oracles
Use Chainlink Price Feeds . These aggregate data from multiple exchanges and off-chain sources, making them immune to single-pool manipulation.
2. TWAP Oracles
Time-Weighted Average Price . Instead of the current price, use the average over the last 30 minutes. Flash loans only last one block!
CASE STUDY
The Mango Markets Exploit
$114 million drained using oracle manipulation.
Activity: Trace the logic of the attack.
Oracle Exploit Worksheet Attack Map: Oracle Manipulation
Blockchain Security Audit | Lesson 04: The Flash Loan Heist
Security Researcher
System Log Date
Scenario: The "Lend-It" Exploit
Lend-It is a protocol where users can deposit ETH and borrow USDC . Lend-It determines the value of deposited ETH by checking a single Uniswap V2 pool (ETH/USDC).
Current Price: $2,000 / ETH . Lending Ratio: Users can borrow up to 80% of their ETH value in USDC.
Task 1: Map the Attack Vector
Fill in the boxes to describe the attacker's atomic transaction sequence.
Step 1: Initiation
Example: Borrow 10M USDC via Flash Loan.
Step 2: Pool Manipulation
How do you use the USDC to change the ETH price?
Step 3: Protocol Interaction
What do you deposit or borrow on "Lend-It" now?
Step 4: The Escape
Repay flash loan and secure the profit.
Task 2: Critical Vulnerability Analysis
1. Why is a Time-Weighted Average Price (TWAP) effective against this specific flash-loan attack?
2. If Lend-It switched to a Chainlink Price Feed, explain how the attack costs for the adversary would change.
Final Security Recommendation
You are the lead security engineer for Lend-It. Propose two immediate architectural changes to prevent this exploit without disabling flash loans (since you can't block flash loans on other protocols).
Audit Sequence 04 | Node Verification ID: 449-ALPHA
Oracle Teacher Guide Teacher Guide: Flash Loans & Oracles
Facilitating the Analysis of Atomic Liquidity Exploits
Lesson Strategy
This lesson introduces students to the most "magic-like" feature of Ethereum: Atomicity . Students must understand that flash loans do not create new money; they democratize the ability to be a "whale" for 15 seconds.
Key Concept: Flash loans are not the vulnerability. The vulnerability is the Oracle . Flash loans simply provide the capital necessary to exploit the oracle's lack of liquidity.
Case Study: Mango Markets (Oct 2022)
The attacker used two accounts to take large long/short positions in MNGO-PERP.
Attacker used ~$5M to pump the price of MNGO on external exchanges.
The Mango Markets oracle updated to the new, inflated price.
The attacker's position value skyrocketed.
They borrowed $114M in other assets (USDC, SOL, etc.) against their "valuable" MNGO.
They never intended to repay the loan; they walked away with the borrowed assets.
LOSS: $114 Million | METHOD: Oracle Price Manipulation
Worksheet Key: Lend-It Attack Map
Step 1: Flash loan a large amount of USDC (the quote asset).
Step 2: Swap all USDC for ETH in the Uniswap pool. This makes ETH very "expensive" in that pool.
Step 3: Deposit a small amount of ETH into Lend-It. Because Lend-It's oracle is manipulated, it thinks the ETH is worth much more. Borrow way more USDC than the ETH is actually worth.
Step 4: Repay the USDC flash loan. Keep the excess USDC.
Critique of TWAP
TWAPs are good, but they introduce Price Lag . If the real market price crashes, a TWAP will keep the protocol's price high for minutes, allowing users to borrow more than their collateral is worth. How do we balance safety and accuracy?
The Ethics of the "Bounty"
In the Mango Markets case, the attacker voted on a DAO proposal to return most of the funds in exchange for a "bug bounty" and a promise of no criminal charges. Is this negotiation ethical?
Blockchain Audit | Lesson 04 Teacher Resource VERIFIED_SECURITY_PROTOCOL_v4.2
Auditing Slides Mastery Level 05
Auditing & Verification
Moving from reactive patching to proactive proof: Professional standards for secure blockchain architecture.
CERTIFIED_SECURE
Proof, Not Testing
"Testing finds bugs, but it doesn't prove their absence. How can we use math to prove a smart contract is unhackable?"
Unit Testing
Verifying that code behaves as expected for specific inputs. (The "Happy Path")
Formal Verification
Mathematical proof that code adheres to a formal specification across ALL possible inputs.
The Professional Audit Pipeline
Static Analysis
Automated scanning for known vulnerabilities (Slither, Mythril).
Manual Review
Human auditors trace logic, check game theory, and find custom edge cases.
Fuzzing
Feeding the contract random/semi-random data to find crashes (Echidna).
Certification
Final report issued with risk ratings: Critical, High, Medium, Low.
Automated Scanners
$ slither contract.sol
INFO:Detectors:
Reentrancy in Vault.withdrawAll (contract.sol#12-20):
External calls:
- (sent, ) = msg.sender.call{value: amount}("")
State variables written after call(s):
- balances[msg.sender] = 0
Reference: https://swcregistry.io/docs/SWC-107
Why use tools?
Consistency: Tools never get tired or miss simple patterns.
Speed: Scan thousands of lines of code in seconds.
But... Tools can't understand business logic or complex game theory.
Formal Verification (FV)
The Spec
You write a Specification in a mathematical language (like CVL - Certora Verification Language).
invariant balance_sum() {
sum(balances) == total_supply;
}
The Proof
The tool attempts to find ANY state where this invariant is violated.
If no violation is found, the property is proven . If one is found, you get a "counter-example" (a trace of how to break it).
Red Team Mindset
Assume Compromise
If there is a way to drain funds, it WILL happen.
Verify Everything
Don't trust comments or "expert" reviews. Audit the raw bytecode.
Audit Checklist Handout Professional Smart Contract Audit Checklist
Standard Operating Procedure | Audit Level 01
01 Automated Static Analysis
Run Slither to detect reentrancy, uninitialized variables, and shadow state.
Run Mythril for symbolic execution (detecting integer overflows/underflows).
Verify Solidity compiler version (prefer ^0.8.0 for built-in overflow protection).
02 Logic & Access Control Review
Check msg.sender vs. tx.origin (Avoid tx.origin for auth).
Identify all onlyOwner or onlyRole modifiers. Are they missing anywhere?
Validate Checks-Effects-Interactions pattern in all payable/withdrawal functions.
Check for Gas Siphon attacks: Do loops grow with user count? (DOS risk).
03 Oracle & Integration Security
Is price data sourced from a single pool? (Manipulation Risk).
Are latestRoundData() results from Chainlink checked for staleness?
Does the contract handle fee-on-transfer or rebasing tokens correctly?
Risk Severity Matrix
Severity Description Action Required CRITICAL Direct theft of funds possible in a single block. Fix immediately before deployment. HIGH Significant risk of fund loss or protocol bricking. High priority fix. MEDIUM Governance risk or edge-case fund lock. Should be fixed. LOW Code optimization or non-critical state drift. Acknowledge/Note.
SWC-REGISTRY_LINK: https://swcregistry.io VERSION_0.1.AUDIT
Final Audit Report Template Audit Project Final
Smart Contract Security Audit Report
Target Protocol
"SafeVault-V1" Implementation
Audit Firm (Student Name)
__________________________
HASH_ID: 7a92-f01b-99ce
"Code is Law, but Law has bugs."
1. Executive Summary
Provide a high-level overview of the audit process and the general security posture of the target contract. Summarize the number of findings by severity.
2. Vulnerability Findings
Finding [CRITICAL-01] Severity: CRITICAL
Title:
e.g., Unprotected Withdrawal in processPayment()
Description:
Explain the bug and the attack vector...
Recommendation:
Explain how to fix the code (e.g., apply CEI pattern)...
Finding [HIGH-01] Severity: HIGH
[Finding Slot 2]
3. Final Certification
Based on the findings above, is this contract ready for mainnet deployment? What are the remaining risks the team should monitor?
Auditor Signature
PENDING_FIX
Blockchain Audit Mastery Sequence