How to get random number in Solana on-chain program?

Viewed 1428

I have just jumped in Solana on-chain program. I am going to make coin game which judge frontside or backside. I tried to use std:: rand and get_random crate but they don't work. If you have experience about it, please let me know.

I use anchor for Solana on-chain program.

1 Answers

unfortunately, The random generator doesn't work on-chain. if you want some randoms, you should get it from outside the chain.

reason?

assume you making randoms using block hash or something similar, so users can exploit that by inserting an instruction or values that checks for favorable outcomes and even worse, forcing it to roll back if it's not satisfactory.

so what should we do?

  1. try to use oracles like chainlink vrf(verifiable random function)

  2. simulate oracle vrf services:

make transaction on-chain that your server listens to it. if this transaction happened, make random number off-chain and callback it from your server.

anchor use randoms like this

use rand::rngs::OsRng;
.
.
.
let dummy_a = Keypair::generate(&mut OsRng);

so, if you require randomness for UUID-like behavior you can use a mechanism like the above from the anchor code repository but if your case is game logic like a dice roll, you need oracles or simulate that.

Related