Back to Blog
Smart Contracts
February 21, 2026
18 min read

True Randomness for Smart Contracts: Why Block Hash Fails and What Works Instead

Block hash is exploitable. Chainlink VRF is cryptographic. QRNG is physics-based. Compare all four major approaches with real code examples, attack patterns, and an integration checklist.

qbit.technology/blog/true-randomness-smart-contracts
True Quantum Randomness for Smart Contracts: Secure. Unbiased. Verifiable.

The $12M Problem: When Randomness Isn't Random

In late 2021, a popular on-chain lottery protocol experienced something that shouldn't be possible: predictable "random" winners. The smart contract generated randomness using blockhash(block.number - 1), a pattern that seemed reasonable but contained a fatal flaw. Within 256 blocks, historical block hashes become unavailable, and worseminers could influence the hashes they produced.

A sophisticated attacker recognized this weakness and systematically timed transactions to manipulate outcomes. By running a validator node, they could influence block contents and predict which addresses would win high-value lottery positions. The exploit went undetected for months because the attack vector wasn't obvious to protocol developers who had never studied the cryptographic properties of blockchain data structures.

Critical Insight
Most on-chain randomness solutions are fundamentally flawed. Yet randomness is essential for NFT trait assignment, blockchain games, DeFi governance, and liquidation selection.

The challenge is finding a source of entropy that is:

  • Unpredictable: No party can compute the outcome before commitment
  • Unbiasable: Miners, validators, and users cannot influence the result
  • Verifiable: The output can be cryptographically proven correct
  • Quantum-resistant: Immune to future computational breakthroughs

This article compares four major approachesblock hash, commit-reveal schemes, Chainlink VRF, and quantum entropy sources like QBIT QRNGwith concrete code examples, security tradeoffs, and implementation guidance.

Why Blockchain Randomness Is Fundamentally Different

Traditional applications generate randomness using system entropy: /dev/urandom on Unix, APIs like crypto.getRandomValues() in browsers. These work because the operating system collects environmental noisedisk timing, network interrupts, thermal variationand mixes it into a random pool.

Blockchains can't do this. Every smart contract runs on thousands of nodes simultaneously, and every node must compute the exact same result. If randomness came from local entropy sources, different nodes would reach different conclusions, and consensus would break.

The Blockchain Randomness Paradox
All data on-chain is deterministic and reproducible. Anything a contract can "see" (block headers, prior transactions, timestamps) is visible to attackers too. Yet developers must generate unpredictable values without external data.

The solutions explored in this article work around this constraint by either:

  • Moving randomness off-chain and verifying it cryptographically (VRF, QRNG)
  • Distributing trust across multiple parties (commit-reveal)
  • Using physics-based entropy from quantum systems that no computing power can predict (QRNG)

Comparison: Block Hash vs Commit-Reveal vs Chainlink VRF vs QRNG

PropertyBlock HashCommit-RevealChainlink VRFQBIT QRNG
Entropy SourceDeterministic blockchain dataMulti-party input (hashed)Cryptographic signature (off-chain)Quantum physical randomness
PredictabilityMiner can bias/controlSecure if honest participantCryptographically unpredictablePhysics-based unpredictable
VerifiabilityTransparent but influencedRequires all parties revealYes — proof verified on-chainYes — quantum signature proof
Quantum ResistanceNo — vulnerableNo — hash collisions possibleNo — ECDSA breaks under quantumYes — physics-based
Latency1–2 blocks2 phases + reveal delay5–20 min callbackSub-second callback
Cost~50k gas only~200k gas (commit+reveal)5–50+ LINK per requestQuantum entropy fee (varies)
Front-RunningYes — MEV builders reorderPartially — during revealNo — output committedNo — output committed

The Block Hash Pitfall: Why It's Still Used (And Why It Shouldn't Be)

Block hashes appear randomthey're 256-bit values derived from transaction trees. Many developers use them for randomness:

UnsafeRNG.sol
solidity
// DON'T DO THIS
pragma solidity ^0.8.0;

contract UnsafeRNG {
    function getRandomTraitID() internal view returns (uint256) {
        // Looks unpredictable, but miners control the outcome
        return uint256(blockhash(block.number - 1)) % 10;
    }

    function mintNFT() external {
        uint256 trait = getRandomTraitID();
        // Assign rarity based on trait ID
    }
}
Why This Breaks
  • Miner control: Miners select which transactions go into blocks and can choose favorable outcomes.
  • Reorg attacks: Validators can propose alternative chains and choose the one with the best randomness outcome.
  • Historical access: Contracts can't access blockhash() values older than 256 blocks.
  • Timestamp manipulation: Miners can adjust block timestamps within bounds (±15 seconds on Ethereum).

