A reentrancy attack exploits a contract that makes an external call before updating its own state. The called contract (the attacker’s) calls back into the original function before the first call finishes, while the contract still thinks nothing has changed, repeating an action (like a withdrawal) many times to drain funds. It is the bug behind The DAO hack and many since. The fix is the checks-effects-interactions pattern (update state before external calls) and a reentrancy guard.
What reentrancy is
When a contract sends Ether or calls another contract, it hands over execution to that other contract, which can run arbitrary code, including calling back into the original contract.
Reentrancy is when the original function calls out before it has finished updating its own state. The attacker’s contract re-enters the function while the old state still says, for example, "you have a balance to withdraw", and exploits that stale state repeatedly.
How it works and example
Classic vulnerable withdraw, the external call happens before the balance is zeroed:
function withdraw() public {
uint bal = balances[msg.sender];
(bool ok,) = msg.sender.call{value: bal}(""); // calls attacker first
balances[msg.sender] = 0; // state updated too late
}
The attacker’s receive()/fallback() calls withdraw() again before balances is set to 0, so the check still passes and they withdraw repeatedly, draining the contract. Cross-function and read-only reentrancy are variants. Shown for defensive context.
How to defend
- Follow checks-effects-interactions: update state before any external call.
- Use a reentrancy guard (a
nonReentrantmodifier) on functions that make external calls. - Prefer pull-over-push for payments so withdrawals do not call untrusted code mid-state.
- Beware read-only reentrancy: a view function reading mid-update state can mislead other protocols; guard those interactions too.
- Audit and test every external-call path for re-entry, including cross-function cases.
References
- [1]SWC Registry: Smart Contract Weakness Classification(SWC Registry)
- [2]Ethereum.org: Smart contract security(Ethereum.org)
- [3]Solidity docs: Security considerations(Solidity)