A re-entrancy attack is a type of vulnerability that can occur in smart contracts that allow an attacker to repeatedly call an external contract in a way that consumes all available gas. This can lead to a denial of service (DoS) attack or allow the attacker to exploit the contract for their own benefit.
Here is an example of a simple contract written in Solidity that is vulnerable to a re-entrancy attack:
pragma solidity ^0.6.0;
contract ReentrancyAttack {
// The attacker's contract address
address public attacker;
// The contract's balance
uint public balance;
// Constructor to set the attacker's contract address
constructor(address _attacker) public {
attacker = _attacker;
}
// Fallback function that is called when the contract receives ether
function() external payable {
// Update the contract's balance
balance += msg.value;
// Call the attacker's contract
attacker.call.value(msg.value)();
}
}
In this example, the contract has a fallback function that is called whenever the contract receives ether. The function updates the contract's balance and then calls the attacker's contract. If the attacker's contract calls back into the original contract, it can create an infinite loop that consumes all available gas.
To prevent this type of attack, it is important to carefully consider the potential for re-entrancy when designing and implementing smart contracts. One way to do this is to use a mutex or lock to prevent multiple calls to the contract's functions at the same time.
Here is an example of how to use a mutex to prevent a re-entrancy attack in Solidity:
pragma solidity ^0.6.0;
contract ReentrancyAttack {
// The attacker's contract address
address public attacker;
// The contract's balance
uint public balance;
// A flag to indicate if the contract is currently executing
bool public executing;
// Constructor to set the attacker's contract address
constructor(address _attacker) public {
attacker = _attacker;
}
// Fallback function that is called when the contract receives ether
function() external payable {
// Set the executing flag to true
executing = true;
// Update the contract's balance
balance += msg.value;
// Call the attacker's contract
attacker.call.value(msg.value)();
// Set the executing flag to false
executing = false;
}
}
In this example, the contract sets a flag (executing) to true before calling the attacker's contract and sets it to false after the call is complete. This allows the contract to prevent re-entrancy by checking the executing flag before executing any functions.
It is important to note that this is just one way to prevent re-entrancy attacks, and there may be other methods that are more suitable for different types of contracts. It is always best to carefully consider the potential vulnerabilities of your contract and take steps to mitigate them.
First posted here.