Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 47 ยท Security

Reentrancy Step by Step

Follow a DAO-style reentrancy attack step by step, then fix it with checks-effects-interactions and reentrancy guards, including cross-function and read-only cases.

Reentrancy is the best-known smart contract bug. In 2016 it let an attacker pull about 3.6 million ether out of a project called The DAO, and the fallout was serious enough that the Ethereum community split the chain over it. The bug is simple, but it has several disguises, and the simple fix does not cover all of them. This lesson walks through the classic version, the two standard defences, and two sneakier variants.

The previous lesson introduced the bug in one paragraph. Here you will trace the exact order of events and then prove each fix with a runnable model. As in other lessons, the JavaScript stand-ins are not the EVM: they model the order of operations, which is all that matters for this bug.

Why a call can come back

A contract can only send ether to another contract by running that contract's code. A plain send to a contract address triggers its receive or fallback function, and a call can give that code nearly all of the remaining gas. The receiving code is written by someone else, and it is free to call your contract again before your function has returned. Your function is then paused in the middle, with the callback running on top of it.

sequenceDiagram
    participant A as Attacker contract
    participant B as Bank
    A->>B: withdraw
    Note over B: reads deposit = 1
    B->>A: send 1 ether
    A->>B: withdraw again
    Note over B: deposit still reads 1
    B->>A: send 1 ether
    A->>B: withdraw again
    Note over B: repeats until the bank is empty

Each nested call sees the old record, because the record is cleared only after the send returns.

The vulnerable shape

SOLIDITY
mapping(address => uint256) public deposits;

function withdraw() external {
    uint256 amount = deposits[msg.sender];       // check
    require(amount > 0, "nothing to withdraw");
    (bool ok, ) = msg.sender.call{value: amount}("");  // interaction
    require(ok, "send failed");
    deposits[msg.sender] = 0;                    // effect, too late
}

The order is check, interaction, effect. Every nested call passes the check, because the effect has not happened yet.

Two standard defences

Checks, effects, interactions Update your records first, call out last.
Reentrancy guard A lock that rejects any nested entry.
1 / 2

Defence 1: checks, effects, interactions

Reorder the function so that all of your own bookkeeping is finished before anything leaves the contract. A callback that arrives now sees the updated state, so its check fails.

SOLIDITY
function withdraw() external {
    uint256 amount = deposits[msg.sender];       // check
    require(amount > 0, "nothing to withdraw");
    deposits[msg.sender] = 0;                    // effect first
    (bool ok, ) = msg.sender.call{value: amount}("");  // interaction last
    require(ok, "send failed");
}

If the send fails, require(ok) reverts the whole transaction, including the zeroing, so the user does not lose their deposit. This one reordering is the most reliable defence and costs no extra gas.

Defence 2: a reentrancy guard

A guard is a modifier that sets a flag on entry and clears it on exit. If the flag is already set, the call is rejected. OpenZeppelin's ReentrancyGuard provides nonReentrant this way, using a storage variable that toggles between two non-zero values (cheaper than going to and from zero). Newer versions also offer a variant built on transient storage.

SOLIDITY
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract Bank is ReentrancyGuard {
    function withdraw() external nonReentrant {
        // ...
    }
}

A guard is a safety net, not a substitute for good ordering. It costs gas on every call, it must cover every function that shares the vulnerable state, and it does nothing for a different contract that reads yours mid-call (more on that below).

Watching the fix work

The model below has one bank class with three modes. The same attacker, with the same one-ether deposit, attacks each version.

JS Drain, then fix it two ways

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the vulnerable run Mallory empties the bank, so Alice's ten ether are gone. In both fixed runs Mallory gets back exactly her one ether. The try/finally in the guard mode mirrors a modifier: the lock is released when the function ends, even if it reverts. In real Solidity a revert undoes the lock automatically, because the write to storage is undone with everything else.

Cross-function reentrancy

Guarding one function is not enough if two functions share the same state. Imagine the bank also has a transfer function that moves a deposit to another address. During the callback inside withdraw, the attacker calls transfer and moves the not-yet-cleared balance to an accomplice. When withdraw finishes it clears the attacker's record, but the accomplice now owns a full copy and withdraws it too.

SOLIDITY
function transfer(address to, uint256 amount) external {
    require(deposits[msg.sender] >= amount, "insufficient");
    deposits[msg.sender] -= amount;
    deposits[to] += amount;
}

The transfer function looks innocent. It is the shared deposits mapping that makes it part of the attack. Use one lock for every function that touches the shared state, or finish your bookkeeping before the external call so there is no stale state to abuse.

JS Cross-function reentrancy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With no lock or a lock on withdraw only, Mallory and her accomplice walk away with two ether for a one-ether deposit. With a shared lock the nested transfer is refused. (In this stand-in transfer has no lock of its own in the withdrawOnly mode, which is exactly the mistake.)

Read-only reentrancy

The third variant never changes your contract's state during the callback. It reads it. Suppose a vault sells shares worth assets / shares each. Its withdraw sends ether first and burns shares afterwards. In the middle, the vault's assets have dropped but the shares have not been burned yet, so the share price it reports is wrong. A different contract that trusts pricePerShare() as a price oracle can be fooled by an attacker who calls it from inside the callback. The vault itself was never "reentered", so a nonReentrant modifier on its state-changing functions does not help.

JS A stale price read from a callback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Defences: finish all related state updates before any external call, so that every read is consistent, and have integrators avoid trusting a spot value that another protocol can distort. Some libraries also let a view function check whether a guard is currently held and revert if so.

Real: the order of operations, the three attack shapes and the roles of ordering and locks. Stand-in: no gas, no real call, and hooks is a simple function table instead of a contract's receive code.

What does not work

  • transfer and send are not a defence. They forward only 2300 gas, which is too little for most reentrant code today, but gas prices change and many contract wallets need more than 2300 gas to receive ether. The accepted advice is to use call and protect the function properly.
  • A guard on only some functions leaves the rest exposed.
  • Trusting your own tokens. Token standards with hooks, such as ERC-777 and ERC-721 safeTransfer callbacks, give the receiving address a chance to run code during a token transfer, so those calls are interactions too.

A review habit: find every external call in a function (ether sends, token transfers, calls to unknown addresses) and ask what state the contract is in at that exact line. If anything is not yet consistent, move the call down.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a checks-effects-interactions function, where does the external call go?

    All of your own state is updated before anything leaves the contract, so a callback sees the final state and fails its checks.
  2. 2. A bank has a nonReentrant withdraw, but an unguarded transfer that moves balances. What can the attacker do?

    That is cross-function reentrancy. The lock must cover every function that touches the shared state, or the state must be updated before the call.
  3. 3. What makes read-only reentrancy different from the classic bug?

    No state is modified during the callback. A consumer of the contract's view functions is fooled by inconsistent values.
  4. 4. Why is switching from call to transfer a poor fix?

    Relying on a fixed gas limit is fragile. Use call and apply checks-effects-interactions or a guard.

Summary

  • Reentrancy happens when an external call runs attacker code before your function has finished updating state.
  • The cure is checks, effects, interactions: finish bookkeeping first, call out last.
  • A nonReentrant guard adds a lock; it must cover every function that shares the vulnerable state.
  • Cross-function reentrancy abuses a second function on the same state; read-only reentrancy abuses inconsistent values read through view functions.
  • Do not rely on transfer, and remember that token hooks are external calls too.

Next: Gas Costs and Optimization.