Reentrancy Attacks
Reentrancy occurs when a contract calls an external contract (e.g., to send ETH), and that external contract calls *back* into the calling contract before the first execution is finished. This creates a recursive loop that can drain funds.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
A vulnerable vault and how to fix it.
Core Concepts
Control Flow Hijack
When you call another contract, you pause your execution and give them the CPU.
Recursion
The attacker calls you, you call them, they call you...
Atomicity
Transactions are atomic, but intermediate states during the transaction can be invalid.
Mental Model
The ATM Glitch
Imagine an ATM. You ask to withdraw $100. The machine hands you the cash *before* it updates your account balance on the screen. Before it can update the screen, you quickly press 'Withdraw' again. The machine sees the balance is still there and hands you another $100.
Under the Hood
External calls (`CALL` opcode) pass execution context to the target. If the target is a contract, it runs code. It can `.call()` back to the origin because the origin is just another address.
Gas Analysis
Reentrancy guards cost gas.
- • Use the Checks-Effects-Interactions pattern (free) instead of a Mutex (gas cost) where possible.
Security Risks
Always assume external calls are malicious.
- ! Single Function Reentrancy.
- ! Cross-Function Reentrancy (Attacker calls a different function sharing state).
- ! Cross-Contract Reentrancy (Attacker calls a system sharing state).
Common Use Cases
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.
Attacker calls withdraw()
The attacker initiates the withdrawal process.
Contract checks balance
Balance is > 0. Check passes.
Contract sends ETH
Contract sends 1 ETH to attacker. Control flow handover!
Attacker Fallback()
Attacker receives ETH and immediately calls withdraw() again!
Re-enter withdraw()
Execution loops back to start. Balance was NOT updated yet!
Drain Loop
This loop continues until gas runs out or contract is empty.