Dria

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

Finalization of request validation will always fail due to underflow bug in function variance in Statistics.sol

Summary

After last validator oracle reports its scores for a given task, finalizeValidation function is called to compute the final score. Statistics lib is used to compute the mean and standard deviation of the scores. Bug lies in function variance. It will iterate through input elements (ie. scores) and for each one calculate its difference from the mean. But it wrongly assumes that every input element is bigger than the mean. By definition of mean, some elements will be smaller than mean and on a first such element TX will revert due to underflow.

Vulnerability Details

This is the variance function containing the bug:

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

Bug is in this specific line:

uint256 diff = data[i] - mean;

It will cause revert due to underflow on the first data[i] element which is lower than the mean. The only case where the revert does not happen is in the case all provided scores are identical, so diff from the mean is 0.

Impact

Task validation cannot be finalized, so buyer agent isn't able to purchase any assets and the round finishes. This happens every round and all sellers listing the assets are losing money since assets can't be bought.

Tools Used

Manual review

Recommendations

Change the implementation of variance to avoid underflow:

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;
+ 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 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.