-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_reentrancy-eth.sol
More file actions
46 lines (39 loc) · 1.43 KB
/
Copy path_reentrancy-eth.sol
File metadata and controls
46 lines (39 loc) · 1.43 KB
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Reentrance {
mapping (address => uint) userBalance;
function getBalance(address u) public view returns(uint){
return userBalance[u];
}
function addToBalance() payable public{
userBalance[msg.sender] += msg.value;
}
function withdrawBalance() public {
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool error, )=msg.sender.call{value: userBalance[msg.sender]}("");
if( !error ){
revert();
}
userBalance[msg.sender] = 0;
}
function withdrawBalance_fixed() public{
// to protect against re-entrancy, the state variable
// has to be change before the call
uint amount = userBalance[msg.sender];
userBalance[msg.sender] = 0;
(bool error, )=msg.sender.call{value: amount}("");
if(!error){
revert();
}
}
function withdrawBalance_fixed_2() public {
// send() and transfer() are safe against reentrancy
// they do not transfer the remaining gas
// and they give just enough gas to execute few instructions
// in the fallback function (no further call possible)
address payable dest = payable(msg.sender);
dest.transfer(userBalance[msg.sender]);
userBalance[msg.sender] = 0;
}
}