Arithmetic overflow and underflow vulnerabilities arise from the binary storage system used in computer programs, including smart contracts. In Solidity, the programming language for Ethereum smart contracts, unsigned integers are declared with types such as uint8, uint16, up to uint256. For instance, a uint8 has a maximum value of 2**8 or 256 (ranging from 0 to 255).
Arithmetic overflow occurs when the result of a mathematical operation exceeds the maximum value that the program can store. For example, if we have a computation like uint8 value = 128 * 2, the result would be 256, which exceeds the maximum value a uint8 can hold. In earlier versions of Solidity (< 0.8.0), such computations would "wrap around" instead of throwing exceptions.
Wrapping around means that if the largest possible integer value is reached, it continues from the smallest possible value (and vice versa). So, in Solidity versions prior to 0.8.0, the computation uint8 value = 128 * 2 would result in 1 instead of an overflow error. This vulnerability creates an entry point for attackers to manipulate outcomes through overflow or underflow attacks, compromising the integrity of smart contracts.
⚡️ Preventing Arithmetic Underflow and Overflow in Solidity ⚡️
To prevent this vulnerability in Solidity, it is recommended to use versions 0.8.0 and above. In these versions, arithmetic underflows and overflows result in reversion and errors automatically, improving the security of your smart contracts.
If you are using versions prior to 0.8.0, you can utilize the Open Zeppelin Safe Math library. This library provides safe arithmetic operations with overflow checks that revert any overflowing operations, preventing vulnerabilities caused by arithmetic overflow and underflow.
Here are a couple of interesting details I learned about Solidity while working on Exercise No. 3:
➤ Solidity performs calculations without following the usual mathematical rules of dividing first and then multiplying when parentheses are not used. Instead, it calculates expressions from left to right.
➤ Remember that Solidity deals with integers, so floating-point numbers are not supported.
I hope this provides you with a clearer understanding of arithmetic overflow and underflow vulnerabilities in Solidity and how to prevent them.