Bible Network Crypto DeFi Onchain RWA AI Agent Stablecoin Chain SAFU CryptoTax DeFAI AGI Claude Me Claude Skill Claude Design Claude Cowork
Independent Media
Not affiliated with any project
The Deepest Crypto Knowledge Base
crypto-bible.com
LATEST
That Trading Pair Showing Hundreds of Millions in Volume? Up to 90% of It Could Be Fake — Three Signals You Can Check Yourself  ·  Why the Same Whale-Sized Order Sometimes Barely Moves the Market — and Sometimes Sets Off an Explosion  ·  $3.2 Trillion in Fake Volume, Orchestrated by Just 489 People — What the Real Profit Structure of a Pump-and-Dump Looks Like  ·  That Order Book Depth You See on an Exchange? A Lot of the Time, Someone Was Paid to Put It There  ·  Why You Should Finish Your KYC Verification Before You Actually Need It  ·  The First Trading Cost You Pay Isn't the Fee — It's a Small Gap You Never Noticed
Glossary · Wallet & Security

Reentrancy Attack

Wallet & Security Advanced

30-Second Version · For the impatient
A <a href="/en/glossary/wallet-and-security/reentrancy-attack/" target="_blank">Reentrancy Attack</a> is a vulnerability exploit against smart contracts: the attacker exploits the window between when the contract sends funds and when it updates its internal state (account balance), calling the original withdrawal function again the instant funds are received — allowing the contract to pass the balance check again before the state updates, repeatedly draining funds until the contract is emptied. The DAO attack of 2016 (approximately $60 million lost) exploited this vulnerability and directly led to the Ethereum hard fork (the ETH/ETC split). This vulnerability remains one of the most critical checks in <a href="/en/glossary/blockchain-fundamentals/smart-contract/">Smart Contract</a> security audits today.
Full Explanation +
01 · What is this?

What is the technical principle of reentrancy attacks, and why is the order of contract operations so important? Reentrancy's root vulnerability lies in a Smart Contract updating its own ledger after transferring funds — this operation order creates exploitable opportunity. The correct approach: update the ledger first (set user balance to 0), then transfer funds to the user. The vulnerable pattern: transfer funds to the user, then update the ledger after transfer completes. The problem: Ethereum's .call() method, when paying a contract, can trigger the receiving contract's fallback function the instant ETH is received. The attacker's fallback function calls the original contract's withdraw again — at this point the original contract's ledger hasn't updated, so the balance check still passes. This re-entry can repeat until the contract's ETH is drained. The entire vulnerability's logic is the wrong order of transfer-then-record.

02 · Why does it exist?

What was The DAO attack and why was it so important? The DAO (Decentralized Autonomous Organization) was a 2016 Ethereum crowdfunding Smart Contract project that raised approximately $150 million worth of ETH at the time. In June 2016, an attacker exploited a reentrancy vulnerability in The DAO's withdrawal contract, repeatedly withdrawing and ultimately transferring away approximately 3.6 million ETH (then worth ~$60 million). The event's impact far exceeded an ordinary hack: the Ethereum community faced a fundamental choice — should they hard fork (modify blockchain state) to forcibly return the stolen ETH to DAO investors? Ultimately, the Ethereum community voted by majority to hard fork, rolling Ethereum back to the state before the attack and returning the stolen funds. This is the origin of today's Ethereum (ETH); the minority who refused to recognize the hard fork maintained the original chain — this became Ethereum Classic (ETC). The DAO attack made the entire crypto industry deeply understand the importance of Smart Contract security, and established the foundational debate between blockchain immutability and governance emergency response.

03 · How does it affect your decisions?

How do you defend against reentrancy attacks? What verified patterns exist? Several standard defensive approaches. First, Checks-Effects-Interactions (CEI) pattern: the most fundamental and important defensive principle. Any contract function should execute in this order: Checks (do all condition checks first) → Effects (update all internal contract state) → Interactions (only then interact with external contracts or addresses, like transferring funds). With state updates before the transfer, even if an attacker re-enters, the balance is already 0, the check fails, and the attack is neutralized. Second, ReentrancyGuard (mutex lock): OpenZeppelin provides a standard ReentrancyGuard module — essentially a boolean mutex lock that sets to locked during function execution and unlocks on completion; if re-entered while locked, it reverts immediately. Simple and effective for complex function call chains. Third, avoid raw call() for payments: transfer() and send() methods forward only 2,300 Gas by default — insufficient for a complex-logic fallback to execute, structurally limiting reentrancy viability (but shouldn't be the primary defense, as Gas mechanics may change with upgrades).

04 · What should you do?

Beyond reentrancy attacks, what other common Smart Contract vulnerability types exist? A few equally important Smart Contract vulnerability types to know. Integer overflow/underflow: before Solidity 0.8's automatic overflow protection, numeric calculations could wrap around (e.g., uint8's 255 + 1 = 0) — exploited to fabricate balances. Modern Solidity has protection, but old contracts remain at risk. Unsafe external calls: when calling external contracts, incorrect handling of return values can let attackers control execution flow. Logic errors: not technical vulnerabilities but business logic design errors — reversed conditionals, missing permission controls — letting attackers use the contract in unintended ways. Flash Loan attacks: using flash loans' instant massive liquidity to manipulate market or Oracle prices within a single transaction, affecting lending or Liquidation logic that relies on these prices. Understanding these vulnerabilities is foundational knowledge for evaluating DeFi protocol security.

Real-World Example +

Use pseudocode to explain the complete reentrancy attack flow. Imagine a simple Ethereum deposit/withdrawal contract with a balances mapping tracking each address's balance. The vulnerable withdraw function:

