TExcelTAD
Home › Solidity › Security: Reentrancy

Security: Reentrancy

Reentrancy is the most famous smart-contract vulnerability. It happens when a contract makes an external call before it has finished updating its own state, and the callee calls back ("re-enters") into the contract while that state is still stale. The 2016 attack on "The DAO" exploited exactly this bug and led to a fork of Ethereum itself.

Everything in this lesson runs on local, disposable toy contracts. The point is to recognize the pattern in your own code and to know the fixes.

The vulnerable bank

solidity
function withdraw() external {
    uint256 amount = balances[msg.sender];
    require(amount > 0);
    (bool ok, ) = msg.sender.call{value: amount}("");   // 1. interaction first...
    require(ok);
    balances[msg.sender] = 0;                           // 2. ...state update last (too late!)
}

When msg.sender is a contract, the call runs its receive function. If that function calls withdraw() again, balances[msg.sender] still holds the old amount, so the bank pays again, and again.

Watching it happen

Main plays three roles: two honest depositors and one attacker contract that deposits 1 ETH and then withdraws repeatedly.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract VulnerableBank {
    mapping(address => uint256) public balances;

    function deposit() external payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw() external {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "nothing to withdraw");
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "send failed");
        balances[msg.sender] = 0;            // BUG: updated after the external call
    }
}

contract Depositor {
    function deposit(VulnerableBank bank) external payable {
        bank.deposit{value: msg.value}();
    }
}

contract Attacker {
    VulnerableBank public immutable bank;
    uint256 public reentries;

    constructor(VulnerableBank bank_) { bank = bank_; }

    function attack() external payable {
        bank.deposit{value: msg.value}();
        bank.withdraw();
    }

    receive() external payable {
        if (address(bank).balance >= 1 ether) {
            reentries++;
            bank.withdraw();                 // re-enter before the balance is zeroed
        }
    }
}

contract Main {
    constructor() payable {}

    function main() external {
        VulnerableBank bank = new VulnerableBank();
        new Depositor().deposit{value: 5 ether}(bank);
        new Depositor().deposit{value: 4 ether}(bank);
        console.log("bank holds:", address(bank).balance / 1 ether, "ETH");

        Attacker attacker = new Attacker(bank);
        attacker.attack{value: 1 ether}();

        console.log("attacker re-entered", attacker.reentries(), "times");
        console.log("attacker now has:", address(attacker).balance / 1 ether, "ETH");
        console.log("bank holds      :", address(bank).balance / 1 ether, "ETH");
    }
}
bank holds: 9 ETH
attacker re-entered 9 times
attacker now has: 10 ETH
bank holds      : 0 ETH

With a 1 ETH deposit, the attacker walked away with the honest users' 9 ETH too. Note how nothing reverted: from the EVM's point of view every step was legitimate.

Fix 1: Checks-Effects-Interactions

Order every function in three phases:

  1. Checks: validate inputs and permissions (require).
  2. Effects: update your own state.
  3. Interactions: call other contracts or send ether, last.
solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract SafeBank {
    mapping(address => uint256) public balances;

    function deposit() external payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw() external {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "nothing to withdraw");   // checks
        balances[msg.sender] = 0;                      // effects
        (bool ok, ) = msg.sender.call{value: amount}("");   // interactions
        require(ok, "send failed");
    }
}

contract Attacker {
    SafeBank public immutable bank;
    constructor(SafeBank bank_) { bank = bank_; }

    function attack() external payable {
        bank.deposit{value: msg.value}();
        bank.withdraw();
    }

    receive() external payable {
        if (address(bank).balance >= 1 ether) {
            bank.withdraw();          // reverts: balance is already 0
        }
    }
}

contract Main {
    constructor() payable {}

    function main() external {
        SafeBank bank = new SafeBank();
        bank.deposit{value: 9 ether}();             // honest funds
        Attacker attacker = new Attacker(bank);

        try attacker.attack{value: 1 ether}() {
            console.log("attack succeeded?!");
        } catch Error(string memory reason) {
            console.log("attack failed:", reason);
        }
        console.log("bank holds:", address(bank).balance / 1 ether, "ETH");
    }
}
attack failed: send failed
bank holds: 9 ETH

The re-entrant withdraw hits require(amount > 0). Its revert makes the attacker's receive fail, so the outer call returns false and the whole attack reverts with send failed. The honest 9 ETH stay put.

Fix 2: a reentrancy guard

A mutex modifier blocks any second entry while a function is running. OpenZeppelin ships it as ReentrancyGuard with the nonReentrant modifier. Here's a minimal version:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

abstract contract ReentrancyGuard {
    uint256 private status = 1;
    error ReentrantCall();

    modifier nonReentrant() {
        if (status == 2) revert ReentrantCall();
        status = 2;
        _;
        status = 1;
    }
}

contract GuardedBank is ReentrancyGuard {
    mapping(address => uint256) public balances;

    function deposit() external payable { balances[msg.sender] += msg.value; }

    // still the buggy order, but the guard stops re-entry
    function withdraw() external nonReentrant {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "nothing to withdraw");
        (bool ok, bytes memory err) = msg.sender.call{value: amount}("");
        if (!ok) {
            assembly { revert(add(err, 32), mload(err)) }   // bubble up the callee's error
        }
        balances[msg.sender] = 0;
    }
}

contract Attacker {
    GuardedBank public immutable bank;
    constructor(GuardedBank bank_) { bank = bank_; }

    function attack() external payable {
        bank.deposit{value: msg.value}();
        bank.withdraw();
    }

    receive() external payable {
        if (address(bank).balance >= 1 ether) bank.withdraw();
    }
}

contract Main {
    constructor() payable {}

    function main() external {
        GuardedBank bank = new GuardedBank();
        bank.deposit{value: 9 ether}();
        Attacker attacker = new Attacker(bank);
        attacker.attack{value: 1 ether}();
    }
}
main() failed: custom error ReentrantCall()

The small assembly block re-throws the inner error so you can see why it failed: the guard's ReentrantCall error.

Beyond a single function

  • Cross-function reentrancy: the attacker re-enters a different function (e.g. transfer) that reads the same stale balance. Put nonReentrant on every function that shares the state, and follow CEI everywhere.
  • Read-only reentrancy: a view function returns stale values while another contract is mid-update, and a third contract trusts them.
  • Token callbacks: ERC-777 hooks and ERC-721's onERC721Received also hand control to the recipient. Any external call is a potential re-entry point, not only ether transfers.

Test yourself

What is the root cause of a reentrancy bug?

  1. Using uint256 for balances
  2. Making an external call before updating the contract's own state
  3. Using events
  4. Calling view functions

What is the correct order in the Checks-Effects-Interactions pattern?

  1. Interactions, checks, effects
  2. Effects, checks, interactions
  3. Checks, effects, interactions
  4. Checks, interactions, effects

Which of these can hand control to another contract and enable re-entry?

  1. Only transfer
  2. Only low-level call
  3. Any external call, including token transfers with callbacks
  4. Only delegatecall