Skip to content

falconandrea/example-re-entrancy-vulnerability

Repository files navigation

trackgit-views

Simple example with Re-Entrancy Vulnerability

This repository demonstrates the re-entrancy vulnerability in Solidity smart contracts. The re-entrancy vulnerability is a common issue that can occur during the development of Ethereum smart contracts. It is important to understand this vulnerability to write secure smart contracts.

Overview

Smart contracts on Ethereum are autonomous programs that execute on the blockchain. When a smart contract receives a transaction, it executes a specific set of instructions defined in its code. The re-entrancy vulnerability occurs when a smart contract interacts with another contract during the execution of instructions, allowing the other contract to repeatedly call back the original contract before the execution completes.

This can be a problem because Solidity smart contracts use a "pay first" model, where transactions send funds before executing the code. If a contract recursively calls the original contract before the execution completes, without interrupting the control flow, it may access the not-yet-updated funds, enabling fraudulent activity.

Example

The VulnerableContract.sol file in this repository contains a simplified example that demonstrates the re-entrancy vulnerability. In this contract, users can deposit funds and withdraw them. However, an attacker can exploit the vulnerability by creating a contract that repeatedly calls the withdraw() function before the balance is updated, allowing them to withdraw more funds than they have.

Testing

To test the re-entrancy vulnerability in the VulnerableContract:

npm install
npx hardhat test

Note: The test is designed to validate the vulnerability, and it should pass. Do not deploy the vulnerable contract to a production environment without addressing the re-entrancy vulnerability.

Make sure to review and understand the code in the VulnerableContract.sol and AttackContract.sol files before running the tests.

Mitigation

To prevent the re-entrancy vulnerability, it is essential to follow secure coding practices in Solidity. Some recommended mitigation strategies include:

  1. Implement the "pay first, withdraw after" pattern, where you update the user's balance before sending the funds.
  2. Use the nonReentrant modifier to prevent recursive calls within the same transaction.
  3. Avoid making external calls or interacting with untrusted contracts during critical operations.
  4. Thoroughly review and test smart contracts to identify and address potential vulnerabilities.

Disclaimer

This repository is for educational purposes only and serves as a demonstration of the re-entrancy vulnerability. It should not be used for deploying production-ready contracts without proper security reviews and testing.

Please use caution when developing smart contracts and seek security audits if needed.