Commit-Reveal Schemes: Distributed but Coordination-Heavy

Commit-reveal schemes solve the miner manipulation problem by forcing participants to commit to values before revealing them. The two-phase design prevents early observation:

  • Phase 1 Commit: Each participant submits hash(secret_value + salt) without revealing the original value.
  • Phase 2 Reveal: Participants publish their original values. The contract verifies they match the commitment, then XORs all values to produce randomness.
CommitRevealRNG.sol
solidity
pragma solidity ^0.8.0;

contract CommitRevealRNG {
    bytes32[] public commits;
    uint256 public commitDeadline;
    uint256 public revealDeadline;
    bool public revealPhaseActive = false;

    // Phase 1: Participants commit
    function commit(bytes32 hashedValue) external {
        require(block.timestamp < commitDeadline, "Commit phase ended");
        commits.push(hashedValue);
    }

    // Phase 2: Participants reveal
    function reveal(uint256 secret, bytes32 salt) external {
        require(revealPhaseActive, "Not in reveal phase");
        require(block.timestamp < revealDeadline, "Reveal phase ended");
        bytes32 commitment = keccak256(abi.encodePacked(secret, salt));
        // Verify & XOR into accumulator
    }

    function getRandom() external view returns (uint256) {
        require(block.timestamp >= revealDeadline, "Reveal phase ongoing");
        return uint256(randomValue);
    }
}

Advantages

  • No external oracle required
  • Transparentall participants see each other's values
  • Impossible to manipulate if one honest participant
  • Low cost (just hashing and XOR)

Disadvantages

  • Coordination burden across both phases
  • Withholding attacks can halt the lottery
  • Off-chain coordination creates DoS vectors
  • Breaks down at scale (thousands of participants)

Quantum Entropy: Physics-Based Randomness for True Unpredictability

Quantum randomness sources (QRNG) generate entropy from physical quantum processesphoton detection, quantum tunneling, radioactive decaythat are fundamentally unpredictable. No amount of computational power or mathematical analysis can predict quantum outcomes.

QBIT QRNG provides access to real quantum entropy hardware, with the same oracle callback interface as Chainlink VRF but with three critical differences:

  • Physics-based: Entropy comes from quantum measurement, not cryptographic operations
  • Quantum-resistant: Quantum computers cannot predict the outcomes
  • Verifiable: Measurement signatures prove the randomness came from legitimate quantum hardware
QRNGConsumer.sol
solidity
pragma solidity ^0.8.4;
import "@qbit/contracts/src/v0.8/QRNGConsumerBase.sol";

contract QRNGConsumer is QRNGConsumerBase {
    QRNGCoordinatorV2Interface COORDINATOR;
    uint64 subscriptionId;
    uint256[] public quantumRandomWords;

    constructor(uint64 _subId) QRNGConsumerBase(qrngCoordinator) {
        COORDINATOR = QRNGCoordinatorV2Interface(qrngCoordinator);
        subscriptionId = _subId;
    }

    function requestQuantumRandomness() external returns (uint256) {
        return COORDINATOR.requestRandomWords(
            keyHash, subscriptionId, callbackGasLimit, 1
        );
    }

    function fulfillRandomWords(
        uint256 _requestId,
        uint256[] memory _randomWords
    ) internal override {
        quantumRandomWords = _randomWords;
    }

    function mintNFTWithQuantumRarity() external {
        require(quantumRandomWords.length > 0, "Not available");
        uint256 rarity = quantumRandomWords[0] % 100;
        uint256 traitId = (quantumRandomWords[0] / 100) % 50;
        _safeMint(msg.sender, rarity, traitId);
    }
}
AspectECDSA (Chainlink VRF)Quantum RNG (QBIT)
Predictability sourceMathematical (can be computed)Physical (cannot be computed)
Attack modelBreak algorithm, predict signaturesViolate laws of physics
Shor’s AlgorithmVulnerableImmune
VerifiabilityCryptographic proofMeasurement proof
Trust requiredOracle honesty + cryptographyQuantum hardware + measurement integrity
Practical Advantages of QBIT QRNG
  • Sub-second latency: Quantum hardware delivers entropy immediately
  • Scalability: Quantum entropy is generated continuously, not on-demand
  • Future-proof: Immune to cryptanalytic breakthroughs and quantum computers
  • Verifiable supply chain: QBIT provides measurement proofs and hardware validation

Real-World Attack Patterns: How Randomness Breaks in Production

Attack 1: The MEV Sandwich Attack on Commit-Reveal

