AuditBase
Sign InGet Started
low

Subtraction may underflow if multiplication is too large

Investigate the potential for numeric underflows in programming when large multiplications lead to subsequent subtraction underflows. This article explores the causes, impacts, and safeguards programmers can use to detect and prevent such vulnerabilities, ensuring accurate and secure calculations.

Category

general

Languages

solidity

Analysis Layer

static

Severity

low

In Solidity, performing arithmetic operations like subtraction after a multiplication can lead to underflow issues if not handled properly. Underflow occurs when an arithmetic operation results in a value lower than the minimum representable value, which in unsigned integers (the most common type in Solidity) wraps around to a very large number. This can introduce serious vulnerabilities and unexpected behavior in smart contracts.

Problem

If a multiplication result is too large, subsequent subtraction may cause an underflow. For example, subtracting a large product from a smaller number can wrap around, leading to incorrect and potentially dangerous outcomes.

Solution

To prevent underflows, it's essential to perform checks before conducting arithmetic operations that might result in values lower than the representable range. Solidity 0.8 and later versions automatically revert on underflow and overflow, but earlier versions require explicit checks.

Example Code

pragma solidity ^0.8.0;

contract SafeArithmetic {
    // Function demonstrating the problem of underflow
    function unsafeOperation(uint256 a, uint256 b, uint256 c) public pure returns (uint256) {
        uint256 product = a * b;
        return product - c; // This may underflow if product < c
    }

    // Safe arithmetic operations with checks
    function safeOperation(uint256 a, uint256 b, uint256 c) public pure returns (uint256) {
        uint256 product = a * b;
        
        // Check to prevent underflow
        require(product >= c, "Underflow error: product is less than c");

        return product - c;
    }
}

Conclusion

Underflow issues in smart contracts can lead to severe vulnerabilities and unexpected behavior. Ensuring safe arithmetic operations by performing checks before subtraction or using Solidity's built-in safety features in version 0.8 and later is essential for maintaining the integrity and security of smart contracts. By adopting these practices, developers can create more robust and reliable decentralized applications.