Reentrancy

Difficulty: Advanced

Question

What is a reentrancy attack in Ethereum smart contracts, and how do you prevent it?

Answer

A reentrancy attack happens when a contract makes an external call to another contract before it has finished updating its own state, and that external contract calls back into the original function. Because the original function's state is still stale, the callback can re-run logic that should only run once, for example withdrawing funds repeatedly before the balance is ever reduced. This was the flaw behind the 2016 DAO hack, which drained around 3.6 million ETH and led to the Ethereum hard fork.

Why it works

On Ethereum, sending ETH to an address can trigger that recipient's code. When a contract sends ETH using a low-level call, the recipient's receive or fallback function runs immediately, still inside the sender's transaction. If the sending contract updates its records only after the transfer, the attacker's fallback can call back into the withdraw function while the balance still shows the full amount. The function has no idea it is being re-entered, so it pays out again and again until gas or funds run out.

The vulnerable pattern

The classic buggy order is: check the balance, send the ETH, then update the balance. The send happens before the update, so during the send the attacker re-enters and the stale balance passes the check every time. The fix is to change the ordering and add guards.

Defences

  1. Checks-Effects-Interactions pattern: do all checks first, then update your own state (effects), and only then make the external call (interactions). If the balance is zeroed before the ETH is sent, a re-entrant call sees zero and fails the check. This ordering alone prevents the classic attack.
  2. Reentrancy guard: a mutex such as OpenZeppelin's nonReentrant modifier sets a lock on entry and releases it on exit, so any re-entrant call reverts. Useful for functions that cannot fully avoid external calls mid-logic.
  3. Pull over push payments: instead of the contract sending funds, let users withdraw their own balance in a separate transaction, shrinking the dangerous surface.
  4. Mind cross-function and cross-contract reentrancy: a guard on one function does not help if another function shares the same state and is re-entered. Protect all functions that touch the shared state.

Beyond the basics

Reentrancy is not only about ETH transfers. ERC-777 token hooks and any callback-style token can re-enter, and read-only reentrancy can corrupt view functions that other protocols rely on for pricing. Modern audits treat any external call as a reentrancy risk, not just raw ETH sends.

Common mistakes

  • Updating balances after the external call instead of before.
  • Assuming only call is risky; any external interaction that hands control to another contract can re-enter.
  • Guarding one withdraw function but leaving a sibling function that shares state unprotected.
  • Relying on gas limits (the old transfer 2300-gas idea), which is unreliable since gas costs change across network upgrades.
A reentrancy drain. The attacker's fallback re-enters withdraw before the balance is ever reduced.
  1. Attacker → Vulnerable Contract: withdraw(): balance check passes
  2. Vulnerable Contract → Attacker: Sends ETH, triggers fallback
  3. Attacker → Vulnerable Contract: fallback re-calls withdraw()
  4. Vulnerable Contract → Attacker: Stale balance passes, sends ETH again

Code examples

Vulnerable vs safe withdraw (Solidity)

// VULNERABLE: sends ETH before updating state
function withdraw() external {
    uint256 amount = balances[msg.sender];
    require(amount > 0, "nothing to withdraw");
    (bool ok, ) = msg.sender.call{value: amount}("");  // re-entry point
    require(ok, "transfer failed");
    balances[msg.sender] = 0;   // too late: attacker already re-entered
}

// SAFE: Checks-Effects-Interactions + reentrancy guard
function withdrawSafe() external nonReentrant {
    uint256 amount = balances[msg.sender];
    require(amount > 0, "nothing to withdraw");
    balances[msg.sender] = 0;   // effect BEFORE the external call
    (bool ok, ) = msg.sender.call{value: amount}("");
    require(ok, "transfer failed");
}

Zeroing the balance before the external call means a re-entrant withdraw sees a zero balance and reverts. The nonReentrant modifier adds a lock as a second line of defence. The language shown is Solidity; cpp is used only for highlighting.

Key points

  • Reentrancy: an external call lets the callee re-enter a function before its state is updated.
  • The 2016 DAO hack exploited this and drained around 3.6 million ETH.
  • Checks-Effects-Interactions ordering is the primary fix; update state before external calls.
  • A reentrancy guard (nonReentrant mutex) is a strong second layer.
  • Watch cross-function, cross-contract, token-hook and read-only reentrancy, not just ETH sends.

Common follow-up questions

  • What is the Checks-Effects-Interactions pattern and why does it work?
  • What is cross-function reentrancy and how does it bypass a single guard?
  • Why is relying on the 2300-gas stipend of transfer discouraged now?
  • How can ERC-777 hooks introduce reentrancy that ERC-20 does not?

Interview tips

  • Reference the DAO hack; it anchors the concept and shows historical awareness.
  • Lead with Checks-Effects-Interactions, then mention guards; ordering is the core insight.
  • Mention that any external call is a risk, not just ETH transfers, to show depth.

Concepts covered

Smart Contracts, Reentrancy, Checks-Effects-Interactions, Reentrancy Guard, Solidity

More Web Security (OWASP, JWT, XSS, CSRF) questions