Lab: free tools · size first · stock scanner · crypto scanner · journal

General

Integer Overflow and Underflow in Smart Contracts

Integer overflow occurs when an arithmetic operation produces a result larger than the maximum value a data type can hold, causing it to wrap around to a very small (or zero) value. Underflow is the reverse. Subtracting past zero wraps around to the maximum value. These bugs in Ethereum smart contracts have been exploited to mint unlimited tokens, bypass balance checks, and drain protocols. Solidity 0.8+ includes automatic overflow/underflow protection.

An integer overflow happens when a number goes past the largest value its type can hold and wraps around to a small one; underflow is the reverse. In older Solidity contracts, this let attackers mint huge balances or bypass checks. Since Solidity 0.8, arithmetic reverts on overflow by default, which removed most of the problem. It still matters in code using unchecked blocks or older compiler versions.

The batchOverflow bug

In April 2018 attackers hit the BeautyChain (BEC) token with a bug later logged as CVE-2018-10299. Its batchTransfer function multiplied the number of receivers by the amount each should get, then checked that total against the sender's balance. With two receivers and a huge amount, the multiplication wrapped past the top of a 256 bit number and came out as zero. Zero passed the balance check, and each receiver was credited the huge amount anyway, roughly 57.9 times ten to the 57th power BEC. OKEx suspended BEC trading after the attack, and other tokens using the same code were flagged.

What changed in Solidity 0.8

Since version 0.8.0, Solidity reverts any addition, subtraction or multiplication that would overflow or underflow. The language team says it made checking the default for readability, at a slight gas cost. Before that, careful teams wrapped every operation in a SafeMath library. Developers who want the old wrapping behavior, usually to save gas in a loop counter that can't overflow, write the code inside an unchecked block. Overflow in 0.8 now ends in a Panic error with its own code, which tools can tell apart from a normal failed require.

Where it still bites

Old contracts compiled before 0.8 are still live and can't be patched unless they're upgradeable. Unchecked blocks are only safe if the reasoning behind them is right. Casting a large number into a smaller type, say from a 256 bit value down to 128 bits, can silently cut off the top bits. Inline assembly skips the compiler's checks entirely. Rounding and precision mistakes are a close cousin and still show up in audits.

What to look for as a user

Check a token contract's compiler version on its explorer page. Anything before 0.8 should show SafeMath or a similar library in its math. A token that can be minted in huge amounts by a bug can crash to zero in minutes, as BEC did on exchanges that still listed it.