Puppy Raffle

AI First Flight #1
Beginner FriendlyFoundrySolidityNFT
EXP
View results
Submission Details
Severity: low
Valid

# [L-1] getActivePlayerIndex returns ambiguous result for index 0 and creates DoS risk

Summary

The getActivePlayerIndex function returns 0 both when a player is at the first index of the array and when a player does not exist in the raffle. Additionally, the function iterates through the entire players array, creating a potential Denial of Service (DoS) vector as the number of players grows.

Vulnerability Details

The function contains two distinct issues:

Ambiguous Return Value

The function iterates through the players array to find a match. If the player is at index 0, it returns 0. However, if the loop finishes without finding the player, it also returns 0 by default.

// Returns 0 if player is at index 0
if (players[i] == player) { return i; }
...
// Also returns 0 if player is NOT found
return 0;

This makes it impossible for external callers (contracts or frontends) to distinguish between "Player is the first entrant" and "Player is not in the raffle."

O(N) Complexity (DoS Risk)

The function uses a for loop to iterate over players.length. As the number of participants increases, the gas cost to call this function on-chain increases linearly. If the array becomes sufficiently large, calling this function on-chain may exceed the block gas limit, causing transactions to revert.

Impact

  • Logic Errors: Frontends or external integrations may incorrectly assume a user is the first player (index 0) when they are actually not in the raffle at all. While refund checks msg.sender, this ambiguity causes poor user experience and potential integration bugs.

  • Gas Waste: Users attempting to interact with the contract based on this incorrect index may send transactions that revert, wasting gas.

Proof of Concept

The following test demonstrates that getActivePlayerIndex returns 0 for a non-existent player, indistinguishable from a player at index 0.

Click to view Foundry Test
function test_GetActivePlayerIndexAmbiguity() public {
address playerOne = address(1);
address nonExistentPlayer = address(2);
// 1. One player enters (index 0)
address[] memory players = new address[](1);
players[0] = playerOne;
puppyRaffle.enterRaffle{value: entranceFee}(players);
// 2. Check index of Player One (Should be 0)
uint256 indexOne = puppyRaffle.getActivePlayerIndex(playerOne);
// 3. Check index of Non-Existent Player (Should NOT be 0, but is)
uint256 indexNonExistent = puppyRaffle.getActivePlayerIndex(nonExistentPlayer);
console.log("Player One Index:", indexOne);
console.log("Non-Existent Player Index:", indexNonExistent);
// Assertion proves the ambiguity
assertEq(indexOne, indexNonExistent);
}

Recommended Mitigation

  1. Fix the Ambiguity: Return a int256 where -1 represents "not found," or use a struct/tuple to be explicit.

function getActivePlayerIndex(address player) external view returns (bool exists, uint256 index) {
for (uint256 i = 0; i < players.length; i++) {
if (players[i] == player) {
return (true, i);
}
}
return (false, 0);
}
  1. Fix the DoS Risk: To avoid the loop entirely, use a mapping to track player indices in time.

mapping(address => uint256) public playerToIndex;
function enterRaffle(address[] memory newPlayers) public payable {
require(
msg.value == entranceFee * newPlayers.length,
"PuppyRaffle: Must send enough to enter raffle"
);
for (uint256 i = 0; i < newPlayers.length; i++) {
players.push(newPlayers[i]);
// Update the mapping when they join
playerToIndex[newPlayers[i]] = players.length - 1;
}
// checks for duplicate players
}
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge 2 days ago
Submission Judgement Published
Validated
Assigned finding tags:

[L-01] Ambiguous index returned from PuppyRaffle::getActivePlayerIndex(address), leading to possible refund failures

## Description The `PuppyRaffle::getActivePlayerIndex(address)` returns `0` when the index of this player's address is not found, which is the same as if the player would have been found in the first element in the array. This can trick calling logic to think the address was found and then attempt to execute a `PuppyRaffle::refund(uint256)`. ## Vulnerability Details The `PuppyRaffle::refund()` function requires the index of the player's address to preform the requested refund. ```solidity /// @param playerIndex the index of the player to refund. You can find it externally by calling `getActivePlayerIndex` function refund(uint256 playerIndex) public; ``` In order to have this index, `PuppyRaffle::getActivePlayerIndex(address)` must be used to learn the correct value. ```solidity /// @notice a way to get the index in the array /// @param player the address of a player in the raffle /// @return the index of the player in the array, if they are not active, it returns 0 function getActivePlayerIndex(address player) external view returns (int256) { // find the index... // if not found, then... return 0; } ``` The logic in this function returns `0` as the default, which is as stated in the `@return` NatSpec. However, this can create an issue when the calling logic checks the value and naturally assumes `0` is a valid index that points to the first element in the array. When the players array has at two or more players, calling `PuppyRaffle::refund()` with the incorrect index will result in a normal revert with the message "PuppyRaffle: Only the player can refund", which is fine and obviously expected. On the other hand, in the event a user attempts to perform a `PuppyRaffle::refund()` before a player has been added the EvmError will likely cause an outrageously large gas fee to be charged to the user. This test case can demonstrate the issue: ```solidity function testRefundWhenIndexIsOutOfBounds() public { int256 playerIndex = puppyRaffle.getActivePlayerIndex(playerOne); vm.prank(playerOne); puppyRaffle.refund(uint256(playerIndex)); } ``` The results of running this one test show about 9 ETH in gas: ```text Running 1 test for test/PuppyRaffleTest.t.sol:PuppyRaffleTest [FAIL. Reason: EvmError: Revert] testRefundWhenIndexIsOutOfBounds() (gas: 9079256848778899449) Test result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 914.01µs ``` Additionally, in the very unlikely event that the first player to have entered attempts to preform a `PuppyRaffle::refund()` for another user who has not already entered the raffle, they will unwittingly refund their own entry. A scenario whereby this might happen would be if `playerOne` entered the raffle for themselves and 10 friends. Thinking that `nonPlayerEleven` had been included in the original list and has subsequently requested a `PuppyRaffle::refund()`. Accommodating the request, `playerOne` gets the index for `nonPlayerEleven`. Since the address does not exist as a player, `0` is returned to `playerOne` who then calls `PuppyRaffle::refund()`, thereby refunding their own entry. ## Impact 1. Exorbitantly high gas fees charged to user who might inadvertently request a refund before players have entered the raffle. 2. Inadvertent refunds given based in incorrect `playerIndex`. ## Recommendations 1. Ideally, the whole process can be simplified. Since only the `msg.sender` can request a refund for themselves, there is no reason why `PuppyRaffle::refund()` cannot do the entire process in one call. Consider refactoring and implementing the `PuppyRaffle::refund()` function in this manner: ```solidity /// @dev This function will allow there to be blank spots in the array function refund() public { require(_isActivePlayer(), "PuppyRaffle: Player is not active"); address playerAddress = msg.sender; payable(msg.sender).sendValue(entranceFee); for (uint256 playerIndex = 0; playerIndex < players.length; ++playerIndex) { if (players[playerIndex] == playerAddress) { players[playerIndex] = address(0); } } delete existingAddress[playerAddress]; emit RaffleRefunded(playerAddress); } ``` Which happens to take advantage of the existing and currently unused `PuppyRaffle::_isActivePlayer()` and eliminates the need for the index altogether. 2. Alternatively, if the existing process is necessary for the business case, then consider refactoring the `PuppyRaffle::getActivePlayerIndex(address)` function to return something other than a `uint` that could be mistaken for a valid array index. ```diff + int256 public constant INDEX_NOT_FOUND = -1; + function getActivePlayerIndex(address player) external view returns (int256) { - function getActivePlayerIndex(address player) external view returns (uint256) { for (uint256 i = 0; i < players.length; i++) { if (players[i] == player) { return int256(i); } } - return 0; + return INDEX_NOT_FOUND; } function refund(uint256 playerIndex) public { + require(playerIndex < players.length, "PuppyRaffle: No player for index"); ```

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!