Token
// 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
We need to hack the Token smart contract in a way that the amount of tokens within our account will be very large
Exploit
The way we are going to exploit this smart contract is by causing the value inside balances[msg.sender] to underflow.
We now that we are starting witn inital balance of 20 tokens. Inside the transfer() function we can see that we are substracting our initial balance from the amount of tokens that we wish to transfer:
balances[msg.sender] -= _value;
So, in order to cause the underflow we just need to pass value bigger than 20 for the _value parameter inside transfer() function
Note that this exploit can not happen in version of Solidity starting from 0.8 or if using the SafeMath library from OpenZeppelin
To exploit the contract we need to:
- call the transfer() function with argument bigger than 20 for the _value parameter ex. contract.transfer(0x000000, 21)