Attack Vectors Presentation 01000111 01101111 01100100
REENTRANCY_DETECTED
int balance = user.bal;
Security Lab: Module 01
Reentrancy & Overflows
Dissecting the architecture of high-profile blockchain exploits and the "Checks-Effects-Interactions" defense.
Attack Vectors
Solidity V0.8+
EVM Exploitation
The Day the Ledger Bleed
In 2016, a hacker drained 3.6 million ETH (worth ~$60M at the time) from The DAO.
The "Recursive Call" Attack
The contract sent funds to the user before updating their balance. The user's malicious contract then called back into the withdrawal function, repeating the process before the first balance update could finish.
Result: A recursive loop of theft.
Vulnerable Snippet
function withdraw(uint _amt) public {
require(balances[msg.sender] >= _amt);
// VULNERABILITY HERE:
// External call before state change
(bool success, ) = msg.sender.call{value: \_amt}("");
require(success);
// State updated TOO LATE
balances\[msg.sender\] -= \_amt;
}
The call triggers the attacker's fallback function, restarting the loop.
How Reentrancy Works
1
Call to Target
Attacker calls withdraw(). The target contract checks the balance and starts the transfer.
2
Fallback Trigger
The transfer triggers the receive() or fallback() in the attacker's contract.
3
Recursive Re-entry
The fallback calls withdraw() again. The target balance hasn't changed yet, so the check passes again.
Arithmetic Overflows
What happens when an 8-bit unsigned integer (uint8) at its max value of 255 is incremented by 1?
255 + 1
= 0
Overflow
0 - 1
= 255
Underflow
Modern Context:
Solidity 0.8.0+ has built-in panic checks for overflows. In older versions (0.4.x - 0.7.x), SafeMath was mandatory.
Odometer Logic
Defense: The Golden Rule
Phase 01
CHECKS
Verify all requirements (require, modifiers).
Phase 02
EFFECTS
Update internal state (balances, mapping changes).
Phase 03
INTERACTIONS
External calls (ETH transfers, other contracts).
Never put an interaction before an effect.
The DAO Heist Lab Lab: The DAO Resurrection
Blockchain Security | Module 01.A
ID: SEC-2026-01
Name: ____________________________
Objective
Identify, exploit, and patch a vulnerable smart contract. You will simulate a reentrancy attack on a simplified "Vault" contract and then refactor the code to withstand the attack.
Part 1: Code Audit
Analyze the following Solidity snippet from a mock decentralized vault:
// Vulnerable Vault Contract (Solidity 0.6.12)
contract SimpleVault {
mapping(address => uint) public balances;
function deposit() public payable {
balances\[msg.sender\] += msg.value;
}
function withdrawAll() public {
uint bal = balances\[msg.sender\];
require(bal > 0);
(bool sent, ) = msg.sender.call{value: bal}("");
require(sent, "Failed to send Ether");
balances\[msg.sender\] = 0;
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
1. Identify the line(s) causing the reentrancy vulnerability. Explain why it is vulnerable in the context of the EVM execution model.
2. If an attacker deploys a contract that calls withdrawAll(), what function in the attacker's contract is triggered by the .call? Describe what code should be in that function to drain the vault.
Part 2: Designing the Exploit
Below is a template for the Attacker contract. Fill in the logic for the reentrancy loop.
contract VaultAttacker {
SimpleVault public vault;
constructor(address \_vaultAddress) public {
vault = SimpleVault(\_vaultAddress);
}
// This function starts the heist
function attack() external payable {
require(msg.value >= 1 ether);
vault.deposit{value: 1 ether}();
vault.withdrawAll();
}
// TRIGGER FUNCTION: Fill in the logic below
fallback() external payable {
// \[YOUR LOGIC HERE\]
}
}
Part 3: Remediation & Best Practices
Rewrite the withdrawAll() function using the Checks-Effects-Interactions pattern to make it secure.
Secure withdrawAll Implementation
function withdrawAll() public {
// 1. Checks
// 2. Effects
// 3. Interactions
}
Bonus: Reentrancy Guard
Besides the "Checks-Effects-Interactions" pattern, what is another common programmatic way (using a state variable) to prevent a function from being re-entered before it finishes execution?
MEV Predator Presentation Mempool Dynamics: Module 02
Into the Dark Forest
Understanding MEV, Front-running, and the predatory ecosystem of the transaction mempool.
Visibility
Execution Speed
Extracted Value
Defining MEV
Maximal Extractable Value (MEV) is the maximum value that can be extracted from block production in excess of standard block rewards.
Inclusion & Ordering
Searchers and builders can choose which transactions to include and in what order .
Censorship
The power to intentionally exclude transactions to protect or enhance profit.
Searchers
Identify opportunities (arbitrage, liquidations).
Builders
Construct blocks to maximize profit.
Front-running Mechanics
Retail User
Transaction in Mempool
MEV Bot
"The bot sees your large swap on Uniswap. It submits its own swap for the same asset with a higher gas fee , ensuring its trade executes right before yours, driving the price up."
Slippage Exploitation
Bots exploit the 'slippage tolerance' users set in their trades.
Priority Gas Auction
Bots engage in bidding wars to get the front-row seat.
The Sandwich Attack
Phase 1: Buy
Bot buys asset before the user's trade.
User Swap
User's trade executes at a worse price .
Phase 2: Sell
Bot sells after user, pocketing the difference.
Bot Profit = (Sell Price - Buy Price) - Gas Fees
Lighting Up the Forest
How do we protect users and decentralize the MEV market?
Discussion Prompt
"Is MEV a fundamental flaw in blockchain design, or is it an inevitable market efficiency that should be embraced and democratized?"
Mempool Analysis Worksheet Lab: Mempool Forensics
Blockchain Security | Module 02.B
ID: MEV-2026-02
Name: ____________________________
Intelligence Report
"A whale has just submitted a transaction to swap 2,500 ETH for DAI on a decentralized exchange. The transaction is currently sitting in the public mempool with a Gas Price of 45 Gwei. You are an MEV Searcher. Your task is to analyze the trade and determine if a sandwich attack is profitable."
Part 1: The Victim's Transaction
Transaction Data
Amount: 2,500 ETH
Min Out (Slippage): 0.5%
Gas Price: 45 Gwei
Current ETH Price: $3,200 DAI
Pool Liquidity (Constant Product)
Reserve ETH: 50,000
Reserve DAI: 160,000,000
Fee: 0.3%
1. Calculate the maximum amount of DAI the whale is willing to accept based on their 0.5% slippage tolerance. Show your work.
2. If you want to front-run this transaction, what is the minimum Gas Price you should set to ensure your transaction is ordered immediately before the whale's? Explain the concept of a "Priority Gas Auction" (PGA).
Part 2: Executing the Sandwich
A sandwich attack requires two transactions (the "bread") around the user's trade (the "filling").
TX 1 (Front-run)
Buy ETH with DAI
Whale Trade
Sell ETH for DAI
TX 2 (Back-run)
Sell ETH for DAI
3. Describe the impact of TX 1 on the ETH price for the Whale. How does this allow TX 2 to become profitable?
Part 3: The Dark Forest Ethics
"Searchers claim that MEV is a service because it keeps markets efficient. Critics argue it is a 'tax' on retail users that degrades trust in decentralized systems."
Draft a 150-word policy recommendation for a new DEX. Should they implement a private mempool or a shared MEV revenue model? Justify your choice.
Verification Beyond Testing Presentation Verification: Module 03
Beyond Testing
Transitioning from heuristic bug-hunting to mathematical proof using Formal Verification.
Slither / Mythril
Invariants
Formal Logic
Why Unit Tests Fail
"Program testing can be used to show the presence of bugs, but never to show their absence!" — Edsger W. Dijkstra
The Edge-Case Trap
Unit tests only check the scenarios you think of. Hackers look for the scenarios you missed.
The Formal Solution
Formal Verification checks all possible states of the contract against a mathematical specification.
Testing
Sample-Based
Verification
Exhaustive
The Auditor's Toolkit
Slither
A static analysis framework that converts Solidity into SlithIR (Intermediate Representation) to find vulnerabilities.
- Reentrancy detection
- Shadowing variables
- Unprotected functions
Mythril
Uses Symbolic Execution to explore control flow paths and identify high-severity exploits.
- Delegatecall bugs
- Integer Overflows
- Transaction Ordering
The Power of Invariants
An Invariant is a property that must always be true, no matter what happens to the contract state.
Example: ERC-20
"The sum of all individual balances must equal the Total Supply."
Example: Uniswap V2
"The product of reserves (x * y) must never decrease after a swap."
Formal verification tools attempt to find a single sequence of inputs that breaks these rules. If they can't, the property is proven.
Professional Audit Workflow
01. Scoping
Define codebase & threat model.
02. Static Run
Run Slither & automated tools.
03. Manual Review
Trace logic & edge cases.
04. Remediation
Devs fix bugs; auditor re-checks.
Next: We will perform a manual audit on a "broken" DeFi protocol.
Audit Interpretation Worksheet Lab: The Auditor's Lens
Blockchain Security | Module 03.C
ID: AUD-2026-03
Name: ____________________________
Defining Formal Properties
Before running automated tools, an auditor must define the "Invariants" of the system. For each of the following decentralized components, write one high-level invariant in plain English and its mathematical representation .
1. A Staking Pool (Stakers earn rewards over time)
English Invariant
Math Representation
\[ \dots \]
2. A Governance Bridge (Locks tokens on Chain A, Mints on Chain B)
English Invariant
Math Representation
\[ \dots \]
Part 2: Tool Output Analysis
You ran Slither on a client's contract. Below is a snippet of the JSON output. Interpret the findings.
{
"impact": "High",
"check": "reentrancy-eth",
"description": "LendingProtocol.liquidate(address) sends eth to msg.sender.
External calls:
- (success, ) = msg.sender.call{value: reward}(\"\")
State variables written after the call(s):
- positions[user].isLiquidated = true",
"confidence": "High"
}
3. Explain the "High Impact" finding above. What specific attack scenario does this finding enable?
4. How would you recommend the client fix this issue? (Provide the corrected pseudo-code sequence).
// Step 1: ...
// Step 2: ...
// Step 3: ...
The Auditor's Oath
"I will not rely solely on automated results. I will assume the developer's intent is flawed until proven otherwise by mathematical logic."
ZK-SNARKs Magic Presentation Cryptography: Module 04
The Magic of ZK-SNARKs
Verifying truth without revealing data. The architectural shift toward privacy-preserving computation.
Privacy
Verifiability
Circuits
What is a ZK-SNARK?
ZK Zero Knowledge
S Succinct
N Non-Interactive
ARK Argument of Knowledge
"I can prove I have a solution to a Sudoku puzzle without showing you a single number in the grid."
The Components
Prover
Has a secret (Witness) and generates a proof.
Verifier
Receives the proof and checks its validity (cheaply).
Thinking in Circuits
In ZK proofs, computations are represented as Arithmetic Circuits . Every program is broken down into a series of mathematical constraints.
Logic Gate Simulation
x
Input (Witness)
y
Input
=
z
Output
Constraint: x + y - z === 0
Rule #1
Only addition and multiplication gates are native.
Rule #2
Control flow (if/else) must be turned into math expressions.
The ZK-Passport
How to prove you are over 21 without revealing your birthdate, name, or address.
Commitment(Birthdate)
ZKProof(Age >= 21)
VERIFIED
The "Toxic Waste" Problem
Many ZK-SNARKs require a Trusted Setup . If the random numbers used during setup aren't destroyed, the "Toxic Waste" can be used to forge fake proofs.
Multi-Party Computation (MPC)
Dozens of people contribute randomness. Only one honest participant is needed to make the waste useless.
ZK-STARKs
The "S" stands for Scalable and the "T" for Transparent —meaning no trusted setup is required at all.
Circuit Design Worksheet Lab: Circuit Architect
Blockchain Privacy | Module 04.D
ID: ZK-2026-04
Name: ____________________________
Objective
Zero-Knowledge proofs require programs to be expressed as a set of mathematical constraints. In this lab, you will practice converting logical statements into arithmetic circuit constraints compatible with libraries like Circom.
Part 1: Simple Logic gates
Example: To prove \( z = x \cdot y \), the constraint is \( x \cdot y - z = 0 \).
1. Boolean Constraining: How do you mathematically constrain a variable b to be either 0 or 1? (Hint: Think of a quadratic equation).
b * (...) = 0
2. Range Check: Write a constraint that proves a value x is either 1, 2, or 3, without revealing which one it is.
(x - 1) * ...
Part 2: Eliminating If-Else
Arithmetic circuits don't support if (condition) { ... }. We use a "Multiplexer" pattern. Given a selector s (where 0 or 1), a value a, and a value b, the output out should be a if s=0 and b if s=1.
3. Construct the single mathematical expression for out in terms of s, a, and b.
out = ...
Part 3: Secret Membership Proof
You want to prove that you know a secret password that hashes to a public targetHash.
Public Inputs
Private Witness
4. Draw or describe the "Circuit" flow. What are the gates? What is the final constraint that the Verifier checks?
Graduate Challenge: Scalability
Why is hashing particularly expensive in a ZK circuit? Consider the number of constraints required for a SHA-256 hash versus an algebraic-friendly hash like Poseidon .
Obfuscating the Ledger Presentation RING_SIG_ACTIVE OBFUSCATION_LVL_9 MIXER_ENTROPY_MAX
Privacy Architectures: Module 05
Obfuscating the Ledger
Breaking the deterministic link between sender and receiver in public blockchain systems.
Anonymity Sets
Mixers
Compliance
Public ≠ Anonymous
Blockchains like Bitcoin and Ethereum are Pseudonymous .
Address Clustering
Chain analysis firms can link addresses to real identities through:
- KYC exchange withdrawals
- Common-input ownership heuristics
- Change-address patterns
The Transaction Graph
1.5 ETH
1.49 ETH
Deterministic linking is the default.
Breaking the Link: Mixers
1. Deposit
Users deposit fixed amounts (e.g., 1 ETH) into a smart contract.
Commitment = hash(nullifier, secret)
2. The Pool
Funds from 1000s of users sit in the pool. It is impossible to tell which deposit belongs to which user.
3. Withdrawal
User provides a ZK-SNARK proving they know a secret from the deposit pool without revealing which one.
Withdrawal Successful (Link Broken)
Protocol-Level Privacy
Unlike Ethereum (Privacy-as-an-App), Monero (XMR) is private-by-default using:
Ring Signatures
Combines your signature with multiple "decoy" signatures from the ledger.
Stealth Addresses
Generates a unique, one-time address for every transaction to the same recipient.
"Hiding in the Crowd"
The Anonymity Set Size
The Right to Privacy vs. AML
Pro-Privacy Argument
Financial privacy is a human right. On a public ledger, revealing your balance to a merchant is like showing them your entire bank statement every time you buy coffee.
"Privacy protects the innocent."
Regulator Argument
Untraceable transactions facilitate money laundering, terror financing, and ransomware. Mixers enable criminals to "clean" stolen funds from hacks.
"Sanctions must be enforceable."
Discussion: Is code speech?
Privacy Case Study Worksheet Case Study: Privacy vs. Policy
Blockchain Ethics | Module 05.E
ID: ETH-2026-05
Name: ____________________________
The Tornado Cash Sanctions
In August 2022, the U.S. Office of Foreign Assets Control (OFAC) sanctioned the Tornado Cash smart contract addresses, making it illegal for U.S. persons to interact with the protocol. This was the first time an autonomous piece of code, rather than an entity or person, was placed on a sanctions list.
Part 1: The Immutability Paradox
1. Explain why it is technically impossible for the "developers" of Tornado Cash to comply with the sanction and "turn off" the protocol. What does this reveal about the nature of decentralized infrastructure?
2. Define "Anonymity Set." How does a user's privacy in a mixer depend on the behavior of other participants in the pool?
Part 2: Privacy-Preserving Compliance
Some researchers suggest "Privacy Pools" where users can prove via ZK-SNARKs that their funds do not originate from a list of known illicit addresses, without revealing their specific transaction history.
Scenario Analysis
You are an architect for a new privacy-focused Layer 2. You have two design choices:
Option A: Total Privacy
Pure Monero-style ring signatures. No way to exclude bad actors, but 100% censorship resistant.
Option B: Compliant Privacy
Uses ZK-Proofs to allow users to prove they aren't on a blacklist. Allows institutional adoption but risks centralization of the "Blacklist".
3. Which option do you choose and why? Consider the impact on both user safety and protocol longevity.
Part 3: Final Reflection
"In a world of total transparency, there is no room for dissent. In a world of total anonymity, there is no room for accountability."
4. Based on what you've learned in this sequence, where should the blockchain industry draw the line between these two worlds? Is a middle ground technically achievable?