"Provably fair" is a phrase that appears on a lot of blockchain projects, and it is often used more loosely than it should be. Fairness in a random draw needs two things: the outcome must be unpredictable to anyone who could profit from knowing it, and anyone must be able to check afterwards that the rules were followed. Blockchains help with the second. The first is surprisingly hard, because a blockchain is a deterministic, public machine.
This post explains why the usual shortcuts fail, builds a small commit-reveal raffle in Solidity, and is deliberately honest about what that design still cannot protect against. It is aimed at developers building giveaways, community raffles and similar systems. It is a technical article, not an invitation to build or play gambling products, which are regulated differently in each country.
Why block.timestamp and friends are not random
Every node must be able to re-execute your transaction and get the same result, so a contract can't use a source of true randomness. What it can see is block data, and that data is known to, or influenced by, the people producing blocks. The Solidity documentation says exactly this: everything in a contract is publicly visible, and using random numbers in contracts is tricky if you don't want block builders to be able to cheat.
block.timestampandblockhash. Predictable or influenceable by whoever builds the block, and visible to any contract called in the same transaction.block.prevrandao. Since Ethereum's move to proof of stake, the oldDIFFICULTYopcode returns the beacon chain's RANDAO value (EIP-4399). It's better than the old sources, but the EIP itself discusses its limits: every proposer has one bit of influence per slot, because they can choose not to propose a block, and a proposer can also censor a transaction so that it lands in a block whose value they already know. For low-value outcomes that may be acceptable; for anything valuable, it is a risk.- Hashing public data yourself. Hashing
msg.senderand a timestamp looks random but is fully predictable to anyone who can simulate the call. An attacker contract can check the outcome first and only proceed when it wins.
What "provably fair" should actually mean
I'd use three properties as a test of any randomness scheme:
- Unpredictable before the draw. Nobody with an interest, including the operator, can know the result in advance.
- Unbiasable. Nobody can nudge the outcome by choosing when to act, what to enter or whether to take part.
- Verifiable after the draw. Anyone can recompute the winner from public data.
Commit-reveal gives you the third, helps with the first against some attackers, and partly fails on the second. Let's see exactly where.
Commit-reveal in one paragraph
Before entries open, the operator picks a secret, hashes it and publishes only the hash: that's the commitment. Entries then close. After that, the operator reveals the secret. The contract checks that it hashes to the commitment, and uses the secret together with the final list of entrants to pick the winner. Because the commitment was fixed before anyone entered, the operator can't choose a secret after seeing the entrants.
The contract
CommitRevealRaffle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Teaching example: an operator commits to a secret BEFORE entries open and reveals it after they close.
/// It stops the operator choosing the secret after seeing who entered. It does NOT stop the operator from
/// refusing to reveal, or from adding their own entries, see the post for the limits.
contract CommitRevealRaffle {
address public immutable operator;
bytes32 public immutable commitment;
uint64 public immutable entryDeadline;
uint64 public immutable revealDeadline;
address[] public entrants;
address public winner;
bool public settled;
bool public cancelled;
error TooLate();
error TooEarly();
error NotOperator();
error BadSecret();
error NoEntrants();
error NotCancellable();
constructor(bytes32 commitment_, uint64 entryWindow, uint64 revealWindow) {
operator = msg.sender;
commitment = commitment_;
entryDeadline = uint64(block.timestamp) + entryWindow;
revealDeadline = entryDeadline + revealWindow;
}
function enter() external {
if (block.timestamp >= entryDeadline) revert TooLate();
entrants.push(msg.sender);
}
function entrantCount() external view returns (uint256) {
return entrants.length;
}
function reveal(bytes32 secret) external {
if (msg.sender != operator) revert NotOperator();
if (block.timestamp < entryDeadline) revert TooEarly();
if (block.timestamp >= revealDeadline) revert TooLate();
if (keccak256(abi.encodePacked(secret)) != commitment) revert BadSecret();
if (entrants.length == 0) revert NoEntrants();
winner = entrants[uint256(keccak256(abi.encodePacked(secret, entrants.length))) % entrants.length];
settled = true;
}
/// If the operator never reveals, anyone can cancel after the deadline so nobody is stuck waiting.
function cancel() external {
if (settled || block.timestamp < revealDeadline) revert NotCancellable();
cancelled = true;
}
}
The constructor takes the commitment and two time windows. enter() works until the entry deadline. reveal() can only be called by the operator, only after entries close and before the reveal deadline, and only with a secret whose hash equals the commitment. The winner is entrants[hash(secret, entrantCount) % entrantCount]. If the operator never reveals, cancel() lets anyone close the raffle after the deadline so nobody is waiting forever.
The tests
CommitRevealRaffle.ts
import { expect } from "chai";
import { network } from "hardhat";
const { ethers, networkHelpers } = await network.create();
const SECRET = ethers.id("operator-secret-chosen-before-entries-open"); // 32-byte value
const COMMITMENT = ethers.keccak256(SECRET);
async function setup() {
const [operator, a, b, c] = await ethers.getSigners();
const raffle = await ethers.deployContract("CommitRevealRaffle", [COMMITMENT, 3600n, 3600n]);
return { raffle, operator, a, b, c };
}
describe("CommitRevealRaffle", function () {
it("picks one of the entrants after the correct secret is revealed", async function () {
const { raffle, a, b, c } = await setup();
for (const s of [a, b, c]) await raffle.connect(s).enter();
await networkHelpers.time.increase(3600);
await raffle.reveal(SECRET);
expect([a.address, b.address, c.address]).to.include(await raffle.winner());
expect(await raffle.settled()).to.equal(true);
});
it("is checkable by anyone: the same inputs always give the same winner", async function () {
const { raffle, a, b, c } = await setup();
for (const s of [a, b, c]) await raffle.connect(s).enter();
await networkHelpers.time.increase(3600);
await raffle.reveal(SECRET);
const idx = BigInt(ethers.solidityPackedKeccak256(["bytes32", "uint256"], [SECRET, 3n])) % 3n;
expect(await raffle.entrants(idx)).to.equal(await raffle.winner());
});
it("rejects a secret that does not match the commitment", async function () {
const { raffle, a } = await setup();
await raffle.connect(a).enter();
await networkHelpers.time.increase(3600);
await expect(raffle.reveal(ethers.id("another secret"))).to.be.revertedWithCustomError(raffle, "BadSecret");
});
it("closes entries on time and blocks early reveals", async function () {
const { raffle, a } = await setup();
await raffle.connect(a).enter();
await expect(raffle.reveal(SECRET)).to.be.revertedWithCustomError(raffle, "TooEarly");
await networkHelpers.time.increase(3600);
await expect(raffle.connect(a).enter()).to.be.revertedWithCustomError(raffle, "TooLate");
});
it("can be cancelled if the operator never reveals", async function () {
const { raffle, a } = await setup();
await raffle.connect(a).enter();
await expect(raffle.cancel()).to.be.revertedWithCustomError(raffle, "NotCancellable");
await networkHelpers.time.increase(7200);
await raffle.cancel();
expect(await raffle.cancelled()).to.equal(true);
});
});
All five pass. Two are worth pointing out. The "checkable by anyone" test recomputes the winner outside the contract from the secret and the entrant count, which is the verification step a skeptical participant would do. The "rejects a secret that does not match" test shows the operator can't swap in a different secret after seeing the entries.
What commit-reveal does not fix
This is the part that "provably fair" marketing tends to skip. In this contract:
- The operator can refuse to reveal. If the operator doesn't like the winner they would get, they can simply not call
reveal. The cancel function stops participants being stuck, but the operator has chosen the outcome "no draw". This is a "last-revealer" problem, and the usual mitigation is a deposit that the operator forfeits. - The operator knows the winner in advance of the last entries. They know the secret, so once they see the entrant list they can compute who would win. Because the final result depends on the number of entrants, an operator who adds their own entries at the very end can try different counts, using several addresses, until a favourable one wins. Commit-reveal stops them changing the secret but not manipulating the entrant list.
- Sybil entries. One person can enter with many addresses. If the prize is worth more than the cost of entering, assume they will. You need entry costs, identity checks or an allowlist, depending on your use case; the Merkle allowlist post shows one approach.
- Timing at the boundary. Entry deadlines use
block.timestamp, which block producers can nudge slightly. A few seconds usually doesn't matter, but don't depend on it. - The operator may lose the secret, or leak it early. A leaked secret before the entry deadline lets someone game their entry position.
Stronger designs, in outline
- Multi-party commit-reveal. Every participant commits to a secret and reveals it; the result mixes all of them. One honest participant who reveals is enough to make the outcome unpredictable, but you now have to handle people who don't reveal.
- Verifiable randomness services. Oracle networks provide random values with a cryptographic proof that the contract verifies on-chain. These exist and are widely used, but I haven't tested one for this post, and they carry their own trust assumptions, fees and integration details. Read each provider's current documentation before you decide.
- Delay functions and threshold schemes. Research-grade options that remove the last-revealer problem. They're more complex than most projects need.
The right choice depends on what's at stake. A free community raffle with a small prize can live with a simple scheme. If the prize has real value, use a design where no single party can bias the result, and get it audited; the audit preparation checklist is a good starting point.
A checklist for any randomness feature
- Write down who could benefit from knowing or biasing the result, and what each of them controls.
- Never derive randomness from block data alone for anything valuable.
- Make the winner computable by anyone from public inputs after the draw.
- Plan for the operator not showing up: deadlines, cancellation, deposits.
- Assume many addresses per person and design the entry rules around that.
- Test the attacks, not just the happy path: a wrong secret, an early reveal, a late entry.
- Check the law where you and your participants live before any prize or money is involved.
"Provably fair" is a claim about a specific design under specific assumptions. When you see it, ask: fair against whom, and what happens if they don't cooperate?
Building a draw, giveaway or on-chain game mechanic?
I design and test the contract side with the attack cases written first. If you want a technical review of your randomness approach, get in touch.
See services Get in touchWhat I ran this against
- Hardhat 3.22.0 (Mocha + ethers template), @openzeppelin/contracts 5.6.1, ethers 6.17.0, solc 0.8.34, Node.js 24.22.1, run on 17 November 2026 on Hardhat's in-process simulated network. Five tests pass: a winner is picked after the correct reveal, the result is reproducible by anyone from public inputs, a wrong secret is rejected, entries close on time and early reveals are blocked, and cancellation works when the operator never reveals.
- I did not test any third-party verifiable-randomness service. Where I mention one, it is general background to check against its own documentation.
- Nothing was deployed to a testnet or mainnet, and the contracts are teaching examples that have not been audited. This is a teaching example for raffles and giveaways, with known weaknesses listed below. It is not a gambling product, and the post does not recommend or promote gambling. Laws on raffles and games of chance vary by country, so take local advice before running anything that involves money or prizes.
Sources checked
- Solidity documentation, Security Considerations, "Private Information and Randomness": everything in a contract is publicly visible, and using random numbers in contracts is tricky if you don't want block builders to be able to cheat: docs.soliditylang.org.
- EIP-4399 (
PREVRANDAO), Security Considerations: each block proposer has 1 bit of influence per slot, and a proposer can censor a transaction to force it into a block whose RANDAO value they know in advance: eips.ethereum.org/EIPS/eip-4399.