Random number generation
Generating random numbers is a common task that you may need in many different projects. You might have already seen the random()
function in FunC docs, but note that its result can be easily predicted unless you employ some additional tricks.
How can someone predict a random number?
Computers are terrible at generating random information because all they do is follow the instructions of users. However, since people frequently need random numbers, they've devised various methods for generating pseudo-random numbers.
These algorithms typically require you to provide a seed value that will be used to generate a sequence of pseudo-random numbers. So, if you run the same program with the same seed multiple times, you'll consistently get the same result. In TON, the seed is different for each block.
Therefore, to predict the result of the random()
function in a smart contract, you just need to know the current seed
of the block, which isn't possible if you're not a validator.
Simply use randomize_lt()
To make the random number generation unpredictable, you can add the current Logical Time to the seed, so different transactions will have different seeds and results.
Just add the randomize_lt()
call before generating random numbers, and your random numbers will become unpredictable:
randomize_lt();
int x = random(); ;; users can't predict this number
However, you should note that validators or collators may still affect the result of the random number, as they determine the seed of the current block.
Is there a way to protect against manipulation by validators?
To prevent (or at least complicate) the substitution of the seed by validators, you can use more complex schemes. For instance, you could skip one block before generating a random number. If we skip a block, the seed will change in a less predictable manner.
Skipping blocks isn't a complex task. You can do it by simply sending a message to the Masterchain and back to the workchain of your contract. Let's examine a simple example!
Do not use this example contract in real projects, write your own instead.