Dria

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

Incorrect Variance Calculation in `Statistics.sol::variance` Function

Summary

The variance function in the Statistics library calculates the variance of an array of non-negative uint256 values, but due to Solidity’s lack of floating-point support, results may be imprecise.

Vulnerability Details

1. The function may return zero variance for non-identical data points. For instance, an input of [1,2,3] yields a variance of 0 due to the integer division rounding error in Solidity.

avg([1,2,3]) = 2
variance = ( (1-2)^2 + (2-2)^2 + (3-2)^2 ) / 3 = 0

avg([1,2,3]) results in 2, and the computed variance is ( (1-2)^2 + (2-2)^2 + (3-2)^2 ) / 3, which approximates to zero in integer division.


2. Solidity's lack of floating-point precision leads to the truncation of calculated variance to the nearest integer. For example, the variance of [1, 2, 3, 5] is theoretically 2.6666 but is truncated to 2.

3. When calculating the difference between data[i] and mean, a potential underflow may occur if data[i] < mean, resulting in an erroneous large number due to uint256 wraparound.

data = [1, 2, 3].
diff = data[0] - mean = 1 - 2 = -1

Impact

This function may produce misleading results

Tools Used

Manual Review

Recommendations

  • Use Absolute Differences:

    • Apply a check to ensure that diff is calculated as diff = data[i] >= mean ? data[i] - mean : mean - data[i]; to avoid potential underflows.

  • Recalculate with Enhanced Precision:

    • Implement a workaround for floating-point precision, such as scaling values before calculations and scaling them down afterward, to approximate decimals.

  • Add Edge Case Checks:

    • Verify that variance values make logical sense, particularly checking for zero variance cases and non-zero data points.

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.