# Randomness and the Blockchain

Author: Markus Waas

Published: 2019-06-23T08:56:15.000Z

Updated: 2026-09-13T14:25:30.000Z

Source: [https://soliditydeveloper.com/2019-06-23-randomness-blockchain](<https://soliditydeveloper.com/2019-06-23-randomness-blockchain>)

## Compatibility and review

Before you start

Historical 2019 proof-of-work discussion. Ethereum now uses proof of stake; block variables and block hashes are not secure application randomness by themselves. The original gambling sketch has been withdrawn because it was incomplete and unsafe.

[Official reference](<https://docs.soliditylang.org/en/latest/units-and-global-variables.html>)

**Update 2023**: Ethereum transitioned to Proof of Stake! If you are interested in the randomness there, you can now use the updated info over at [https://soliditydeveloper.com/prevrandao](<https://soliditydeveloper.com/prevrandao>).

When we talk about randomness and blockchain, these are really two problems:

1. How to generate randomness in smart contracts?
2. How to produce randomness for proof-of-stake (POS) systems? Or more generally, how to produce trusted randomness in public distributed systems?

There is some overlap of course and some approaches for the first problem may also be used for the second one and vice versa. But I can already tell you that the best possible solutions for both questions most likely hasn’t been found yet. The fact of the matter is that these are really important problems, to say it in the words of famous Donald:

> Random numbers should not be generated with a method chosen at random.
>
>
>
> Donald Knuth

Why is it so hard? Well, that’s due to the nature of random numbers. One can easily create a seemingly random stream of numbers which follows a certain logic known to an attacker which enables him to predict the numbers.

![Comic: an accounting office’s random number generator repeats nine; when questioned, its operator says you can never be sure with randomness.](<https://cdn0.scrvt.com/b095ee27d37b3d7b6b150adba9ac6ec8/440b97377ee5d6b4/c2a4cd736477/RNG.gif>)

Naively, one might propose that each node computes a random number locally. It further broadcasts this random number. Since each node will do the same, one can compute the final random number using a function that takes the previously locally generated numbers as inputs and produces a single output, e.g., `v1 ⊕ v2 · · · ⊕ vn`. However, the last node to broadcast his local random number can wait with the generation until he received local numbers from every other node. Subsequently, he can produce any final random number R for the distributed system by picking a local number `vx = R ⊕ v1 ⊕ v2 · · · ⊕ vn`. Clearly, such a system to produce random numbers is flawed.

We need something better. Stay tuned for detailed descriptions how to tackle these issues. Meanwhile, have a look at [Predicting Random Numbers in Ethereum Smart Contracts](<https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620?gi=55eb50efe444>). It’s a great start for the first question. And for the second one, there are some interesting ideas out there and some seemingly crazy ones, e.g., the new idea by the Ethereum Foundation to build thousands of ASIC’s to verify VDF’s.

## Random Number Generation for Solidity Smart Contracts \#1

By now, most people are aware of the problem that one faces when trying to generate random numbers in a smart contract. There is unfortunately no one-size-fits-all solution for this, so let me go through the existing solutions.

### Short Recap of Fails

![A gate secured with a padlock and string, captioned “Seems secure — against anyone incapable of using scissors.”](<https://cdn0.scrvt.com/b095ee27d37b3d7b6b150adba9ac6ec8/951878f9297addcd/dbde81f17242/v/b256e1038991/0secure.jpg>)

Let’s briefly look at the common first ideas and why they are bad. I won’t go into much detail here, because others have done a great job of doing so.

## 1. Using block variables

- *`block.number`*: The number of the block.
- *`block.timestamp`*: The timestamp of the block.
- *`block.difficulty`*: The historical proof-of-work difficulty used to determine the Ethash target. It is not a count of trailing zeros. Since the Merge, this opcode returns PREVRANDAO instead.
- *`block.gaslimit`*: The gas limit of the block, i.e., the maximum total gas for the block.
- *`block.coinbase`*: The block’s fee-recipient address (the miner’s beneficiary in this proof-of-work discussion).

Those are obvious bad choices, because they can be predicted by anyone or at least the miner. Some more easy (`block.number`) than others (`block.difficulty`).

What if we add a private seed to the contract? The resulting random number can be computed with a passed variable and the privately stored seed as inputs. However, this approach does not consider the impossibility to store private data inside a public network. Despite Ethereum having private state-variable visibility in smart contracts, this storage can still be read by anyone running an Ethereum node. Reading private or internal state can be achieved by `web3.eth.getStorageAt`. Therefore, it merely increases the effort for someone trying to predict the randomness.

## 2. Using the block hash

Technically also a block variable, but it deserves its own section. Ethereum’s block hash is Keccak-256 of the RLP-encoded execution block header. Keccak-256 differs from standardized SHA3-256. Historical Ethash proof of work separately compared its result with a difficulty-derived numeric target; it did not require trailing zeros in the block hash or use the miner’s address as a separate salt. A cryptographic hash alone does not turn block production into unbiased application randomness.

A past block hash is already public. During execution, `blockhash` returns zero for the current block, future blocks and blocks outside its 256-block window. Committing to a future block does not remove proposer influence, delayed settlement or withholding risks.

**How to use a future block hash?**

```solidity
// Historical sketch withdrawn during the September 2026 review.
// This was not a complete or safe gambling contract.
// For application randomness, use an authenticated randomness service
// and review its request, confirmation and fulfillment requirements.
// See https://docs.chain.link/vrf/v2-5/security
```

The check for `randomNumber != 0` is essential, because Solidity can only look back at 256 blocks. So if a player waits for more than 256 blocks, he could enforce it to be 0. This has been used to [hack SmartBillions](<https://www.reddit.com/r/ethereum/comments/74d3dc/smartbillions_lottery_contract_just_got_hacked/>) for example.

**So all good with using the future block hash?**

A block reward alone does not establish a safe maximum wager. The relevant incentives depend on the selection and settlement rules, the value at risk and the block producer’s other opportunities. The old 3 ETH / 6 ETH rule of thumb is not a security bound.

## 3. Commitment scheme

First versions of the commitment scheme exist since 1981. Have a look a Manuel Blum’s [coin flipping over the telephone](<https://www.cs.cmu.edu/~mblum/research/pdf/coin/>). It’s an interesting read. We can simply use hashes in Solidity. So what’s the idea?

We use the naive idea I described at the beginning:

> Each node computes a random number locally. It further broadcasts this random number. Since each node will do the same, one can compute the final random number using a function that takes the previously locally generated numbers as inputs and produces a single output, e.g., v₁⊕ v₂ · · · ⊕ vₙ.

But instead of broadcasting the random number, a node will compute the hash of that number first. This hash will be the *commitment*. It then broadcasts the commitment hash. How does that help?

As the name suggests, a node is then *committed* to its original secret number, because finding an alternative opening should be computationally infeasible for a suitable hash and encoding. Therefore, in the subsequent reveal phase a node cannot change its secret number anymore. Naturally, each node starts with the reveal phase only after having received all other node’s commitments. The procedure will look like this:

1. All participants, `P1` … `Pn`, each generate a secret value, `Vi`.
2. `Pi` computes the commitment hash for their secret value: `Ci = H(Vi)`.
3. Each `Pi` sends `Ci` first (instead of `Vi`) .
4. After all `Ci` are received, each `Pi` sends `Vi`. All participants can verify the receiving secret values by checking if `Ci == H(Vi)`.
5. Once all `Vi` have been revealed and verified, the result of the random number generation will be `R = V1 ⊕ V2 ⊕ … ⊕ Vn. (XOR)`
6. Should one participant fail to reveal his `Vi`, the protocol needs an explicit deadline and consequence for non-revelation; a hash commitment does not enforce either by itself.

![Meme of a puzzled man: “Something something something. Something just ain’t right.”](<https://cdn0.scrvt.com/b095ee27d37b3d7b6b150adba9ac6ec8/e0db21870b2646ab/358b4a23f95c/v/7fca0a646413/not-right.jpeg>)

Sounds too good to be true? You’re right. Commit-and-reveal can be used with two or more participants, but it needs an explicit answer to non-revelation in either case. I have implemented a proof of concept prototype for this in Solidity and AWS Lambda: [https://github.com/gorgos/Highstakes-SmartRoulette](<https://github.com/gorgos/Highstakes-SmartRoulette>).

Let’s look at the liveness problem:

The **last-revealer problem** is that a participant may know the result before deciding whether to complete the reveal phase. Binding the secret does not force disclosure. With multiple identities or external positions, a penalty tied only to one ticket may not cover the incentive to withhold. A protocol needs explicit timeout, settlement and incentive assumptions.

****

#### **Multi-party commitment scheme**

The modification for the multi-party environment is fairly simple, but comes with some major drawbacks.

**Modification:** In addition to their commitments, each participant sends along a pledge. After the reveal phase, the pledge will be refunded to every revealing entity. In case of participants not revealing their value, they not only just loose the gamble, but also their pledge. In such a scenario, the pledges of all not revealing entities are split between all revealing entities or alternatively burned.

**Implication:** Required collateral depends on the payoff model, control of multiple identities, refunds, side bets and the treatment of withheld contributions. The previous $400 million and $39,992 examples did not state enough assumptions to establish a general bound and have been removed. Burning a pledge changes incentives but does not by itself prove fairness or liveness.

A [similar implementation](<https://github.com/randao/randao>) was an early application-level experiment. Ethereum’s live proof-of-stake consensus uses proposer BLS reveals to update its RANDAO mix. The earlier VDF roadmap was research, not a feature implemented by the RANDAO transition.

## Conclusion

We have looked at block-derived values and commitment schemes. Neither is a complete application-randomness protocol by itself: both need carefully defined timing, settlement and trust assumptions. An authenticated verifiable-randomness service is another option, with its own confirmation and fulfillment requirements.
