🔁 How Reentrancy Works: Call Before Update

Learn how attackers exploit external calls to drain contract funds

Previous Section
The DAO Hack

⚙️ How Reentrancy Attacks Work

Let's simulate a live reentrancy attack to understand exactly how attackers exploit the vulnerability. Watch as the contract is drained step by step.

🎯 Interactive: Attack Simulator

Run the attack simulation to see how reentrancy exploits vulnerable contracts:

🏦Contract Balance

100 ETH

👤Attacker Balance

0 ETH

📚Call Stack

No active calls

Attack Progress

Step 1 of 10IN PROGRESS
Initial State

Contract has 100 ETH, Attacker deposited 10 ETH

Key Concepts

1️⃣External Calls Are Dangerous

When your contract calls another address (especially with call), that address can execute arbitrary code, including calling back into your contract.

// Dangerous!
msg.sender.call{value: amount}("");

2️⃣Checks-Effects-Interactions Pattern

Always follow this order: check conditions, update state, then interact externally.

1. Checks
Validate inputs
2. Effects
Update state
3. Interactions
External calls

3️⃣State Consistency

The attack works because the contract's state (balances) is inconsistent during the external call. The balance hasn't been zeroed yet, so the check passes on reentry.

❌ Balance: 10 ETH (not updated)
✅ Balance: 0 ETH (updated first)

4️⃣Fallback/Receive Functions

When a contract receives ETH, its receive() or fallback() function executes. Attackers put malicious code here.

receive() external payable {
// Malicious reentrancy code here
VictimContract.withdraw();
}

Attack Variations

🔄
Single-Function Reentrancy

Attacker reenters the same function repeatedly (like our simulation above).

Cross-Function Reentrancy

Attacker calls different function that shares state. Harder to detect.

🎭
Delegatecall Reentrancy

Exploit delegatecall to execute code in target's context.

🔗
Cross-Contract Reentrancy

Attack via multiple related contracts that share state.

💡 Understanding The Flow

The attack succeeds because:

  1. Control flow is transferred to attacker during external call
  2. State hasn't been updated when attacker regains control
  3. Same checks pass again on reentry because balances unchanged
  4. Loop continues until contract is fully drained