✅Token
overflow and underflow
Description
The goal of this level is for you to hack the basic token contract below.
You are given 20 tokens to start with and you will beat the level if you somehow manage to get your hands on any additional tokens. Preferably a very large amount of tokens.
Things that might help:
What is an odometer?
Code Audit
The description states that we are given 20 tokens initially. That is, the contract is deployed with _initialSupply = 20
, so balances[msg.sender] = 20
is executed by the constructor.
The issue is at require(balances[msg.sender] - _value >= 0)
. Recall that uint
can underflow. If we transfer 21 tokens out to some random address (such as the zero address), we will have balances[msg.sender] - _value = -1
. Since uint
does not handle negative numbers, this -1
underflows to a huge positive number on the other side of the spectrum, hence the require()
statement evaluates to true.
When balances[msg.sender] -= _value
is handled, underflow is triggered one more time, and then balances[msg.sender]
is updated to a huge positive number.
Solution
Transfer 21 tokens to the zero address:
Verify that we own a huge number of tokens now:
Click "Submit instance" and move on to the next level.
Summary
Overflows are very common in solidity and must be checked for with control statements such as:
An easier alternative is to use OpenZeppelin's SafeMath library that automatically checks for overflows in all the mathematical operators. The resulting code looks like this:
If there is an overflow, the code will revert.
Last updated