code-423n4 / 2021-09-yaxis-findings

0 stars 0 forks source link

The `sqrt` function can overflow execute invalid operation #104

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

hrkrshnn

Vulnerability details

The sqrt function can overflow execute invalid operation

The function sqrt is incorrect for the x = type(uint).max.

function sqrt(
    uint256 x
)
    private
    pure
    returns (uint256 y)
{
    uint256 z = (x + 1) / 2;
    y = x;
    while (z < y) {
        y = z;
        z = (x / z + z) / 2;
    }
    y = y * (10 ** 9);
}  

Because of the overflow in x + 1, the value of z is 0. The expression z = (x / z + z) / 2; in the for loop does a division by zero (an invalid opcode) for solidity versions below 0.8.0, consuming all the remaining gas in the context. Although the function ends in a halting state for x = type(uint256).max, the sqrt is well defined.

Note that the sqrt function does a final scaling, I've ignored the scaling part. It is also recommended to rename the function to sqrtAndScale or something more readable.

GainsGoblin commented 2 years ago

Realistically the protocol will never calculate sqrt for x=type(uint).max.

GalloDaSballo commented 2 years ago

Sponsor has acknowledged