Skip to content
DoS Audit finding Intermediate

DoS in MergingPool::claimRewards function and potential DoS in RankedBattle::claimNRN function if called after a significant amount of rounds passed

The claimRewards and claimNRN functions loop from the user's last claimed round to the current round, and claimRewards also loops over all winners per round. If many rounds pass, the gas cost can exceed the block gas limit, preventing users from claiming rewards.

ahmedaghadi Follow with btk, 0xKowalski and 48 others

Originally disclosed on Code4rena

Submitted by ahmedaghadi, also found by SpicyMeatball (1, 2), btk, 0xKowalski, ktg (1, 2), 0xDetermination (1, 2), Ryonen, sl1 (1, 2), MrPotatoMagic, klau5 (1, 2, 3), vnavascues, pontifex, Nyxaris, alexzoid, inzinko, grearlake (1, 2), Honour, cu5t0mpeo, evmboi32, Avci, Greed, josephdara, VAD37, DeFiHackLabs, 0xPluto, radev_sw (1, 2), MidgarAudits, KmanOfficial, soliditywala, ladboy233, AlexCzm, jesusrod15, erosjohn, merlinboii, taner2344, Krace, ke1caM (1, 2), BigVeezus, Draiakoo, peanuts (1, 2), McToady (1, 2), Giorgio, 0x13, deadrxsezzz, SovaSlava, almurhasan (1, 2), 0xvj, _eperezok (1, 2), emrekocak, fnanni, pipidu83, y4y, jesjupyter, BARW (1, 2), djxploit, sobieski, ReadyPlayer2 (1, 2), Fitro, 0xAleko, zaevlad, GoSlang, 0xRiO, Cryptor, Kalogerone, t0x1c, nuthan2x, yovchev_yoan, and dvrkzy

