Member-only story
How to Generate Truly Random Numbers in Solidity and Blockchain
Why need random numbers in blockchain, what the issues are, and the best solutions

Generating random numbers in solidity historically has been an issue until Chainlink VRF came around. Right now though, if you try to find out how to make random numbers in solidity, your top results include:
Solidity is not capable of creating random numbers.
Don’t generate random numbers inside your contracts. It won’t work, you will get hacked.
Be careful. That random number is 100% predictable so not suitable for a game of chance or any situation in which a participant is presumed to not be able to guess it.
— Rob Hitchens on StackExchange ETH
They don’t seem too promising, and they are all saying the same thing.
Getting a Random Number on the Blockchain Has Historically Been a Security Disaster
Yes. I said “historically”. If you’ve got any context clues at all, yes I’m going to tell you how this is circumvented, solved, and how you can create a verifiably random number in three minutes.
And if you learn anything by the end of this article, please do me and the world a favor and use this knowledge to create a Texas hold’em game. Please. Before I do.
Why do we need random numbers?
We might want to create a random number to make a lottery, game, or get random seeds for test data. To do this in the past, we’d use the most current block hash as the seed for our pseudo-random number generator. This is the first approach most tutorials will take you through.
Approach 1: Use the Current Blockhash
Since the blockchain is constantly growing, and the ID of each block hash constantly changing, we can just use that block has to get a random number, right? We can code this in solidity with this function:
function random() private view returns(uint){
return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
}