Integer Overflow & Underflow
Integer Overflow & Underflow
Integer overflow and underflow vulnerabilities occur when arithmetic operations exceed the maximum or minimum value a variable type can hold.
Understanding the Issue
In Solidity versions before 0.8.0, integer operations did not check for overflow/underflow by default.
Overflow Example
uint8 maxValue = 255;
maxValue = maxValue + 1; // Overflows to 0 (in Solidity < 0.8.0)Underflow Example
uint8 minValue = 0;
minValue = minValue - 1; // Underflows to 255 (in Solidity < 0.8.0)Solidity 0.8.0+ Protection
Starting with Solidity 0.8.0, overflow/underflow checks are built-in and will cause transactions to revert automatically.
// Solidity ^0.8.0
uint8 value = 255;
value = value + 1; // Will revert with "Arithmetic operation overflow"When to Use Unchecked
For gas optimization, you can use `unchecked` blocks when you're certain overflow won't occur:
function increment(uint counter) public pure returns (uint) {
unchecked {
return counter + 1; // Skip overflow check for gas savings
}
}Legacy Contract Protection
For contracts using Solidity < 0.8.0, use SafeMath library:
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract LegacyContract {
using SafeMath for uint256;
uint256 public value;
function add(uint256 amount) public {
value = value.add(amount); // Safe addition
}
function subtract(uint256 amount) public {
value = value.sub(amount); // Safe subtraction
}
}Best Practices
1. Use Solidity 0.8.0 or higher
2. Only use `unchecked` when absolutely necessary and safe
3. For legacy contracts, always use SafeMath
4. Test edge cases with maximum and minimum values
5. Document any unchecked arithmetic operations
Detection
- **Slither**: Detects unsafe arithmetic operations
- **Mythril**: Identifies potential overflow/underflow
- **Manual review**: Check all arithmetic operations