A Reentrancy Guard is a security mechanism used in smart contracts (especially in Solidity) to prevent reentrancy attacks — a common vulnerability where a malicious contract repeatedly calls back into a function before the previous execution finishes, potentially draining funds
How it works:
Modifier:
- Reentrancy guards are typically implemented as a modifier in Solidity (or similar mechanisms in other languages).
Locking Mechanism:
- The modifier utilizes a boolean flag (often named locked or similar) to indicate whether the function is currently executing.
Before Execution:
- When a function protected by the reentrancy guard is called, the guard first checks if the flag is set (meaning the function is already running). If the flag is set, the call is typically reverted or ignored to prevent re-entry.
During Execution:
- If the function is not already executing, the guard sets the flag to indicate the function is now running and then proceeds with the function's logic.
After Execution:
- After the function completes its execution, the guard resets the flag to its initial state (e.g., false), indicating that the function is available for another call.
Example:
- A popular implementation is the nonReentrant modifier from OpenZeppelin. It prevents a contract from calling itself (directly or indirectly).