5 - Token

overflow / underflow in Solidity

Ethernaut Level5: Tokenarrow-up-right

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

contract Token {

  mapping(address => uint) balances;
  uint public totalSupply;

  constructor(uint _initialSupply) public {
    balances[msg.sender] = totalSupply = _initialSupply;
  }

  function transfer(address _to, uint _value) public returns (bool) {
    require(balances[msg.sender] - _value >= 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
  }

  function balanceOf(address _owner) public view returns (uint balance) {
    return balances[_owner];
  }
}

Goal of this level

  • Having more than 20 tokens.

What you should know before

Solution

chevron-rightKey to solve this problem πŸ”‘hashtag

There was no overflow/underflow protection before solidity version 0.8

Use Remix IDE!

Maximum value that uint256 variable can have is 2**256 - 1.

Initial Token balance of AttackToken contract is 0.

But when you call attack() function, underflow occurs so the balance of AttackToken contract becomes 2**256 - 2.

You will eventually have 22 tokens after you deploy AttackToken contract and call attack().

Done! 😎

Key Takeaways

  • Overflow/Underflow occured in solidity versions before 0.8

Last updated