Dria

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

Underflow revert in variance calculation

Summary

To calculate the variance, we subtract the mean from each number in the dataset, square these differences, sum them up, and then find the average of these squared differences. This method helps in quantifying how much the numbers in the dataset deviate from the mean.
The issue at hand here is that we will in most cases inevatibily run into an underflow error since not each number is bigger than the mean.

Vulnerability Details

The mean is calculated as the sum of all numbers in the data array divided by data.length. By nature, we expect some numbers to be above the mean and some below it. The current library used to calculate variance does not account for numbers below the mean, leading to underflows.

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; <@ will underflow
sum += diff * diff;
}
ans = sum / data.length;
}

As a result this calculation will underflow when data[i] < mean.

Impact

Calculations cannot move forward, finalizeValidtion will revert, and thus validations may not be finalized.

Tools Used

Recommendations

Changes are imperative in order to avoid underflows.

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;
+ if(data[i] > mean) uint256 diff = data[i] - mean;
+ else uint256 diff = mean - data[i];
sum += 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.