Skip to content

Instantly share code, notes, and snippets.

@nathan-websculpt
Created September 22, 2021 18:03
Show Gist options
  • Save nathan-websculpt/217d6b08fccc9016878c7d84d51675bc to your computer and use it in GitHub Desktop.
Save nathan-websculpt/217d6b08fccc9016878c7d84d51675bc to your computer and use it in GitHub Desktop.
Here is an example of the OpenZeppelin Reentrancy Guard in use
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/security/ReentrancyGuard.sol";
contract Attackee is ReentrancyGuard {
mapping(address => uint) public attackeeBalances;
function depositIntoAttackee() external payable {
attackeeBalances[msg.sender] += msg.value;
}
function withdrawFromAttackee() external nonReentrant {
uint senderBalance = attackeeBalances[msg.sender];
require(senderBalance > 0);
attackeeBalances[msg.sender] = 0;
(bool success, ) = address(msg.sender).call{ value: senderBalance }("");
require(success, "withdrawFromAttackee failed to send");
}
function getBalanceFromAttackee() external view returns (uint) {
return address(this).balance;
}
}
contract Attacker {
Attackee public contractToAttack;
constructor(address _contractToAttackAddress) {
contractToAttack = Attackee(_contractToAttackAddress);
}
//this is called when Attackee sends Ether to this contract (Attacker)
receive() external payable {
//comment this out to allow the withdrawal
//if(address(contractToAttack).balance >= 1 ether) {
// contractToAttack.withdrawFromAttackee();
//}
}
function depositIntoAttackee() external payable {
require(msg.value >= 1 ether);
contractToAttack.depositIntoAttackee{value: msg.value}();
}
function performAttack() external {
contractToAttack.withdrawFromAttackee();
}
function getBalanceFromAttacker() external view returns (uint) {
return address(this).balance;
}
}
@rhcproc
Copy link

rhcproc commented Dec 2, 2022

Thanks. This is a useful example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment