Group of developers pairing on Solidity code at a communal table, laptops open, whiteboards in background, tech bootcamp collaboration.
Protocols

On-Chain Randomness Generation

A security-focused implementation playbook for sourcing randomness in Michelson contracts. Covers the RANDOM opcode, commit-reveal schemes, baker manipulation risks, and secure pattern requirements for DeFi and gaming applications.
introduction
ON-CHAIN RANDOMNESS IN TEZOS

Introduction

Understanding the security model, manipulation risks, and implementation patterns for generating randomness in Michelson smart contracts.

On-chain randomness generation is a critical primitive for DeFi protocols, gaming applications, and NFT minting platforms on Tezos. The protocol provides a native RANDOM opcode in Michelson, but its security properties are fundamentally limited by the baker's ability to censor or selectively include operations that produce unfavorable outcomes. Builders must understand that RANDOM alone is not a secure source of randomness for high-value applications; it is a commitment to a future random seed that a block proposer can observe before deciding whether to include a transaction.

The standard mitigation pattern on Tezos is a commit-reveal scheme, where a user commits to a future action by submitting a hash, waits for the RANDOM seed to be fixed in a subsequent block, and then reveals their action. This two-phase approach prevents last-second manipulation by ensuring the random outcome is bound to a seed that was unknown at the time of commitment. However, the security of this pattern degrades if the economic value of manipulation exceeds the baker's block reward and bond, or if the reveal phase is not enforced with timeouts and penalties. Developers must also account for the RANDOM opcode's behavior across protocol upgrades, as changes to the seed generation mechanism could alter the distribution or predictability of values.

For teams building lotteries, randomized airdrops, or on-chain games, a security review of the randomness implementation is essential. Chainscore Labs can assess the commit-reveal lifecycle for front-running vulnerabilities, verify timeout and penalty logic, and model the economic incentives for baker manipulation at various value thresholds. This analysis extends to integration risks for wallets and indexers that must correctly parse and display the two-phase state machine to users.

ON-CHAIN RANDOMNESS SECURITY

Quick Facts

Key facts about randomness sources, manipulation risks, and secure usage patterns in Tezos smart contracts.

FieldValueWhy it matters

Primary opcode

RANDOM

The only native source of pseudo-randomness in Michelson; its security properties dictate the design of all on-chain games and lotteries.

Entropy source

Baker-selected seed within protocol constraints

A baker can choose to not include a transaction if the resulting randomness is unfavorable, making naive single-transaction randomness insecure.

Manipulation cost

Loss of baking rewards and fees for the skipped block

The economic cost of manipulation is low for high-value outcomes, so commit-reveal schemes are required to increase the cost of bias.

Secure pattern

Commit-Reveal with RANDOM

A two-step process where a commitment is made before the random seed is known, preventing bakers from selectively censoring unfavorable results.

Commitment phase

User submits a hash of their secret and choice

This locks in the user's action without revealing it, making it impossible for a baker to predict the outcome of the final reveal.

Reveal phase

User reveals the secret; contract combines with RANDOM

The final randomness is derived from both the user's pre-committed secret and the baker-provided seed, making bias computationally infeasible.

Critical vulnerability

Using RANDOM in a single operation

A contract that generates randomness and settles the outcome in the same transaction is trivially exploitable by the block-producing baker.

Review target

Commit-reveal state machine logic

Flaws in timeout handling, secret length, or reveal validation can still allow manipulation, making a security review of the full game logic essential.

technical-context
RANDOMNESS SOURCING IN MICHELSON

Technical Mechanism

A technical breakdown of the on-chain randomness primitives available to Tezos smart contract developers and the secure patterns required to mitigate baker manipulation.

Tezos provides a dedicated RANDOM opcode in Michelson that generates a pseudo-random byte sequence within a smart contract's execution context. The opcode consumes a seed, a number of bytes, and the current level from the stack, and produces a deterministic sequence of bytes. The critical security property is that the generated value is deterministic given the same inputs and context, meaning its entropy is entirely dependent on the seed provided by the caller. A naive implementation where a user submits a seed in the same operation that consumes the randomness is trivially exploitable, as a baker can reorder transactions, censor unfavorable seeds, or simulate the outcome before deciding to include the operation.

The standard mitigation for this manipulation vector is a commit-reveal scheme, which decouples the seed submission from the randomness consumption across two distinct phases. In the commit phase, a participant submits a hash of a secret seed, locking in their future randomness contribution without revealing it. The contract records this commitment alongside the block level. In the reveal phase, typically enforced after a minimum number of blocks have elapsed, the participant submits the original secret. The contract verifies it against the stored hash and then uses it as the seed for the RANDOM opcode. This temporal separation prevents bakers from simulating the outcome during the commit phase because the secret is unknown, and it prevents them from censoring the reveal phase without forfeiting the opportunity, as the commitment is already on-chain.

