Dria

Swan
NFTHardhat
21,000 USDC
View results
Submission Details
Severity: high
Valid

Potential `underflow` in `variance` calculation leads to reverts

Summary

A vulnerability exists in the variance() function where an underflow can occur if any element in the data array is smaller than the calculated mean. This results in a revert due to Solidity’s checked arithmetic introduced in versions ^0.8.0 and above, which does not permit underflows in unsigned integers (uint256).

Vulnerability Details

The function calculates variance by iterating through an array data and computing the squared difference between each element and the mean.

function variance(uint256[] memory data) internal pure returns (uint256 ans, uint256 mean) {
mean = avg(data);
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
>> uint256 diff = data[i] - mean; // Underflow if data[i] < mean
sum += diff * diff;
}
ans = sum / data.length;
}

However, when an element in data is less than the mean, the subtraction operation leads to an underflow, causing a revert.

Scenario:

  • Consider an array with values such as data = [2, 5, 4, 9].

  • Mean is calculated as 20/4 = 5

  • When iterating over the array, for data[0] = 2, the difference 2 - 5 results in a negative value.

  • This underflow causes an immediate revert, halting execution.

Impact

The underflow vulnerability in the variance function causes reverts if any value in data is less than the mean, effectively making the function unreliable.

Tools Used

Manual Review

Recommendations

Use absolute difference:

function variance(uint256[] memory data) internal pure returns (uint256 ans, uint256 mean) {
mean = avg(data);
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
- uint256 diff = data[i] - mean;
+ uint256 diff = data[i] > mean ? data[i] - mean : mean - data[i];
sum += diff * diff;
}
ans = sum / data.length;
}
Updates

Lead Judging Commences

inallhonesty Lead Judge 7 months ago
Submission Judgement Published
Validated
Assigned finding tags:

Underflow in computing variance

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.