Generate random numbers
This document explains how to generate cryptographically secure random encrypted numbers fully on-chain using the TFHE
library in fhEVM. These numbers are encrypted and remain confidential, enabling privacy-preserving smart contract logic.
Key notes on random number generation
On-chain execution: Random number generation must be executed during a transaction, as it requires the pseudo-random number generator (PRNG) state to be updated on-chain. This operation cannot be performed using the
eth_call
RPC method.Cryptographic security: The generated random numbers are cryptographically secure and encrypted, ensuring privacy and unpredictability.
Random number generation must be performed during transactions, as it requires the pseudo-random number generator (PRNG) state to be mutated on-chain. Therefore, it cannot be executed using the eth_call
RPC method.
Basic usage
The TFHE
library allows you to generate random encrypted numbers of various bit sizes. Below is a list of supported types and their usage:
Example: Random Boolean
Bounded random numbers
To generate random numbers within a specific range, you can specify an upper bound. The random number will be in the range [0, upperBound - 1]
.
Example: Random bumber with upper bound
Random encrypted bytes
For generating larger random values, you can use encrypted bytes. These are ideal for scenarios requiring high-precision or high-entropy data.
Example: Random Bytes
Security Considerations
Cryptographic security: The random numbers are generated using a cryptographically secure pseudo-random number generator (CSPRNG) and remain encrypted until explicitly decrypted.
Gas consumption: Each call to a random number generation function consumes gas. Developers should optimize the use of these functions, especially in gas-sensitive contracts.
Privacy guarantee: Random values are fully encrypted, ensuring they cannot be accessed or predicted by unauthorized parties.
Last updated