Randomness and the Blockchain

How to achieve secure randomness for Solidity smart contracts?

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.

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. 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

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 difficulty of the block, i.e., how many trailing zeros are sufficient for a successful new hash.
  • block.gaslimit: The gas limit of the block, i.e., the maximum allowed amount of gas per transaction.
  • block.coinbase: The block miner’s address.

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 a concept of private memory 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. A block hash in Ethereum is computed as the Keccak256, an early implementation of SHA-3. It is a one way function, and by requiring a certain amount of trailing zeros as well as the miner’s address as salt, the resulting hash cannot be predicted by anyone. Well, that’s at least the idea.

First, you have to use it right. That means, use a future block hash! If you use an old one, people can see it obviously. If you use the current block’s hash, it will be empty, because it hasn’t been mined yet.

How to use a future block hash?

mapping (address => uint256) gameWeiValues;
mapping (address => uint256) blockHashesToBeUsed;

function playGame() public {
    if (!blockHashesToBeUsed[msg.sender]) {
        // first run, determine block hash to be used                          
        blockHashesToBeUsed[msg.sender] = block.number + 2; // use 2 or more
        gameWeiValues[msg.sender] = msg.value;

    uint256 randomNumber = uint256(blockhash(blockHashesToBeUsed[msg.sender]));

    blockHashesToBeUsed[msg.sender] = 0;
    gameWeiValues[msg.sender] = 0;

    if (randomNumber != 0 || randomNumber % 2 == 0) {
        uint256 winningAmount = gameWeiValues[msg.sender] * 2;

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 for example.

So all good with using the future block hash?

It depends! Are you allowing gambles with winning amounts higher than the block reward? Then be aware of miner manipulation. If we assume a block reward of 3 ETH, any gamble for more than 6 ETH actually gives miners an incentive to cheat on the gamble. While a miner cannot freely choose the hash for a block, he may choose not to publish a newly found block hash → influence on the randomness.

3. Commitment scheme

First versions of the commitment scheme exist since 1981. Have a look a Michael Blum’s coin flipping over the telephone. 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 it’s impossible to find a collision (another number that produces the same hash). 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, P1Pn, 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, he automatically looses.

Sounds too good to be true? You’re right. This only works for two nodes, e.g., in a casino with a bank and single player. I have implemented a proof of concept prototype for this in Solidity and AWS Lambda: https://github.com/gorgos/Highstakes-SmartRoulette.

Let’s see why this only works for two nodes:

The issue we are facing is the situation where the last node Pi has to reveal its value, since it can calculate R with its last secret value before anybody else, the last-revealer-problem. Thus, it might not be able to influence R any more as it is committed to its value Vi. However, it may choose not to reveal the value, leaving all other parties no other option than to abort the random number generation. As in the two-user scenario, the not revealing node may loose the gamble. Nevertheless, that is not sufficient this time. Since there may be multiple users behind an entity and only the not-revealing-party looses, an attacker may do the following:

  1. Create as many entities as wanted and participate in the gamble with all of them.
  2. In the reveal phase, hold back the secret value of his last entity.
  3. Wait for every other entity to reveal their value and then compute the final result. If it yields a positive outcome in the sum for all participating entities, choose to reveal the value of the last entity. Otherwise, never reveal the last value. The gamble must be aborted and players will be refunded. The attacker only lost the gamble with a single entity.

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: Unfortunately, the required pledge sizes can get absurdly high. Given a lottery for 10,000 participants, a ticket fee of 4 USD and a single winner, every participant would be required to pledge almost 400 million USD when refunding the pledges to the participants (feel free to do the math).

Alternatively, the pledges can be burned (Refunding them to the bank, the random number service, charity or some other third party poses the risk of cheating from the receiving party). Burning pledges reduces the necessary pledge size down to 39,992 USD for our lottery example which is still too high for most practical use cases.

A similar implementation exists, but has not been used in practice as of this date. Randao will also be used in ETH2.0 as base random beacon topped with VDF’s (verifiable delay functions). We can discuss the usage in ETH2.0 in more detail in a later post.


We have looked at two methods for multi-party randomness in Solidity. While the blockhash if used correctly, works nicely in many scenarios, it does not perform well when there is much at stake which would allow miners to cheat. Secondly, the commitment approach is very useful for two-player scenarios. Unfortunately for multi-player situations for most real-world use cases, it will not suffice. What can we do then? One option might be using an oracle which we can discuss in the next related blog post.

Markus Waas

Solidity Developer

More great blog posts from Markus Waas

  • Matic Logo

    How to use Matic in your Dapp

    Deploying and onboarding users to Matic to avoid the high gas costs

    Gas costs are exploding again, ETH2.0 is still too far away and people are now looking at layer 2 solutions. Here's a good overview of existing layer 2 projects: https://github.com/Awesome-Layer-2/awesome-layer-2 . Today we will take a closer look at Matic as a solution for your Dapp. Why Matic...

  • Migrating from Truffle to Buidler

    And why you should probably keep both.

    Why Buidler? Proper debugging is a pain with Truffle. Events are way too difficult to use as logging and they don't even work for reverted transactions (when you would need them most). Buidler gives you a console.log for your contracts which is a game changer. And you'll also get stack traces...

  • Factory

    Contract factories and clones

    How to deploy contracts within contracts as easily and gas-efficient as possible

    The factory design pattern is a pretty common pattern used in programming. The idea is simple, instead of creating objects directly, you have an object (the factory) that creates objects for you. In the case of Solidity, an object is a smart contract and so a factory will deploy new contracts for...

  • IPFS logo

    How to use IPFS in your Dapp?

    Using the interplanetary file system in your frontend and contracts

    You may have heard about IPFS before, the Interplanetary File System. The concept has existed for quite some time now, but with IPFS you'll get a more reliable data storage, thanks to their internal use of blockchain technology. Filecoin is a new system that is incentivizing storage for IPFS...

  • tiny-kitten

    Downsizing contracts to fight the contract size limit

    What can you do to prevent your contracts from getting too large?

    Why is there a limit? On November 22, 2016 the Spurious Dragon hard-fork introduced EIP-170 which added a smart contract size limit of 24.576 kb. For you as a Solidity developer this means when you add more and more functionality to your contract, at some point you will reach the limit and when...


    Using EXTCODEHASH to secure your systems

    How to safely integrate anyone's smart contract

    What is the EXTCODEHASH? The EVM opcode EXTCODEHASH was added on February 28, 2019 . Not only does it help to reduce external function calls for compiled Solidity contracts, it also adds additional functionality. It gives you the hash of the code from an address. Since only contract addresses...

  • Uniswap

    Using the new Uniswap v2 in your contracts

    What's new in Uniswap v2 and how to integrate Uniswap v2

    What is UniSwap? If you're not familiar with Uniswap yet, it's a fully decentralized protocol for automated liquidity provision on Ethereum. An easier-to-understand description would be that it's a decentralized exchange (DEX) relying on external liquidity providers that can add tokens to smart...

  • Continuous Integration

    Solidity and Truffle Continuous Integration Setup

    How to setup Travis or Circle CI for Truffle testing along with useful plugins.

    Continuous integration (CI) with Truffle is great for developing once you have a basic set of tests implemented. It allows you to run very long tests, ensure all tests pass before merging a pull request and to keep track of various statistics using additional tools. We will use the Truffle...

  • Devcon 6

    Upcoming Devcon 2021 and other events

    The Ethereum Foundation just announced the next Devcon in 2021 in Colombia

    Biggest virtual hackathon almost finished First of all, the current HackMoney event has come to an end and it has been a massive success. One can only imagine what kind of cool projects people have built in a 30 days hackathon. All final projects can be seen at:...

  • ERC-2020

    The Year of the 20: Creating an ERC20 in 2020

    How to use the latest and best tools to create an ERC-20 token contract

    You know what an ERC-20 is, you probably have created your own versions of it several times (if not, have a look at: ERC-20 ). But how would you start in 2020 using the latest tools? Let's create a new ERC-2020 token contract with some basic functionality which focuses on simplicity and latest...

  • hiring

    How to get a Solidity developer job?

    There are many ways to get a Solidity job and it might be easier than you think!

    You have mastered the basics of Solidity, created your first few useful projects and now want to get your hands on some real-world projects. Getting a Solidity developer job might be easier than you think. There are generally plenty of options to choose from and often times not a lot of...

  • People making fun

    Design Pattern Solidity: Mock contracts for testing

    Why you should make fun of your contracts

    Mock objects are a common design pattern in object-oriented programming. Coming from the old French word 'mocquer' with the meaning of 'making fun of', it evolved to 'imitating something real' which is actually what we are doing in programming. Please only make fun of your smart contracts if you...

  • React and Ethereum

    Kickstart your Dapp frontend development with create-eth-app

    An overview on how to use the app and its features

    Last time we looked at the big picture of Solidity and already mentioned the create-eth-app . Now you will find out how to use it, what features are integrated and additional ideas on how to expand on it. Started by Paul Razvan Berg, the founder of sablier , this app will kickstart your frontend...

  • Solidity Overview

    The big picture of Solidity and Blockchain development in 2020

    Overview of the most important technologies, services and tools that you need to know

    Now, I do not know about you, but I remember when I first started with Solidity development being very confused by all the tools and services and how they work in connection with one another. If you are like me, this overview will help you understand the big picture of Solidity development. As I...

  • Design Pattern Solidity: Free up unused storage

    Why you should clean up after yourself

    You may or may not be used to a garbage collectors in your previous programming language. There is no such thing in Solidity and even if there was a similar concept, you would still be better off managing state data yourself. Only you as a programmer can know exactly which data will not be used...

  • How to setup Solidity Developer Environment on Windows

    What you need to know about developing on Windows

    Using Windows for development, especially for Solidity development, can be a pain sometimes, but it does not have to be. Once you have configured your environment properly, it can actually be extremely efficient and Windows is a very, very stable OS, so your overall experience can be amazing. The...

  • Avoiding out of gas for Truffle tests

    How you do not have to worry about gas in tests anymore

    You have probably seen this error message a lot of times: Error: VM Exception while processing transaction: out of gas Disclaimer : Unfortunately, this does not always actually mean what it is saying when using Truffle , especially for older versions. It can occur for various reasons and might be...

  • Design Pattern Solidity: Stages

    How you can design stages in your contract

    Closely related to the concept of finite-state machines, this pattern will help you restrict functions in your contract. You will find a lot of situations where it might be useful. Any time a contract should allow function calls only in certain stages. Let's look at an example: contract Pool {...

  • Web3 1.2.5: Revert reason strings

    How to use the new feature

    A new Web3 version was just released and it comes with a new feature that should make your life easier. With the latest version 1.2.5 , you can now see the the revert reason if you use the new handleRevert option. You can activate it easily by using web3.eth.handleRevert = true . Now when you use...

  • Gaining back control of the internet

    How Ocelot is decentralizing cloud computing

    I recently came across an ambitious company that will completely redefine the way we are using the internet. Or rather, the way we are using its underlying infrastructure which ultimately is the internet. While looking at their offering, I also learned how to get anonymous cloud machines, you...

  • Devcon 5 - Review

    Impressions from the conference

    I had a lot to catch up on after Devcon. Also things didn't go quite as planned, so please excuse my delayed review! This year's Devcon was certainly stormy with a big typhoon warning already on day 1. Luckily (for us, not the people in Tokyo), it went right past Osaka. Nevertheless, a lot of...

  • Devcon 5 - Information, Events, Links, Telegram

    What you need to know

    Devcon 5 is coming up soon and there are already lots of events available, information about Osaka and more. Here is a short overview: Events Events Calendar Events Google Docs Events Kickback Most events are in all three, but if you really want to see all, you will have to look at all three...

  • Design Pattern Solidity: Off-chain beats on-chain

    Why you should do as much as possible off-chain

    As you might have realized, Ethereum transactions are anything but cheap. In particular, if you are computing complex things or storing a lot of data. That means sometimes we cannot put all logic inside Solidity. Instead, we can utilize off-chain computations to help us. A very simple example...

  • Design Pattern Solidity: Initialize Contract after Deployment

    How to use the Initializable pattern

    There are a few reasons why you might want to initialize a contract after deployment and not directly by passing constructor arguments. But first let's look at an example: contract MyCrowdsale { uint256 rate; function initialize(uint256 _rate) public { rate = _rate; } } What's the advantage over...

  • Consensys Blockchain Jobs Report

    What the current blockchain job market looks like

    Consensys published their blockchain jobs report which you can checkout in their Blockchain Developer Job Kit . The most interesting aspects are Blockchain developer jobs have been growing at a rate of 33x of the previous year according to LinkedIns jobs report Typical salary is about...

  • Provable — Randomness Oracle

    How the Oraclize random number generator works

    One particularly interesting approach by Provable is the usage of a hardware security device, namely the Ledger Nano S. It uses a trusted execution environment to generate random numbers and provides a Provable Connector Contract as interface. How to use the Provable Randomness Oracle? Use the...

  • Solidity Design Patterns: Multiply before Dividing

    Why the correct order matters!

    There has been a lot of progress since the beginning of Ethereum about best practices in Solidity. Unfortunately, I have the feeling that most of the knowledge is within the circle of experienced people and there aren’t that many online resources about it. That is why I would like to start this...

  • Devcon 5 Applications closing in one week

    Devcon 5 Applications closing

    Watch out for the Devcon 5 applications. You only have one week left to apply either as Buidler Student Scholarship Press Devcon is by far the biggest and most impressive Ethereum conference in the world. And it's full of developers! I am especially excited about the cool location this year in...