Dria

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

The `Statistics::variance` function will revert due to underflow if data[i] < mean, as this causes a negative result in unsigned arithmetic.

Summary

The Statistics::variance function will revert if the value of data[i] is less than the mean, indicating that the calculation for finding the difference is incorrect.

Vulnerability Details

We are using solidity version 0.8.20.

After Solidity version 0.8.0, any overflow or underflow will cause the transaction to revert.

In the Statistics::variance function, if the value of data[i] is less than mean, this situation can occur frequently because the mean is always less than some numbers in data set, leading to reverts.

Such reverts can cripple the contract, preventing it from functioning properly.

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;
}

Impact

The revert from underflow will prevent the contract from functioning properly.

Tools Used

Manual Review

Recommendations

The below given recommendations will give the absolution difference of numbers without reverting.

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;
+ // Absolute difference
+ 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 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.