High severity
Weak randomness from block.timestamp or blockhash
Updated 2026-11-10
The EVM has no built-in random number generator, so a contract that needs to pick a winner, assign a trait or shuffle a queue reaches for whatever on-chain value looks unpredictable: block.timestamp, now, or the hash of a recent block from blockhash. None of these is secret. Every value that goes into the block is chosen or seen by the party that produces the block, and all of them are fully known to anyone who simulates the call before sending it. So a “random” draw built from block.timestamp % players.length is a draw the attacker can compute in advance and often bend in their favour.
Vulnerable pattern
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
contract Raffle {
address[] public players;
address public winner;
function enter() external payable {
require(msg.value == 0.01 ether, "fee");
players.push(msg.sender);
}
// BUG: block.timestamp is not a secret, so this is not a random draw.
function draw() external {
uint256 idx = uint256(block.timestamp) % players.length;
winner = players[idx];
}
function claim() external {
require(msg.sender == winner, "not the winner");
payable(msg.sender).transfer(address(this).balance);
}
}The exploit needs no special privilege. Before calling draw(), anyone can read the pending block’s timestamp (or just compute block.timestamp % players.length for the block they are about to land in) and only send the transaction when the result points at their own entry. An attacker can go further and wrap the call: a contract that computes the same index and reverts unless it wins turns the raffle into a near-free roll. draw() only goes through when it wins, and a losing attempt costs just the gas of an early revert (or nothing, if it is sent through a private relay that leaves reverting transactions out). And the party that builds the block decides whether the draw lands in it and in what order, so it can wait for a value that favours it, or leave out a draw that would not. The blockhash variant is no better: blockhash of any block in range is public, and blockhash of the current or a future block, or of one more than 256 blocks back, returns zero, so uint256(blockhash(block.number)) % n is a constant.
The fix
Do not derive randomness from any block value. Get the entropy from a source that is fixed before anyone can see it and that no single participant can predict or grind: a verifiable random function (VRF) with an on-chain callback, or a commit-reveal scheme where participants lock in hashed secrets first and reveal them after entries close. The example below does it in two steps: draw() closes entries and asks a VRF coordinator for randomness, and the winner is picked later, in the callback that delivers the random word. The contract itself reads no block value for the draw.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
// The shape of a VRF coordinator: ask for randomness now, and it calls you
// back in a later transaction with a random word it has proven on chain.
interface IVRFCoordinator {
function requestRandomWords() external returns (uint256 requestId);
}
contract Raffle {
address[] public players;
address public winner;
IVRFCoordinator public immutable coordinator;
uint256 public pendingRequest;
bool public closed;
constructor(IVRFCoordinator _coordinator) { coordinator = _coordinator; }
function enter() external payable {
require(!closed, "closed");
require(msg.value == 0.01 ether, "fee");
players.push(msg.sender);
}
// FIX, step 1: close entries, then ask. Nobody knows the word yet.
function draw() external {
require(!closed && players.length > 0, "not open");
closed = true;
pendingRequest = coordinator.requestRandomWords();
}
// Step 2, a later transaction: only the coordinator delivers the word,
// and the winner is picked here, from a list that can no longer change.
function fulfillRandomWords(uint256 requestId, uint256[] calldata words) external {
require(msg.sender == address(coordinator), "only coordinator");
require(requestId == pendingRequest && winner == address(0), "unexpected");
winner = players[words[0] % players.length];
}
function claim() external {
require(msg.sender == winner, "not the winner");
payable(msg.sender).transfer(address(this).balance);
}
}Two practical cautions when you wire this up. First, close the draw before you ask for randomness, and act on the word in the callback that delivers it. If entries stay open, or the word sits in storage for a later call to use, whoever reads it first can still join or wait until it favours them; Chainlink’s own consumer contract notes recommend carrying out everything a random word decides inside the fulfilment call. With Chainlink VRF you inherit VRFConsumerBaseV2Plus, whose rawFulfillRandomWords rejects any caller but the coordinator before it runs your fulfillRandomWords; the example spells out the same check. That base also lets the consumer’s owner change the coordinator, so the owner has to be trusted not to point it at an address that picks the word; the example keeps the coordinator immutable. Second, a commit-reveal scheme is only as strong as its penalty for not revealing: a participant who dislikes the result and withholds their reveal must forfeit a deposit worth more than the veto could save them, or they can veto any draw they would lose. Both patterns move the decision off the block header: the bug was the source feeding the modulo, not the modulo itself. The examples are kept short: a production raffle also needs a refund path for a request that is never fulfilled (never a re-draw, which would let someone choose between random words) and a payout that a contract wallet can receive.
A note on scope
Slither’s detector flags a modulo (%) whose left operand depends on block.timestamp, now, or the return value of blockhash(). That direction matters: block.timestamp % n is flagged, but n % block.timestamp is not. The detector only follows the left operand, the dividend; a block value used as the divisor still makes the result depend on the block, it is just not a shape this detector looks for. Plain block.number is not treated as a randomness source by this detector, and a modulo with no block-value dependence is left alone. Neither is block.prevrandao (block.difficulty before the merge), the value most post-merge code reaches for: it is the beacon chain’s RANDAO mix, already fixed when the previous block is published, which that block’s proposer can bias by withholding it, and on OP Stack chains such as Base it is copied from an L1 block and stays the same across several L2 blocks. block.prevrandao % n gets no weak-prng finding from Slither or from pactlint, so check it by hand. pactlint keeps a genuine draw at high severity, but it quiets three shapes that usually use a block value and a modulo for something other than randomness: a modulo by a large power of two (uint32(block.timestamp % 2**32), which just narrows a timestamp into a smaller slot), the period-rounding shape t - t % 1 weeks, and x % 2 where the same value is also halved in the function (a bit test inside exponentiation-by-squaring). Those are demoted to informational, which the report leaves out unless you ask for informational results. The rule matches the shape of the code, not its intent, so treat it as a heuristic: a real draw written in one of those shapes (a 16-bit trait taken as uint256(blockhash(block.number - 1)) % 2**16, say) is demoted too, and time arithmetic that is not a draw, such as block.timestamp % 1 days for the time of day, still shows as high and needs a human look.
Scan your contract for this
pactlint flags weak-prng and other recurring DeFi bug classes in Solidity
source or a verified contract on Ethereum or Base. Pay per call in USDC on Base, Polygon, Solana, BNB Chain or Arbitrum with x402,
or on Tempo with MPP, no signup; the first few scans each day are free.
A modulo on block.timestamp, now or blockhash used as randomness is reported by
Slither’s stock weak-prng detector (“Weak PRNG”), rated high impact at medium confidence, which
pactlint surfaces at high severity. It is not downgraded or denied in policy. The one adjustment we add is a
triage rule that demotes the three non-random modulo shapes above (type truncation, period rounding, and the squaring bit test)
to informational (left out of the report unless you ask for informational results). We confirmed this on solc 0.8.19: the raffle above fires the detector at high impact and medium
confidence on uint256(block.timestamp) % players.length; the fixed raffle, which takes its word from the coordinator
callback, has no weak-prng finding; uint32(block.timestamp % 2**32) still fires the raw detector but is the informational truncation
case; and n % block.timestamp does not fire, confirming the left-operand direction. Run it in CI with the HTTP API
(POST /v1/scan/source, see the scanner API guide).
Heuristic and educational, not an audit.