Dria

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

Calculating The Standard Deviation And Mean For A Set Of Generations Or Validations Would Revert When Calculating Differences In Getting The Variance

Summary

When calculating the standard deviation in the finalizeValidation in the Swan.sol the function reverts due to arithmetic underflow when calculating the variance in the Statistics.sol library.

Vulnerability Details

The finalizeValidation function on the last validation required for the request finalized the validation by making use of mean values and standard deviation to get a good range of scores.

Inside the finalizeValidation function we have this line of code

// ..... some other code here ....
// compute the mean and standard deviation
(uint256 _stddev, uint256 _mean) = Statistics.stddev(scores);
// ..... some other code here ....

Inside the stddevfunction we calculate the mean and the variance, the sqrt of the vaiance returns the standard deviation.

Here is the function:

Inside the function we have the variance calculated as follows, the issue lies where the set of values in the data that was passed are either higher, lower or equal to the mean value.

The scores that are lower than the mean value would revert inside this statement uint256 diff = data[i] - mean;

/// @notice Compute the variance of the data.
/// @param data The data to compute the variance for.
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++) {
// this is where the issue lies
// the values in the data array for the scores of the generation or validation
// could have higher or lower values than the mean. Subtracting them from the mean
// would result in an arithmetic underflow.
uint256 diff = data[i] - mean;
sum += diff * diff;
}
ans = sum / data.length;
}

Take for example a set of scores in the data array to be [4,3,7,6,4] the mean would be 4.8, in solidity 4. When calculating the variance, inside the for loop when we get to the element 3, we're trying to do a 3-4 which would simply revert.

Impact

The task Id would never get fully finalized due to the continous revert when finalizing the validation in the variance function. If this would be a buyers agent oracle purchase request that request would not be finalized and this would probably be the case for most tasks because the validation scores would be a range of values higher or lower than the mean.

Recommendations

Make use of a ternary operator to check which value is greater between the value in the data arrray and the mean, whichever is greater use that as the value to be subtracted from.

Updates

Lead Judging Commences

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