Skip to main content

Onchain randomness

Advanced
Concept

The Internet Computer provides a secure and verifiable way to generate random numbers directly within canisters. This functionality is exposed through the raw_rand method offered by the management canister and the Motoko Random module.

The method takes no input and returns 32 pseudo-random bytes to the caller.

How it works

Behind the scenes, ICP utilizes a Verifiable Random Function (VRF) to generate randomness.

During each round, the VRF is evaluated with the current input being the number of the round. This process produces a fresh set of random bytes.

These bytes become the seed for a pseudorandom number generator (PRNG) called random tape. The random tape is built using chain-key cryptography and is used to create unique random values for each canister that requested randomness in the previous round.

raw_rand calls only use the random tape from the next round. This ensures that no one can exploit knowledge of the current round's randomness to predict future outputs. To learn more about the execution layer of ICP, refer to the execution layer documentation.

To learn more about the technical details of randomness on ICP, watch the Community Conversations video on randomness.

How to use

Developers can directly access randomness through the raw_rand method in the management canister. See the examples below.

import IC "ic:aaaaa-aa";

actor {
public func random_bytes() : async Blob {
await IC.raw_rand();
};
};

In addition to the raw_rand method, Motoko offers a Random module for generating random numbers.