Dria

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

Calculating `variance()` will fail if the mean is greater than one of the values.

Description

When calculating the Variant of a set of variants, we add the summation of the square root of the difference between each element and the Average then divide them by their number

When Subtracting The element by the Average, we made a Power 2 operation, which makes the value positive even if the result was negative.

The problem is that we are performing the subtraction operation first (Element - Average), and put it in uint256, which will make it revert because of underflow in solidity.

libraries/Statistics.sol#L22

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

This will make calculating variance() always revert if one of the elements is smaller than the average.

This will make finalizeValidation() process revert as it uses stddev() function that uses variance() functions for the scores input

Recommendations

If Element < Avg reverse the order of subtraction

diff --git a/contracts/libraries/Statistics.sol b/contracts/libraries/Statistics.sol
index 8c53643..ac713c9 100644
--- a/contracts/libraries/Statistics.sol
+++ b/contracts/libraries/Statistics.sol
@@ -19,7 +19,7 @@ library Statistics {
mean = avg(data);
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
- uint256 diff = data[i] - mean;
+ 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.