TwentyOne

First Flight #29
Beginner FriendlyGameFiFoundrySolidity
100 EXP
View results
Submission Details
Severity: low
Valid

Bad logic in `playersHand` function

Summary

The goal of the function playersHand in the provided code is to calculate the total value of the cards in a player's hand.

In Blackjack, the value of the cards ranges from 1 to 10, with Aces being uniquely versatile as they can be valued at either 1 or 11, depending on what is more beneficial for the hand. However, in this particular context, the card values are starting from 0, which deviates from the traditional rules of Blackjack.

Vulnerability Details

Wrong value for cards in the if statement:

uint256 cardValue = playersDeck[player].playersCards[i] % 13;
if (cardValue == 0 || cardValue >= 10) {
playerTotal += 10;
} else {
playerTotal += cardValue;
}

In the provided code, there is an assumption that a card value can be 0. However, this is not true in Blackjack. The lowest value a card can have is actually 1, which is the value of an Ace. In Blackjack, an Ace can be worth either 1 or 11, depending on which value is more beneficial for the hand. Unfortunately, the current logic does not account for this special handling of Aces.

To address this, the code should be adjusted to ensure that the value of an Ace is correctly calculated as either 1 or 11, based on the current total value of the hand. Additionally, the card value calculation should avoid any value of 0, as it is not applicable in Blackjack.

Impact

The most immediate effect is that the program will produce incorrect results, as it will not perform as intended. For the Blackjack function, incorrect card value calculations lead to erroneous game outcomes.

Tools Used

manual review

Recommendations

Please fix function with this example:

function playersHand(address player) public view returns (uint256) {
uint256 playerTotal = 0;
uint256 aceCount = 0;
for (uint256 i = 0; i < playersDeck[player].playersCards.length; i++) {
uint256 cardValue = (playersDeck[player].playersCards[i] % 13) + 1;
if (cardValue == 1) {
// @audit Ace can be worth 1 or 11
aceCount += 1;
playerTotal += 11; // Initially count Ace as 11
} else if (cardValue >= 10) {
// @audit Face cards (Jack, Queen, King) are worth 10
playerTotal += 10;
} else {
// @audit Number cards are worth their face value
playerTotal += cardValue;
}
}
// @audit Adjust for Aces if total value exceeds 21
while (playerTotal > 21 && aceCount > 0) {
playerTotal -= 10; // Convert one Ace from 11 to 1
aceCount -= 1;
}
return playerTotal;
}
Updates

Lead Judging Commences

inallhonesty Lead Judge 11 months ago
Submission Judgement Published
Validated
Assigned finding tags:

Wrong ace value

Support

FAQs

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