Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article explains integer overflow and underflow.

These arithmetic errors can lead to financial losses in smart contracts, so understanding them is essential for Solidity developers and bug bounty researchers.

If you are unfamiliar with the series, see the following related article.

[Solidity-Bug Bounty] Understanding How Malicious Code Can Be Hidden

What are overflow and underflow?

Overflow

Overflow occurs when a value exceeds the maximum representable by its data type.

Think of a glass filled to the brim: adding more water makes it overflow. This analogy illustrates the term, not the precise behavior of binary arithmetic.

A Solidity uint8 can represent integers from 0 to 255. Suppose maxNum is initialized to 255.

javascript
uint8 public maxNum= 255;

What happens when we add 1? Consider the following function.

javascript
function addNum() public {
    maxNum ++;
}

Under the wrapping arithmetic used in the original Solidity 0.7 example, the result is 0.

Overflow result

The following diagrams illustrate the process.

Binary integer overflow

Binary integer overflow

Binary integer overflow

Binary integer overflow

The maximum value of uint8 is 2^8-1 = 255, represented in binary as 11111111.

Adding 1 gives 11111111 + 1 = 100000000. When arithmetic wraps to eight bits, the leading 1 is discarded and the result becomes 00000000, or 0 in decimal.

This explains why 255 + 1 wraps to 0 in this example.

Underflow

Underflow occurs when a value falls below the minimum representable by its data type.

Imagine trying to drink more water from an already empty glass. Again, this is only an analogy for the term.

A uint8 can represent 0 through 255. Suppose minNum is initialized to its minimum value.

javascript
uint8 public minNum= 0;

What happens when we subtract 1? Consider this function.

javascript
function subNum() public {
    minNum --;
}

In the original wrapping-arithmetic demonstration, the result is 255.

Underflow result

The following diagrams illustrate underflow.

Binary integer underflow

Binary integer underflow

Binary integer underflow

Binary integer underflow

The minimum value is 0, represented as 00000000 in binary. Subtracting 1 gives -1 mathematically. With unsigned eight-bit wrapping arithmetic, the result is reduced modulo 256 to 11111111, or 255 in decimal.

This explains why 0 - 1 wraps to 255. It is modular arithmetic, not simply removal of a minus sign.

Code

The complete code used in the preceding demonstrations is reproduced here.

solidity
// SPDX-License-Identifier: GPL-3.0

// pragma solidity ^0.8.13;
pragma solidity ^0.7.6;

contract OverflowUnderflow {
    uint8 public maxNum= 255;
    uint8 public minNum= 0;
		
		/// @notice maxNumに1を加算する関数。
    function addNum() public {
        maxNum ++;
    }
		
		/// @notice minNumに1を減算する関数。
    function subNum() public {
        minNum --;
    }
}

Overflow and underflow in practice

Arithmetic vulnerabilities in a time-locked bank

To illustrate the security consequences, the original article uses a contract that accepts deposits and permits withdrawals after a specified period. The example is based on:

Bank

solidity
// SPDX-License-Identifier: GPL-3.0

// pragma solidity ^0.8.13;
pragma solidity ^0.7.6;

contract Bank {
		// 預け入れている資金を格納。
    mapping(address => uint) public balances;
    // 預け入れる期間を格納。
    mapping(address => uint) public lockTime;

    /// @notice 一定額資金を預けて、1週間後のタイムスタンプを保存する関数。
    function deposit() public payable {
        balances[msg.sender] += msg.value;
        lockTime[msg.sender] = block.timestamp + 1 weeks;
    }

    /// @notice 預けてる期間を延長できる。
    function increaseLockTime(uint _time) public {
        lockTime[msg.sender] += _time;
    }

    /// @notice 預けている資金を引き出し、balancesの値を0にする。   
    function withdraw() public {
        uint balance = balances[msg.sender];
        
        // 預けた資金があるか確認。 
        require(balance > 0, "There are no funds available to withdraw.");
        // 預け入れ期間を過ぎているか確認。
        require(block.timestamp > lockTime[msg.sender], "Lock time not expired");

        balances[msg.sender] = 0;

        // 送金
        (bool sent, ) = msg.sender.call{value: balance}("");

        // 資金を送れたかの確認。
        require(sent, "Failed to send Ether");
    }
}

