Reentrancy
Reentrancy is a smart contract vulnerability where an external call allows an attacker to re-enter the calling function before its state updates are complete, enabling repeated unauthorized actions such as draining funds.
In Depth
Reentrancy attacks exploit the fact that external calls in Solidity transfer execution control to the callee, which can call back into the original contract before state changes are finalized. The most infamous example is the 2016 DAO hack, which resulted in the loss of approximately $60 million in ETH and led to the Ethereum hard fork. The primary defense is the checks-effects-interactions pattern, where all state changes are made before any external calls. Reentrancy guards (mutexes) such as OpenZeppelin's ReentrancyGuard provide an additional layer of protection by locking the contract during execution. Modern fuzzing and invariant testing tools can systematically detect reentrancy by testing whether invariants hold mid-execution.
Frequently Asked Questions
What is a reentrancy attack in smart contracts?
A reentrancy attack occurs when a malicious contract exploits an external call to re-enter the vulnerable contract before its state updates are finished. This allows the attacker to repeat actions like withdrawals multiple times. The DAO hack in 2016 is the most well-known reentrancy exploit, draining roughly $60 million in ETH.
How do you prevent reentrancy in Solidity?
The main defenses are the checks-effects-interactions pattern (update all state before making external calls) and reentrancy guards like OpenZeppelin's ReentrancyGuard modifier. Additionally, invariant testing with fuzzers can verify that no sequence of calls violates accounting invariants mid-execution.
Can fuzzing detect reentrancy vulnerabilities?
Yes. Stateful fuzzers like Echidna and Medusa can be configured with callback-enabled actors that attempt to re-enter the contract during external calls. By checking invariants after each step, the fuzzer can detect when reentrancy leads to an inconsistent state.