Dria

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

Preventing underflow in variance and standard deviation calculations with absolute difference handling

Summary

The variance and stddev functions in the Statistics library risk reverting due to an underflow error when calculating differences between array elements and the mean. This occurs because the diff calculation does not account for cases where an element is less than the mean, causing issues when using unsigned integers. Implementing absolute difference handling prevents these reverts, ensuring smooth execution of both functions.

Vulnerability Details

In the variance function, the line uint256 diff = data[i] - mean assumes data[i] is always greater than or equal to mean, which may not be true. When data[i] < mean, the subtraction causes an underflow, reverting the transaction. This issue also affects the stddev function, as it relies on variance for its calculations. Since uint256 types cannot represent negative values, using absolute values is necessary to avoid this underflow.

https://github.com/Cyfrin/2024-10-swan-dria/blob/c8686b199daadcef3161980022e12b66a5304f8e/contracts/libraries/Statistics.sol#L22

In

https://github.com/Cyfrin/2024-10-swan-dria/blob/c8686b199daadcef3161980022e12b66a5304f8e/contracts/llm/LLMOracleCoordinator.sol#L335

https://github.com/Cyfrin/2024-10-swan-dria/blob/c8686b199daadcef3161980022e12b66a5304f8e/contracts/llm/LLMOracleCoordinator.sol#L365

stddev function is used.

Impact

  • Reverted Transactions: Without the fix, both variance and stddev will revert if any data point is less than the mean, leading to unusable functions in this library.

  • Poor User Experience: Developers and users may experience unexpected failures when calling these functions, potentially leading to confusion and disrupted contract logic.

Tools Used

Recommendations

To prevent the underflow error, update the variance function to calculate the absolute difference between data[i] and mean. Here is the revised function:

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];
}
ans = sum / data.length;
}

This change ensures variance and, by extension, stddev can handle any valid uint256 inputs without risking underflow, providing a robust and predictable experience.

Updates

Lead Judging Commences

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