Simple Explanation of Integer Overflow in Smart Contracts

·

2 min read

An integer overflow vulnerability happens when a number variable in Solidity exceeds its maximum value or goes below its minimum value, causing it to "wrap around" and behave unexpectedly.

How It Works:

  • In Solidity, integers have a fixed size (e.g., uint8, uint256).

    • uint8: Can store values from 0 to 255.

    • uint256: Can store values from 0 to 2^256 - 1.

Overflow:

  • If you add to a number that’s already at its maximum value, it wraps back to 0.

    • Example: uint8 x = 255; x = x + 1;x becomes 0.

Underflow:

  • If you subtract from a number at its minimum value, it wraps back to the maximum value.

    • Example: uint8 x = 0; x = x - 1;x becomes 255.

Why It’s Dangerous:

Attackers can exploit this to manipulate calculations and bypass restrictions in smart contracts.

Example:

solidityCopyEditcontract Vulnerable {
    uint8 public balance = 255;

    function add(uint8 _amount) public {
        balance += _amount; // Overflow occurs if _amount > 0
    }
}
  • What Happens:

    • If someone calls add(1), the balance wraps around to 0 instead of increasing further.

    • This can lead to broken logic or financial losses.

How to Prevent It:

  1. Use SafeMath Library:

    • Before Solidity 0.8, you could use the SafeMath library to prevent overflows.

    • It reverts the transaction if an overflow or underflow occurs.

  2. Upgrade to Solidity 0.8+:

    • Solidity 0.8+ has built-in overflow and underflow checks. If an operation causes an overflow/underflow, the transaction automatically reverts.