10 - Reentrancy

classic reentrancy attack

Ethernaut Level10: Reentrancyarrow-up-right

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;

import 'openzeppelin-contracts-06/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 {}
}d

Goal of this level

  • steal all the funds from the contract

What you should know before

Solution

chevron-rightKey to solve this problem 🔑hashtag

This level can easily be solved using classic reentrancy attack.

Call attack function with 0.001 ether .

Done! 😎

Key Takeaways

Last updated