code-423n4 / 2024-07-traitforge-findings

0 stars 0 forks source link

Precision Loss in Entropy Calculation #358

Closed howlbot-integration[bot] closed 1 month ago

howlbot-integration[bot] commented 1 month ago

Lines of code

https://github.com/code-423n4/2024-07-traitforge/blob/279b2887e3d38bc219a05d332cbcb0655b2dc644/contracts/EntropyGenerator/EntropyGenerator.sol#L181

Vulnerability details

Description

The EntropyGenerator contract's entropy calculation function is prone to precision loss due to its reliance on integer division followed by a modulo operation. This method may cause biased results due to truncation errors, particularly when the position is large.

The code in question is:

uint256 entropy = (slotValue / (10 ** (72 - position))) % 1000000;

Here, the integer division may result in a significant loss of precision, especially when position is large. This precision loss can skew the results of the modulo operation, leading to biased entropy values.

Impact

This issue can lead to biased entropy values, affecting the uniformity of NFT trait generation. Potential impacts include:

1.Unfair Advantages: Certain NFTs may receive preferential traits due to biased entropy. 2.Reduced Randomness: The randomness and uniqueness of NFTs could be compromised. 3.Exploitable Patterns: Predictable patterns in NFT traits might be exploited by players. The problem is particularly concerning because entropy is used to determine important parameters like NukeFactor, forgePotential, and role assignments (Forger or Merger).

Proof of Concept

Assuming slotValue is a large number close to 2^256 - 1, and position is 0:

uint256 slotValue = 2**256 - 1;
uint256 position = 0;

uint256 entropy = (slotValue / (10 ** 72)) % 1000000;

In this scenario, the division slotValue / (10 ** 72) yields a smaller number due to truncation. The following modulo operation will then produce results biased toward smaller values, failing to evenly distribute across the range 0 to 999999.

Tools Used

Recommended Mitigation Steps

  1. Adopt Bitwise Operations for Entropy Extraction:
    uint256 entropy = (slotValue >> (4 * (18 - position))) & 0xFFFFFF;

    This approach uses bitwise operations to extract 24 bits (6 hex digits) from slotValue, avoiding precision loss associated with division.

2.Conduct Extensive Testing: Implement comprehensive tests to verify that entropy values are uniformly distributed across the entire possible range. This ensures that the entropy generation is fair and unbiased.

Assessed type

Math

c4-judge commented 1 month ago

koolexcrypto changed the severity to QA (Quality Assurance)

c4-judge commented 1 month ago

koolexcrypto marked the issue as grade-c