function withdraw() external {
  require(balances[msg.sender] > 0);  // check balance
  (bool success,) = msg.sender.call{value: balances[msg.sender]}("");  // send funds FIRST
  require(success);
  balances[msg.sender] = 0;  // update balance AFTER
}

The attacker deploys a malicious contract with a fallback function:

fallback() external payable {
  if (address(victim).balance > 1 ether) {
    victim.withdraw();  // immediately call again the instant ETH is received
  }
}

Attack flow: attacker calls victim.withdraw(); contract checks balance > 0 (passes); contract transfers ETH to attacker; attacker's fallback triggers and immediately calls victim.withdraw() again; at this point the contract's balances[attacker] is still the original value (update happens after transfer); check passes again, transfer again; loop until contract is empty.

The CEI-fixed version: update balances[msg.sender] = 0 first, then .call{value: ...}. One line of order change — the entire attack is blocked.

Diagram
Reentrancy Attack: Withdraw Before Balance Updates重入攻擊 vs 安全提款雙欄對比流程圖:左側綠色欄「正常提款(安全)」——步驟順序:① 呼叫提款 → ② 檢查餘額足夠 → ③ 先更新餘額為零 → ④ 再打款。右側紅色欄「重入攻擊漏洞」——關鍵差異:步驟三和四順序反轉:② 檢查餘額通過 → ③ 先打款(回調立即觸發,攻擊者在回調中再呼叫提款)→ 餘額尚未更新,步驟②再Reentrancy Attack: Withdraw Before Balance UpdatesNormal Withdraw (Safe)1. User calls withdraw(1 ETH)2. Check: balance ≥ 1 ETH ✓3. Update balance = 04. Send 1 ETH to user ✓Reentrancy Exploit1. Attacker calls withdraw(1 ETH)2. Check: balance ≥ 1 ETH ✓3. Send 1 ETH → callback triggers↺ calls withdraw(1 ETH) AGAIN before balance updates!4. Check STILL passes (balance not yet 0)Loop repeats until contract is drained. The DAO hack (2016, $60M) used this exact pattern.Crypto Bible · crypto-bible.com
Feel free to share. Please credit the source.
Common Misconceptions +
✕ Misconception 1
× Misconception 1: Reentrancy is an outdated vulnerability; modern smart contracts have all defended against it and you don't need to worry. Wrong. While reentrancy has been widely known since 2016, many subsequent contracts have re-exposed reentrancy risk by ignoring CEI or introducing complex cross-contract interactions. Many DeFi attacks with eight-digit dollar losses have included reentrancy elements (sometimes combined with flash loans). Modern Solidity has better tools, but not every developer uses them — security audits still list reentrancy as a mandatory check.
✕ Misconception 2
× Misconception 2: Only withdrawal (withdraw) functions can have reentrancy vulnerabilities. Wrong. Any function that makes external calls before state updates can have reentrancy risk — for example, a function that calls an external contract before distributing rewards, or a function that triggers a token transfer callback before updating its ledger. The CEI principle applies to all functions that interact with external contracts, not just withdrawals.
The Missing Link +
Direct Impact

Reentrancy reveals a fundamental engineering trade-off in smart contract design: the sequence between external calls (transferring funds to another address or contract) and state updates. The intuitive write-then-record approach makes business logic clearer (give you the money first, then note you have none), but introduces reentrancy risk. The CEI record-then-write approach, while slightly counterintuitive for business logic, completely eliminates the reentrancy problem. This trade-off now has a clear consensus answer — always use CEI — but it reminds us that smart contract code security and intuitive business logic sometimes have subtle conflicts. Every smart contract is public and immutable — once deployed with a bug, fixing it requires migrating to a new contract, not a silent patch push like traditional software. This makes pre-launch auditing of smart contracts more critical than any traditional software.

Ask a Question
Please enter at least 10 characters
More Related Topics
How to Choose a Crypto AI Agent Service: Five Evaluation Frameworks to Avoid Marketing Traps
AI Agent Bible
Before authorizing an Agent service, ask four questions: are its authorization boundaries code-enforced or just promises? Can you see complete reasoning logs for every operation? Is there a third-party audit report? Who holds the private key? Only when all four have clear answers should you consider authorization. A beautiful interface is not evidence of safety.
#hack#security
Crypto Agent Pre-Launch Security Checklist: 12 Mandatory Items from Testnet to Mainnet
AI Agent Bible
12 mandatory security items before launching a crypto Agent: no plaintext private keys, complete wallet isolation, ERC-20 approval limits, no credentials in System Prompt, backend write tool validation, Schema validation layer, independent confirmation channel for high-value ops, daily spend circuit-breaker, market anomaly circuit-breaker, complete four-layer logs. Missing even one is not acceptable.
#hack#security
Tool Use Mechanism Complete Breakdown: How AI Agents 'Act,' and Why This Design Determines Whether They Can Be Trusted
AI Agent Bible
An AI Agent's LLM doesn't actually execute any tool — it only outputs 'I want to do this' requests; your backend code does the real execution. This design is the foundation of all security: the execution layer is under your control, and security validation is added there. How well tools are designed determines whether an Agent can be trusted.
#hack#security
Front-Running Your Agent: When MEV Bots Target AI Agent Trades, the Losses Can Be Worse Than When They Target You
AI Agent Bible
AI Agents are better MEV bot prey than human traders — because Agent trading patterns are predictable, high-frequency, and time-regular. Losing 0.3% per front-run, an Agent operating 20 times daily accumulates nearly 22% annual drag. This doesn't show as a fee — it's invisible strategy erosion.
#hack#security