Created
September 22, 2021 18:03
-
-
Save nathan-websculpt/217d6b08fccc9016878c7d84d51675bc to your computer and use it in GitHub Desktop.
Here is an example of the OpenZeppelin Reentrancy Guard in use
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
Thanks. This is a useful example.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used as an example in This Blog Post