Dria

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

Variance will always revert because of the underflow that will happen while subtracting

Summary

The vulnerability in the Statistics#variance function is due to the possibility of underflow when calculating the difference between elements in the dataset and the mean. Since at least one element in a dataset with varied values will be less than the mean, the calculation data[i] - mean will revert due to underflow

Vulnerability Details

Here is Statistics#variance function:

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;
}
ans = sum / data.length;
}

The function checks the average/mean of the data set, then calculates diff by subtracting the mean from each element in the data set (data[i]).

The issue is that in every dataset, as long as all elements are not equal, the mean will surely be greater than at least 1 element in the data set.
This will cause the diff calculation to underflow

For example,

  • Given a data set [1,2,3], mean = 2

  • We can see that one element is less than the mean.

Trying to calculate the variance over this data set will underflow cos the function will calculate diff as 1-2.

Impact

Revert when last validator calls validate; unable to finalize validation

Tools Used

Manual Review

Recommendations

if mean>data[i], do: mean-data[i]
else: data[i]-mean

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.