Skip to main content

Random Number Generation

Inco Lightning provides on-chain encrypted random number generation through the e_rand function. This enables use cases like lotteries, games, fair distribution, and any application requiring unpredictable values.

Overview

FunctionDescriptionSignature
e_randGenerate encrypted random number(CpiContext, u8) -> Result<Euint128>
The generated random value is encrypted and cannot be predicted or known until decrypted by an authorized party.

Basic Usage

use anchor_lang::prelude::*;
use inco_lightning::cpi::accounts::Operation;
use inco_lightning::cpi::e_rand;
use inco_lightning::types::Euint128;
use inco_lightning::ID as INCO_LIGHTNING_ID;

pub fn generate_random(ctx: Context<GenerateRandom>) -> Result<()> {
    let cpi_ctx = CpiContext::new(
        ctx.accounts.inco_lightning_program.to_account_info(),
        Operation {
            signer: ctx.accounts.authority.to_account_info(),
        },
    );

    // Generate encrypted random number
    let random_value: Euint128 = e_rand(cpi_ctx, 0)?;

    ctx.accounts.account.random = random_value;
    Ok(())
}
The second parameter identifies whether the operand is ciphertext (0) or plaintext (1). Always pass 0 when working with encrypted handles.

Account Structure

#[derive(Accounts)]
pub struct GenerateRandom<'info> {
    #[account(mut)]
    pub authority: Signer<'info>,

    #[account(mut)]
    pub account: Account<'info, MyAccount>,

    /// CHECK: Inco Lightning program for encrypted operations
    #[account(address = INCO_LIGHTNING_ID)]
    pub inco_lightning_program: AccountInfo<'info>,
}

#[account]
pub struct MyAccount {
    pub random: Euint128,
}

Use Cases

Fair Lottery Selection

pub fn select_winner(ctx: Context<SelectWinner>) -> Result<()> {
    let cpi_ctx = CpiContext::new(
        ctx.accounts.inco_lightning_program.to_account_info(),
        Operation {
            signer: ctx.accounts.authority.to_account_info(),
        },
    );

    // Generate random value for winner selection
    let random_index: Euint128 = e_rand(cpi_ctx, 0)?;

    ctx.accounts.lottery.winner_index = random_index;
    Ok(())
}

Random Game Outcomes

pub fn roll_dice(ctx: Context<RollDice>) -> Result<()> {
    let cpi_ctx = CpiContext::new(
        ctx.accounts.inco_lightning_program.to_account_info(),
        Operation {
            signer: ctx.accounts.authority.to_account_info(),
        },
    );

    // Generate random dice roll
    let dice_result: Euint128 = e_rand(cpi_ctx, 0)?;

    ctx.accounts.game.last_roll = dice_result;
    Ok(())
}

Security Properties

  • Unpredictable: Random values cannot be predicted before generation
  • Encrypted: Results are encrypted and only visible to authorized parties
  • Verifiable: Decryption requires attestation from the covalidator network
The random value remains encrypted until decryption is requested. Ensure proper access control is set up before allowing decryption of random values in sensitive applications.