Dria

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

M-01 Variance Calculation Revert Due to Integer Underflow

Summary

A vulnerability has been identified in the Statistics contract where the variance calculation can revert due to integer underflow when the mean is greater than any individual data point.

Vulnerability Details

In Statistics.sol:22, the variance calculation function contains a mathematical operation that can cause an underflow. The relevant code section shows:

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; // This can underflow
sum += diff * diff;
}
ans = sum / data.length;
}

The vulnerability exists because:

  1. The calculation uses unsigned integers (uint256)

  2. When mean is larger than data[i], subtraction will underflow

  3. No check exists to handle cases where mean > individual data points

  4. The current implementation assumes all data points are greater than or equal to the mean

Example of failure:

// Given data points: [1, 1, 10]
// Mean = (1 + 1 + 10) / 3 = 4
// First iteration: 1 - 4 = underflow error

Impact

  • Function reverts for valid statistical calculations

  • Unusable for datasets where mean exceeds any data point

  • Causes the purchase score validation logic to fail if any given score is less than the mean of all the scores

Tools Used

Manual Review

Recommendations

To address this vulnerability, implement the following measures:

  1. Use Absolute Difference

    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++) {
    // Calculate absolute difference to prevent underflow
    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 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.