deposit

Accepts a deposit of funds.

increaseLockTime

Extends the period for which the funds are locked.

withdraw

Allows funds to be withdrawn once the lock time has passed.

Attack

solidity
contract Attack {
    Bank bank;

    constructor(Bank _bank) {
        bank = Bank(_bank);
    }

    fallback() external payable {}

    function attack() public payable {
        bank.deposit{value: msg.value}();

        // 最大値から預け入れている期間を引いた値を取得。
        // その値に1を足すことで、預け入れている期間に加算した際、オーバーフローを起こす。
        bank.increaseLockTime(
            type(uint).max - bank.lockTime(address(this)) + 1
        );
        bank.withdraw();
    }
}

The demonstration contract is deployed with the address of Bank.

attack

The example deposits funds through Bank's deposit function. It demonstrates that unchecked addition can wrap the stored lock time to zero by using the difference between the maximum unsigned integer and the existing lock time, plus one.

The following simplified numerical example uses an illustrative maximum of 1000 rather than the real maximum of uint.

Example

  • Maximum representable value: 1000.
  • Existing lock time: 100.
  • Difference between the maximum and lock time: 1000 - 100 = 900.
  • Existing lock time plus that difference plus one: 100 + 900 + 1 = 1001 → 0 under the assumed wrapping arithmetic.

The original demonstration shows the resulting behavior.

Demonstration of lock-time overflow

A normal early withdrawal fails, whereas the overflow in the vulnerable example changes the lock time and permits a withdrawal. Arithmetic invariants therefore need explicit protection.

Mitigation

Preventing overflow and underflow

There are two approaches discussed in the original article.

Use Solidity 0.8 or later

The previous examples deliberately use Solidity 0.7. Starting with Solidity 0.8, ordinary arithmetic operations are checked by default. Overflow and underflow cause a runtime revert unless unchecked arithmetic is explicitly used.

The original demonstration switches to Solidity 0.8.

Checked arithmetic in Solidity 0.8

The operation that previously succeeded now fails.

Use the SafeMath library

A second historical approach is to use SafeMath. Its checked operations revert instead of allowing arithmetic to wrap.

The original code is shown below. Its remote import points to a moving branch and is not a reproducible dependency pin; modern Solidity normally provides checked arithmetic without SafeMath.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

// SafeMathをimport
import"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";

contract Bank {

    // uint256にSafeMathを使用。
    using SafeMath for uint256;

    mapping(address => uint) public balances;
    mapping(address => uint) public lockTime;

    /// @notice 一定額資金を預けて、1週間後のタイムスタンプを保存する関数。
    function deposit() public payable {
        balances[msg.sender] += msg.value;
        lockTime[msg.sender] = block.timestamp + 1 weeks;
    }

    /// @notice 預けてる期間を延長できる。
    function increaseLockTime(uint _time) public {
        // SafeMathを使用して加算
        lockTime[msg.sender] .add(_time);
    }

    /// @notice 預けている資金を引き出し、balancesの値を0にする。   
    function withdraw() public {
        uint balance = balances[msg.sender];
        
        // 預けた資金があるか確認。 
        require(balance > 0, "There are no funds available to withdraw.");
        // 預け入れ期間を過ぎているか確認。
        require(block.timestamp > lockTime[msg.sender], "Lock time not expired");

        balances[msg.sender] = 0;

        // 送金
        (bool sent, ) = msg.sender.call{value: balance}("");

        // 資金を送れたかの確認。
        require(sent, "Failed to send Ether");
    }
}

contract Attack {
    Bank bank;

    constructor(Bank _bank) {
        bank = Bank(_bank);
    }

    fallback() external payable {}

    function attack() public payable {
        bank.deposit{value: msg.value}();

        // 最大値から預け入れている期間を引いた値を取得。
        // その値に1を足すことで、預け入れている期間に加算した際、オーバーフローを起こす。
        bank.increaseLockTime(
            type(uint).max - bank.lockTime(address(this)) + 1
        );
        bank.withdraw();
    }
}

Conclusion

Summary of integer overflow and underflow

This article covered overflow, underflow, their security consequences, and ways to prevent them.

If you have questions, feel free to contact me on Twitter. I regularly write about Solidity, blockchain, and Web3 and share interesting articles there.

References

https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422