4. Describe reentrancy attack on Ethereum
Understanding Reentrancy in Ethereum Smart Contracts¶
Introduction¶
Reentrancy is a common vulnerability in Ethereum smart contracts. It occurs when a contract calls an external contract, which then calls back into the original contract before the first execution completes.
Core Concepts¶
- Smart Contracts: Self-executing contracts with the terms of the agreement between buyer and seller directly written into lines of code.
- Ethereum Blockchain: A decentralized platform that runs smart contracts.
How Reentrancy Happens¶
- Initial Call: A user or contract initiates a function call in a smart contract.
- External Call: This function then makes an external call to another contract.
- Callback: The external contract makes a recursive call back to the original function.
The Vulnerability¶
If the original function does not properly manage its state or handles funds incorrectly before making an external call, the external contract can exploit this by recursively calling back, leading to unexpected behaviors like multiple withdrawals.
Example Scenario¶
- A smart contract has a function to withdraw funds.
- A user calls this function, which transfers funds and then updates their balance.
- If the contract sends funds before updating the balance, a malicious contract can repeatedly call this function, draining the contract's funds.
Reentrancy Prevention¶
- Update State First: Always update all internal states before calling external contracts.
- Reentrancy Guards: Use modifiers that prevent reentry into certain functions.
- Pull Over Push for Payments: Allow users to withdraw funds themselves rather than pushing funds to them.
- Use Reentrancy-safe Libraries: Such as OpenZeppelin's
ReentrancyGuard.