Despite the commit-reveal pattern, residual risks remain. A baker can still censor the reveal operation if the economic value of doing so exceeds the cost of the forfeited commitment. For high-value applications, developers must carefully calibrate the timeout window and the economic stake required during the commit phase. Additionally, the RANDOM opcode itself is not a source of cryptographic entropy; it is a deterministic pseudo-random generator. The security of the entire scheme collapses if the secret is guessable or if the same seed is reused. Teams implementing on-chain randomness for lotteries, gaming, or DeFi protocols should subject their specific commit-reveal implementation and parameter choices to a dedicated security review to ensure the manipulation cost is appropriately calibrated for the value at stake.

RANDOMNESS SECURITY RESPONSIBILITIES

Affected Actors

DeFi and Gaming Developers

You bear the primary responsibility for implementing randomness securely. The RANDOM opcode alone is insufficient for high-value use cases because the baker who produces the block can manipulate the result.

Required Actions:

  • Never use RANDOM as the sole source of entropy for prize draws, NFT mints, or liquidation ordering.
  • Implement a commit-reveal scheme where users commit a hash of their secret, the contract mixes the revealed secret with a block-level value, and a timeout handles non-revealing participants.
  • Ensure your commit-reveal scheme is resistant to last-revealer manipulation by using a two-phase reveal structure or a verifiable delay function (VDF) for critical applications.
  • Test your implementation against a baker who selectively includes or excludes operations to bias the outcome.

Chainscore Labs can review your randomness architecture and commit-reveal logic to identify manipulation vectors before mainnet deployment.

implementation-impact
SECURE RANDOMNESS INTEGRATION

Implementation Workflow & Patterns

A structured approach to integrating on-chain randomness in Tezos, moving from understanding baker manipulation risks to implementing commit-reveal schemes and verifying the final contract.

01

1. Threat Modeling: Baker Manipulation

Begin by modeling the specific financial risk if a baker manipulates the outcome. The RANDOM opcode exposes a value from the baker's context, making it trivially predictable and manipulable by the block proposer. For any application where the outcome has monetary value—such as NFT mints, gaming rewards, or lottery draws—a single-block reliance on RANDOM is a critical vulnerability. Quantify the maximum extractable value per manipulated transaction to determine the required security rigor for your commitment scheme.

02

2. Designing the Commit-Reveal Scheme

Implement a two-phase commit-reveal pattern to neutralize baker front-running. In the commit phase, a user submits a hash of their secret and their intended action. In the reveal phase, typically after a delay of several blocks, the user reveals the secret. The final on-chain randomness is derived by combining the revealed secret with a protocol-level value from a block after the commit, making it computationally infeasible for a baker to pre-calculate a profitable outcome. Ensure the reveal window has a strict deadline with a slashing or forfeiture mechanism for non-revealers.

03

3. Secure Entropy Sourcing

Do not use a single source of entropy. Combine the user's revealed pre-image with a future block hash or a value from a decentralized oracle. In Tezos, a common pattern is to use the block hash of the reveal operation's block or a subsequent one. This ensures that even if a user tries to abort a losing reveal, the protocol can enforce a penalty. For high-value applications, consider a multi-party computation or a verifiable delay function (VDF) oracle to further decentralize the entropy source and remove single-baker bias.

04

4. Michelson Implementation & Gas Profiling

Translate the commit-reveal logic into gas-efficient Michelson. Use SHA256 or BLAKE2B for hashing secrets and CHECK_SIGNATURE if the commit needs to be authenticated. Store the commitment and a block-level deadline in a big_map. The reveal entrypoint must verify the hash, combine the secret with the designated block hash, and execute the final logic. Profile the reveal operation extensively, as complex hashing and state updates can hit gas limits, causing the transaction to fail and locking user funds.

05

5. Integration Testing & Simulation

Before mainnet deployment, simulate the full commit-reveal lifecycle using the run_script and simulate_operation RPCs. Test adversarial scenarios: a user committing and not revealing, a baker attempting to censor reveal transactions, and a user trying to reveal with an incorrect secret. Verify that the forfeiture logic correctly transfers funds and that the final randomness is uniformly distributed. This simulation phase is critical for catching logic errors that could lead to permanent fund loss.

ON-CHAIN RANDOMNESS SECURITY

Risk Matrix

Evaluates failure modes and manipulation risks for Tezos applications sourcing randomness on-chain via the RANDOM opcode or commit-reveal schemes.

RiskFailure modeSeverityMitigation

Baker manipulation of RANDOM opcode

A baker can selectively withhold or include blocks to influence the random seed within a future cycle, biasing outcomes in gambling or lottery contracts.

High

Do not use RANDOM for high-value outcomes. Implement a commit-reveal scheme that requires participants to commit before the seed is known.

Last-revealer advantage in commit-reveal

In a naive commit-reveal scheme, the last participant to reveal can calculate the final outcome and choose to abort by not revealing, skewing results.

High

Require economic collateral from all participants that is slashed if they fail to reveal within the timeout window.

Block producer censorship of reveal transactions

A baker can censor a specific participant's reveal transaction to prevent an unfavorable outcome, effectively biasing the result.

Medium

Design reveal phases to span multiple blocks and use a commit-reveal scheme with a sufficiently long reveal window to make sustained censorship costly.

Insufficient entropy source

Using only block hash or level as a seed provides low entropy that a baker can brute-force or manipulate by grinding through block contents.