The MergingPool::claimRewards function loop through last claimed round ID to the latest round ID ( https://github.com/code-423n4/2024-02-ai-arena/blob/main/src/MergingPool.sol#L139 ):

function claimRewards(
    string[] calldata modelURIs,
    string[] calldata modelTypes,
    uint256[2][] calldata customAttributes
)
    external
{
    uint256 winnersLength;
    uint32 claimIndex = 0;
@->    uint32 lowerBound = numRoundsClaimed[msg.sender];
@->    for (uint32 currentRound = lowerBound; currentRound < roundId; currentRound++) {
        numRoundsClaimed[msg.sender] += 1;
        winnersLength = winnerAddresses[currentRound].length;
        for (uint32 j = 0; j < winnersLength; j++) {
            if (msg.sender == winnerAddresses[currentRound][j]) {
                _fighterFarmInstance.mintFromMergingPool(
                    msg.sender,
                    modelURIs[claimIndex],
                    modelTypes[claimIndex],
                    customAttributes[claimIndex]
                );
                claimIndex += 1;
            }
        }
    }
    if (claimIndex > 0) {
        emit Claimed(msg.sender, claimIndex);
    }
}

Also there’s another nested loop which loops through all the winners each round. Thus, it will become very expensive to claim rewards and eventually leads to block gas limit. Due to which some users may never be able to claim their rewards.

Therefore, If user try to claim their rewards after many rounds has passed then due to the above mentioned loops, it will consume a lot of gas and eventually leads to block gas limit.

Similarly, the RankedBattle::claimNRN function loop through last claimed round ID to the latest round ID ( https://github.com/code-423n4/2024-02-ai-arena/blob/main/src/RankedBattle.sol#L294 ) :

function claimNRN() external {
    require(numRoundsClaimed[msg.sender] < roundId, "Already claimed NRNs for this period");
    uint256 claimableNRN = 0;
    uint256 nrnDistribution;
@->    uint32 lowerBound = numRoundsClaimed[msg.sender];
@->    for (uint32 currentRound = lowerBound; currentRound < roundId; currentRound++) {
        nrnDistribution = getNrnDistribution(currentRound);
        claimableNRN += (
            accumulatedPointsPerAddress[msg.sender][currentRound] * nrnDistribution
        ) / totalAccumulatedPoints[currentRound];
        numRoundsClaimed[msg.sender] += 1;
    }
    if (claimableNRN > 0) {
        amountClaimed[msg.sender] += claimableNRN;
        _neuronInstance.mint(msg.sender, claimableNRN);
        emit Claimed(msg.sender, claimableNRN);
    }
}

Although, it’s relatively difficult to reach the block gas limit in claimNRN function as compared to claimRewards function, but still it’s possible.

Proof of Concept

For claimRewards function, Add the below function in MergingPool.t.sol:

function testClaimRewardsDOS() public {
    address user1 = vm.addr(1);
    address user2 = vm.addr(2);
    address user3 = vm.addr(3);

    _mintFromMergingPool(user1);
    _mintFromMergingPool(user2);
    _mintFromMergingPool(user3);

    uint offset = 35;
    uint totalWin = 9;

    uint256[] memory _winnersGeneral = new uint256[](2);
    _winnersGeneral[0] = 0;
    _winnersGeneral[1] = 1;

    uint256[] memory _winnersUser = new uint256[](2);
    _winnersUser[0] = 0;
    _winnersUser[1] = 2;
    for (uint i = 0; i < offset * totalWin; i++) {
        if (i % offset == 0) {
            _mergingPoolContract.pickWinner(_winnersUser);
        } else {
            _mergingPoolContract.pickWinner(_winnersGeneral);
        }
    }

    string[] memory _modelURIs = new string[](totalWin);
    string[] memory _modelTypes = new string[](totalWin);
    uint256[2][] memory _customAttributes = new uint256[2][](totalWin);
    for (uint i = 0; i < totalWin; i++) {
        _modelURIs[
            i
        ] = "ipfs://bafybeiaatcgqvzvz3wrjiqmz2ivcu2c5sqxgipv5w2hzy4pdlw7hfox42m";
        _modelTypes[i] = "original";
        _customAttributes[i][0] = uint256(1);
        _customAttributes[i][1] = uint256(80);
    }
    vm.prank(user3);
    uint gasBefore = gasleft();
    _mergingPoolContract.claimRewards(
        _modelURIs,
        _modelTypes,
        _customAttributes
    );
    uint gasAfter = gasleft();
    uint gasDiff = gasBefore - gasAfter;
    emit log_uint(gasDiff);
    uint256 numRewards = _mergingPoolContract.getUnclaimedRewards(user3);
    assertEq(numRewards, 0);
    assertGt(gasDiff, 4_000_000);
}

You can run the test by:

forge test --mt testClaimRewardsDOS -vv

Here I had considered 3 users, user1, user2, and user3. After each offset rounds, I picked user3 as a winner. There were total of 315 ( offset * totalWin ) rounds passed and user3 won in 9 of them. Then I tried to claim rewards for user3 and it consumed more than 4M gas.

Also the more the round in which user3 has won, the more gas it will consume. Even if offset is 1 and totalWin is 9 ( i.e total of 9 rounds out of which user3 won in 9 of them ), it will consume more than 3.4M gas.

Also, we’ve considered only 2 winners per round, as the number of winners increases, the gas consumption will also increase due to the nested loop which loops through all the winners each round.

So if any user claim their rewards after many rounds has passed or if they have won in many rounds, it will consume a lot of gas and eventually leads to block gas limit.

For claimNRN function, Add the below function in RankedBattle.t.sol:

function testClaimNRNDoS() public {
    _neuronContract.addSpender(address(_gameItemsContract));
    _gameItemsContract.instantiateNeuronContract(address(_neuronContract));
    _gameItemsContract.createGameItem(
        "Battery",
        "https://ipfs.io/ipfs/",
        true,
        true,
        10_000,
        1 * 10 ** 18,
        type(uint16).max
    );
    _gameItemsContract.setAllowedBurningAddresses(
        address(_voltageManagerContract)
    );

    address staker = vm.addr(3);
    _mintFromMergingPool(staker);
    vm.prank(_treasuryAddress);
    _neuronContract.transfer(staker, 400_000 * 10 ** 18);
    vm.prank(staker);
    _rankedBattleContract.stakeNRN(30_000 * 10 ** 18, 0);
    assertEq(_rankedBattleContract.amountStaked(0), 30_000 * 10 ** 18);

    address claimee = vm.addr(4);
    _mintFromMergingPool(claimee);
    vm.prank(_treasuryAddress);
    _neuronContract.transfer(claimee, 400_000 * 10 ** 18);
    vm.prank(claimee);
    _rankedBattleContract.stakeNRN(40_000 * 10 ** 18, 1);
    assertEq(_rankedBattleContract.amountStaked(1), 40_000 * 10 ** 18);

    uint offset = 35;
    uint totalWin = 9;
    for (uint i = 0; i < offset * totalWin; i++) {
        // 0 win
        // 1 tie
        // 2 loss
        if (i % offset == 0) {
            uint256 currentVoltage = _voltageManagerContract.ownerVoltage(
                claimee
            );
            if (currentVoltage < 100) {
                vm.prank(claimee);
                _gameItemsContract.mint(0, 1); //paying 1 $NRN for 1 batteries
                vm.prank(claimee);
                _voltageManagerContract.useVoltageBattery();
            }

            vm.prank(address(_GAME_SERVER_ADDRESS));
            _rankedBattleContract.updateBattleRecord(1, 50, 0, 1500, true);
        } else {
            uint256 currentVoltage = _voltageManagerContract.ownerVoltage(
                staker
            );
            if (currentVoltage < 100) {
                vm.prank(staker);
                _gameItemsContract.mint(0, 1); //paying 1 $NRN for 1 batteries
                vm.prank(staker);
                _voltageManagerContract.useVoltageBattery();
            }

            vm.prank(address(_GAME_SERVER_ADDRESS));
            _rankedBattleContract.updateBattleRecord(0, 50, 0, 1500, true);
        }
        _rankedBattleContract.setNewRound();
    }

    uint256 gasBefore = gasleft();
    vm.prank(claimee);
    _rankedBattleContract.claimNRN();
    uint256 gasAfter = gasleft();
    uint256 gasDiff = gasBefore - gasAfter;
    emit log_uint(gasDiff);
    assertGt(gasDiff, 1_000_000);
}

You can run the test by:

forge test --mt testClaimNRNDoS -vv

In the case of claimNRN function, it consumed more than 1M gas which is relatively less as compared to claimRewards function. But still it has potential to reach block gas limit.

Even for the users for whom these both functions doesn’t reach block gas limit, it can be very expensive and difficult for them to claim their rewards if some rounds has passed.

Tools Used

Foundry

Recommended Mitigation Steps

It can be fixed by adding a parameter for the number of rounds to consider.

For claimRewards function, so the changes would look like:

function claimRewards(
    string[] calldata modelURIs,
    string[] calldata modelTypes,
-    uint256[2][] calldata customAttributes
+    uint256[2][] calldata customAttributes,
+    uint32 totalRoundsToConsider
)
    external
{
    uint256 winnersLength;
    uint32 claimIndex = 0;
    uint32 lowerBound = numRoundsClaimed[msg.sender];
+    require(lowerBound + totalRoundsToConsider < roundId, "MergingPool: totalRoundsToConsider exceeds the limit");
-    for (uint32 currentRound = lowerBound; currentRound < roundId; currentRound++) {
+    for (uint32 currentRound = lowerBound; currentRound < lowerBound + totalRoundsToConsider; currentRound++) {
        numRoundsClaimed[msg.sender] += 1;
        winnersLength = winnerAddresses[currentRound].length;
        for (uint32 j = 0; j < winnersLength; j++) {
            if (msg.sender == winnerAddresses[currentRound][j]) {
                _fighterFarmInstance.mintFromMergingPool(
                    msg.sender,
                    modelURIs[claimIndex],
                    modelTypes[claimIndex],
                    customAttributes[claimIndex]
                );
                claimIndex += 1;
            }
        }
    }
    if (claimIndex > 0) {
        emit Claimed(msg.sender, claimIndex);
    }
}

For claimNRN function, so the changes would look like:

- function claimNRN() external {
+ function claimNRN(uint32 totalRoundsToConsider) external {
    require(numRoundsClaimed[msg.sender] < roundId, "Already claimed NRNs for this period");
    uint256 claimableNRN = 0;
    uint256 nrnDistribution;
    uint32 lowerBound = numRoundsClaimed[msg.sender];
+    require(lowerBound + totalRoundsToConsider < roundId, "RankedBattle: totalRoundsToConsider exceeds the limit");
-    for (uint32 currentRound = lowerBound; currentRound < roundId; currentRound++) {
+    for (uint32 currentRound = lowerBound; currentRound < lowerBound + totalRoundsToConsider; currentRound++) {
        nrnDistribution = getNrnDistribution(currentRound);
        claimableNRN += (
            accumulatedPointsPerAddress[msg.sender][currentRound] * nrnDistribution
        ) / totalAccumulatedPoints[currentRound];
        numRoundsClaimed[msg.sender] += 1;
    }
    if (claimableNRN > 0) {
        amountClaimed[msg.sender] += claimableNRN;
        _neuronInstance.mint(msg.sender, claimableNRN);
        emit Claimed(msg.sender, claimableNRN);
    }
}

brandinho (AI Arena) confirmed

AI Arena mitigated:

https://github.com/ArenaX-Labs/2024-02-ai-arena-mitigation/pull/12

Status: Mitigation confirmed. Full details in reports from niser93, fnanni, and d3e4.


The original report as published on Code4rena, by ahmedaghadi. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the unbounded loop over all unclaimed rounds, plus a nested loop over all winners per round, causes gas usage to grow with the number of rounds and winners.

What the attacker needed

Many rounds pass since last claim; user has won in multiple rounds

The fix

The functions should be changed to accept a parameter limiting the number of rounds to process per call.

How it was found

  1. Set up three users and mint fighters for them.
  2. Simulate 315 rounds, picking user3 as a winner every 35 rounds.
  3. Call claimRewards for user3 and measure gas used.
  4. Observe gas usage exceeds 4 million.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

These functions let users collect rewards for many past rounds. They use a loop that goes through every round since the user last claimed. If a user waits a long time, the loop becomes very long and the transaction costs too much gas, so it fails.

What is DoS?

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.

More by ahmedaghadi

View all

1 more disclosed report, best first.

More from AI Arena

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.