A user commits to a value in a commit-reveal lottery. A searcher observes the pending commit transaction in the mempool and realizes they can frontrun it:

  1. Searcher includes their own commit first
  2. Searcher observes the target user's commit
  3. During reveal phase, searcher withholds their own reveal
  4. User reveals alone, giving searcher information to decide whether to reveal too

This isn't possible with threshold cryptography (VRF/QRNG) because outcomes are determined before any participant sees them.

Attack 2: Validator Control of Block Hash Randomness

A stake pool operator running a consensus client can influence randomness by building multiple chain tips, observing which produces favorable outcomes, and continuing the favorable tip. This requires both validator control and observation, but it's economically rational for high-value lotteries.

Attack 3: Historical Block Hash Lookups

Vulnerable Pattern
solidity
// Vulnerable pattern — do not use
uint256 oldHash = uint256(blockhash(block.number - 100));

Since blockhash() only works for blocks N-256 to N-1, the history is immutablethe randomness outcome is now known. Block hash has a hard 256-block limit by protocol design. You cannot work around it.

Attack 4: Timestamp Manipulation During High-Volume NFT Mints

Vulnerable Pattern
solidity
// Vulnerable
uint256 seed = block.timestamp % 1000;

A proposer can set the timestamp to allowed values, pre-compute randomness for each, choose the best outcome, and repeat for multiple transactions in the same block. Chainlink VRF and QRNG prevent this by committing to randomness before block construction.

Integration Checklist: Choosing and Implementing Secure Randomness

For NFT Projects

  • Separate minting from trait assignment
  • Use Chainlink VRF or QBIT QRNG for trait randomness
  • Never use blockhash(), block.timestamp, or msg.sender for rarity
  • Verify oracle callback authenticity before assigning traits
  • Log all randomness requests and fulfillments for auditability

For Games

  • Use verifiable randomness for all outcome-determining values
  • Separate game action (betting) from outcome commitment (VRF request)
  • Never allow users to choose when randomness is generated
  • Implement per-action gas limits to prevent looping attacks
  • Test with both honest and Byzantine players

For DeFi Protocols

  • Use randomness for validator selection in liquidation auctions
  • Implement threshold schemes if decentralizing oracle selection
  • Monitor oracle uptime and consider fallback mechanisms
  • Document oracle dependencies in risk disclosures
  • Consider hybrid approaches (VRF + QRNG) for critical systems

FAQ

How can attackers exploit weak randomness in NFT minting?

Attackers target predictable randomness by timing transactions to favorable outcomes. With block hash randomness, a validator can observe multiple potential blocks and choose the one producing the best traits. Verifiable randomness (VRF/QRNG) solves this by committing to the random output before any user knows the outcome.

Why is Chainlink VRF cryptographically sound if it's off-chain?

Chainlink VRF moves generation off-chain but verifies it on-chain using ECDSA signatures. A Chainlink node cannot forge a signature—attempting to would be mathematically equivalent to breaking elliptic curve cryptography, which is computationally infeasible with classical computers.

Can quantum computers break Chainlink VRF?

Yes, partially. Shor’s algorithm can compute discrete logarithms, allowing an attacker to forge ECDSA signatures. This is why quantum-resistant sources like QBIT QRNG matter—they generate entropy from physics, not mathematics.

How do I choose between Chainlink VRF, QBIT QRNG, and commit-reveal?

Use Chainlink VRF for industry-standard solutions in Ethereum ecosystem. Use QBIT QRNG for quantum-resistant guarantees, multi-chain environments, or sub-second latency needs. Use commit-reveal for small, trusted groups like DAO voting with zero external dependencies.

Can I combine multiple randomness sources for higher security?

Yes. XOR combination (uint256 finalRandom = vrfOutput ^ qrngOutput) requires both oracles to be compromised. For most applications, a single well-chosen source is sufficient. Use hybrid approaches only for exceptionally high-value outcomes (>$1M).

Conclusion

Randomness on blockchains is a solved problem, but only if you choose the right tool for your use case.

Block hash is never appropriate for valuable outcomes. Commit-reveal works for small, coordinated groups but breaks down at scale. Chainlink VRF is the industry standardsecure, well-tested, and well-supported. Quantum RNG sources like QBIT QRNG represent the future of blockchain entropy.

The good news: implementing secure randomness is straightforward. Copy the code examples from this guide, follow the integration checklist, and you'll have a system that's resistant to miner manipulation, oracle bias, and front-running attacks.

The better news: your users will know they're in a fair game. That trust is worth more than any randomness algorithm.

Ready to implement true randomness?

Explore the QBIT developer SDK, review our documentation, and start building with quantum entropy today.

Share this article