Dria

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

Variance Is Not Working

Summary

The function Statistics::variance calculates the variance of a dataset. However, the current implementation is prone to a revert error when attempting to compute the difference between each data point and the mean, particularly for values less than the mean. This happens because of underflow in the subtraction operation.

Vulnerability Details

In the current implementation, when calculating variance, the function iterates over each data point in the array and calculates the difference between the data point and the mean. If a value in data is less than the mean, subtracting mean from that value results in a negative number, which causes an underflow in unsigned integer arithmetic, leading to a revert.

Example Scenario:

Input array: [1, 2, 3, 4, 5]
The mean is calculated as 3.
When the first element 1 is processed, the function attempts to compute 1 - 3, which results in an underflow for uint256 and causes the function to revert.

Impact

This vulnerability effectively breaks the variance function for any input where one or more data points are less than the mean, making the function unreliable and unusable for many typical datasets.

Tools Used

Manual Review

Recommendations

Make the following changes:

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;
- sum += diff * diff;
+ int256 diff = data[i] - mean;
+ sum += uint256(diff * diff);
}
ans = sum / data.length;
}
Updates

Lead Judging Commences

inallhonesty Lead Judge 12 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.