Security Patterns
A reentrancy guard is a mutual-exclusion lock (mutex) that prevents a function from being called again before its first invocation has finished. It is the most common defense against reentrancy attacks, where an external call hands control back to an attacker mid-execution.
The guard sets a "locked" flag on entry, runs the function body, and clears the flag on exit. Any re-entrant call while the flag is set reverts. OpenZeppelin's ReentrancyGuard provides this via the nonReentrant modifier.
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract Vault is ReentrancyGuard {
function withdraw() external nonReentrant {
// cannot be re-entered before it returns
}
}
A reentrancy guard only protects the functions it decorates. It does not stop read-only reentrancy, where an attacker re-enters through an unguarded view function. Guards are also no substitute for the checks-effects-interactions pattern.
Q: Does a reentrancy guard stop all reentrancy?
A: No. It protects the decorated state-changing functions but not read-only reentrancy through unguarded view functions, and it does not replace ordering state updates before external calls.
Q: Is a reentrancy guard enough on its own?
A: Use it together with checks-effects-interactions. The guard is defense-in-depth; correct ordering of state changes before external calls is the primary fix.
Related terms
Firepan
Run a free surface scan — results in minutes, no credit card required.
Run Free Scan →