Dria

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

[M-1] variance::Statistics.sol diff should be initialized as int256 rather than uint256 as data[i]-mean can be also be negative

Description

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++) {
//@audit
uint256 diff = data[i] - mean;
sum += diff * diff;
}
ans = sum / data.length;
}

I assume diff is deviation ( deviations can either be
positive or negative)
so initializing diff as uint256 is a wrong thing to do.

Impact: Revert when diffis negative, which is not supposed to be. Logic error

Recommended mitigation

diff and sum should be initialized as int256 and then ans can be finally wrapped as uint256

function variance(uint256[] memory data) internal pure returns (uint256 ans, uint256 mean) {
mean = avg(data);
int256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
//@q i assume `diff` is deviation, well deviations can either be
//positive or negative
//so initializingt diff as uint256 is a wrong thing to do.
int256 diff = data[i] - mean;
sum += diff * diff;
}
ans = uint256(sum / data.length);
}
Updates

Lead Judging Commences

inallhonesty Lead Judge about 1 year 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.