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.
Handle
hrkrshnn
Vulnerability details
The
sqrt
function can overflow execute invalid operationThe function sqrt is incorrect for the
x = type(uint).max
.Because of the overflow in
x + 1
, the value ofz
is0
. The expressionz = (x / z + z) / 2;
in the for loop does a division by zero (aninvalid
opcode) for solidity versions below 0.8.0, consuming all the remaining gas in the context. Although the function ends in a halting state forx = type(uint256).max
, thesqrt
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.