High

Combine multiple future block hashes or use a verifiable delay function (VDF) to prevent grinding. Ensure the seed space is computationally infeasible to iterate.

Front-running of commit transactions

A mempool observer sees a pending commit and submits their own commit with a more favorable value, gaining an edge in the subsequent reveal phase.

Medium

Use a cryptographic commitment scheme (e.g., hash of value + secret salt) to hide the committed value until the reveal phase.

Smart contract reentrancy during payout

A malicious winner contract calls back into the randomness game contract during prize distribution, re-entering and draining funds.

Critical

Follow the checks-effects-interactions pattern. Update internal state before making external calls. A Chainscore Labs security review can verify reentrancy guards.

Incorrect off-chain verification by indexers

An indexer or UI incorrectly computes the on-chain randomness outcome, displaying a false win/loss state to users.

Low

Replicate the exact Michelson randomness logic off-chain. A Chainscore Labs review can audit the indexing logic for parity with on-chain computation.

RANDOMNESS IMPLEMENTATION REVIEW

Developer Security Checklist

A practical checklist for developers implementing on-chain randomness in Michelson. Each item identifies a specific risk, explains why it matters, and describes the signal or artifact that confirms a secure implementation.

What to check: Confirm that the contract strictly separates a commit phase from a reveal phase, and that the reveal phase cannot be skipped or replayed. The contract must store a hash of the preimage during commit and verify it during reveal.

Why it matters: Without a properly enforced two-phase lifecycle, a baker or observer can withhold or selectively publish transactions to manipulate the final randomness output. The commit must be immutable once submitted, and the reveal must be mandatory for the game to resolve.

Readiness signal: The contract's entrypoint logic shows a clear state machine transition from AwaitingCommit to AwaitingReveal to Resolved, with no path to resolve without a valid reveal matching the stored commitment.

Chains We Build On

Looking to build on a specific blockchain?

We build smart contracts, DeFi applications, wallets, tokenization platforms, and blockchain infrastructure across the major ecosystems teams choose today. That includes Ethereum, Arbitrum, Optimism, Polygon, Avalanche, Solana, Sui, Aptos, Hedera, Stellar, and NEAR, with support for additional EVM and non-EVM networks based on your product requirements.

EVM ecosystems

  • Ethereum logo
    Ethereum
  • Arbitrum logo
    Arbitrum
  • Optimism logo
    Optimism
  • Polygon logo
    Polygon
  • Avalanche logo
    Avalanche
  • Cronos logo
    Cronos

Non-EVM ecosystems

  • Solana logo
    Solana
  • Sui logo
    Sui
  • Aptos logo
    Aptos
  • Hedera logo
    Hedera
  • Stellar logo
    Stellar
  • NEAR logo
    NEAR

Additional ecosystems

  • Polkadot logo
    Polkadot
  • Cosmos logo
    Cosmos
  • TON logo
    TON
  • Cardano logo
    Cardano
  • Algorand logo
    Algorand
  • Tempo logo
    Tempo

Also available for Base, appchains, custom EVM networks, and cross-chain product architecture.

RANDOMNESS SECURITY FAQ

Frequently Asked Questions

Common questions from developers building games, lotteries, and DeFi protocols that require on-chain randomness on Tezos.

No, not by itself. The RANDOM opcode in Michelson generates a pseudo-random value deterministically from a seed. The seed is derived from the commitment (a hash of the baker's secret and the cycle position) revealed by the baker. A malicious baker can choose to withhold block production if the resulting randomness is unfavorable to them, effectively allowing them to bias the outcome. This is a form of last-revealer manipulation. For any application where the financial incentive to manipulate the outcome exceeds the baker's block reward, using RANDOM directly is unsafe. You must combine it with a commit-reveal scheme or an external verifiable random function (VRF) oracle.

Trusted by Industry Leaders

Delivering blockchain solutions for 5+ years.

We have partnered with 50+ leading DeFi protocols, NFT ecosystems, and fintech innovators to build secure, scalable, and capital-efficient blockchain products.

Selected Partners & Clients

ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
“I've been working with Chainscore Labs for last 3+ years, they've consistently delivered with strong ownership across multiple projects. The team is reliable and detail-oriented.”
L
Lee Erswell
CEO, Telos Foundation
how to get started

How to get started?

If you're looking for blockchain integration, ChainScore Labs has 5+ years of experience helping teams build and integrate exchanges, wallets, smart contracts, tokenization solutions, and protocol-connected products, we can help you choose the right path, integrate securely, and get to production faster. Our team consists of experienced blockchain developers and architects who can help you with your blockchain integration needs.

01

Exploration & Strategy

Define your product goals and choose the right blockchain architecture for your use case.

02

Architecture & Design

Design the smart contracts, tokenomics, and security parameters of your system.

03

Development & Integration

Build and integrate with wallets, oracles, and front-end dApps for a seamless experience.

04

Security & Launch

Comprehensive audits followed by a risk-managed mainnet deployment to protect your users.

Start a build

Need a blockchain engineering team?

Send the project context and we will respond with next steps, scope questions, and a practical path to delivery.