Dria

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

Variance calculation can underflow often and cause task to never be completed

Summary

During the variance calculation there could be underflow which will cause revertion of validation and inturn result in the task never being completed.

Vulnerability Details

In the calculation of variance the line uint256 diff = data[i] - mean;could underflow and revert very frequently.

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

(https://github.com/Cyfrin/2024-10-swan-dria/blob/c8686b199daadcef3161980022e12b66a5304f8e/contracts/libraries/Statistics.sol#L18-L26)

Assume the following dataset:
data = [1,10,10]
1. Mean = (1+10+10)/3 = 7
During the calculation of variance:
uint256 diff = 1 - 7 is done, this will revert since the mean > data[i].
Causing the task to never be completed.



Impact

Complete DOS of the task naturally(no attack is needed, and the likelihood of this quite common).

Tools Used

Manual Review

Recommendations

Update the function as follows:

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

Lead Judging Commences

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