Prevent Integer Overflow in Ethereum Smart Contracts
Do you know that most of the hacker attacks for stoling money from smart contracts are based on a type of bug called Integer Overflow? Today we dicuss about this kind of bug and how to simply prevent it.
Let’s get back to the fundermental
So what is Integer Overflow? Basically it is the case you make an integer variable store the value bigger than it limit, for example a 32-bit integer can store value from -2³¹ to 2³¹-1. If you assign a number out of the range to the variable, its value will become something else and what is the value depend on how the integer is presented in the system.
e.g. we have a 8-bit unsigned integer which store value from 0 to 255. Take a look at below snippet:
uint a = 255;
a = a + 1; // Now a = 0
So why a = 0 after we plus 1? Because a
‘s binary presentation is: 11111111
when we plus 1 it is like this:
11111111 + 00000001 = 100000000
The result in binary is 100000000
which has 9 bits, but in the memory where your variable a
stored only have 8 bits, which is the last 8 zero-bits. That’s why the variable a
become 0
You can see that Integer Overflow is very simple to understand, and it not only happen for plus operator but also other operator as well.