/** * Deterministic seeded random numbers, JSON-serialisable so the state is persisted next to the game state (docs/09 §3) * and a whole game can be replayed and checked from its seed (docs/04 §5). * * New games (2026-10-11): ChaCha20 (RFC 8439) keyed by a 256-bit seed from the OS (`crypto.getRandomValues`). * It is a cryptographic generator: seeing any number of dice, cards or tiles tells nothing about the next ones * (sfc32 is fast but its state can be worked out from enough outputs). Games started before keep sfc32 (4-word * seeds/states), so their replays and saved games stay exactly the same. * * State layouts: sfc32 `[a, b, c, d]`; ChaCha20 seed `[k0..k7]`, state `[k0..k7, block, used, 0]`. */ export type Sfc32State = [number, number, number, number]; export type ChaChaSeed = [number, number, number, number, number, number, number, number]; export type ChaChaState = [number, number, number, number, number, number, number, number, number, number, number]; export type RngState = Sfc32State | ChaChaSeed | ChaChaState; export interface Rng { /** Float in [0, 1). */ next(): number; /** Unbiased integer in [0, maxExclusive). */ int(maxExclusive: number): number; /** Fisher–Yates shuffle, returns a new array. */ shuffle(arr: readonly T[]): T[]; } /** A fresh 256-bit seed from the operating system's secure random source. */ export function createSeed(): ChaChaSeed { const buf = new Uint32Array(8); crypto.getRandomValues(buf); return [...buf] as ChaChaSeed; } /** Pool of OS random words for `secureRandom` (one `getRandomValues` call per 256 numbers). */ const pool = new Uint32Array(512); let poolAt = pool.length; /** * Uniform float in [0, 1) with 53 random bits from the operating system's secure source (`crypto.getRandomValues`), * a drop-in for `Math.random` wherever the server picks something nobody should be able to predict: computer moves, * thinking times, room codes, computer ids (2026-10-11). Game dice/cards/tiles use the seeded ChaCha20 below. */ export function secureRandom(): number { if (poolAt + 2 > pool.length) { crypto.getRandomValues(pool); poolAt = 0; } const hi = pool[poolAt++]! >>> 5; // 27 bits const lo = pool[poolAt++]! >>> 6; // 26 bits return (hi * 67108864 + lo) / 9007199254740992; } export function seedToHex(seed: RngState): string { return seed.map((n) => (n >>> 0).toString(16).padStart(8, '0')).join(''); } /** 32 hex digits = an sfc32 seed (older games), 64 = a ChaCha20 seed. */ export function seedFromHex(hex: string): Sfc32State | ChaChaSeed { if (!/^([0-9a-f]{32}|[0-9a-f]{64})$/.test(hex)) throw new Error('invalid seed hex'); return Array.from({ length: hex.length / 8 }, (_, i) => parseInt(hex.slice(i * 8, i * 8 + 8), 16) >>> 0) as Sfc32State | ChaChaSeed; } const rotl = (x: number, n: number) => ((x << n) | (x >>> (32 - n))) >>> 0; /** ChaCha20 block (RFC 8439 §2.3) for `key`, block counter `counter`, nonce 0. Exported for the test vector. */ export function chachaBlock(key: readonly number[], counter: number, nonce: readonly number[] = [0, 0, 0]): Uint32Array { const init = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, ...key.map((k) => k >>> 0), counter >>> 0, ...nonce.map((n) => n >>> 0)]; const x = Uint32Array.from(init); const qr = (a: number, b: number, c: number, d: number) => { x[a] = (x[a]! + x[b]!) >>> 0; x[d] = rotl(x[d]! ^ x[a]!, 16); x[c] = (x[c]! + x[d]!) >>> 0; x[b] = rotl(x[b]! ^ x[c]!, 12); x[a] = (x[a]! + x[b]!) >>> 0; x[d] = rotl(x[d]! ^ x[a]!, 8); x[c] = (x[c]! + x[d]!) >>> 0; x[b] = rotl(x[b]! ^ x[c]!, 7); }; for (let i = 0; i < 10; i++) { qr(0, 4, 8, 12); qr(1, 5, 9, 13); qr(2, 6, 10, 14); qr(3, 7, 11, 15); qr(0, 5, 10, 15); qr(1, 6, 11, 12); qr(2, 7, 8, 13); qr(3, 4, 9, 14); } for (let i = 0; i < 16; i++) x[i] = (x[i]! + init[i]!) >>> 0; return x; } /** Mutable generator over a copy of `state`; read the advanced state back with `rng.state()`. */ export class SeededRng implements Rng { private a = 0; private b = 0; private c = 0; private d = 0; /** ChaCha20: key, current block number and words of it already used; null for sfc32. */ private key: number[] | null = null; private blockNo = 0; private used = 16; private block: Uint32Array | null = null; constructor(state: RngState) { if (state.length === 4) { [this.a, this.b, this.c, this.d] = state.map((n) => n >>> 0) as Sfc32State; } else if (state.length === 11) { this.key = state.slice(0, 8).map((n) => n >>> 0); this.blockNo = state[8] >>> 0; this.used = state[9]; } else throw new Error(`SeededRng: bad state length ${(state as number[]).length}`); } /** sfc32 seeds run a few warm-up rounds as recommended; ChaCha20 seeds start at block 0. */ static fromSeed(seed: Sfc32State | ChaChaSeed | RngState): SeededRng { if (seed.length === 8) return new SeededRng([...seed, 0, 0, 0] as ChaChaState); const rng = new SeededRng(seed); for (let i = 0; i < 12; i++) rng.nextUint32(); return rng; } state(): RngState { if (this.key) return [...this.key, this.blockNo, this.used, 0] as ChaChaState; return [this.a, this.b, this.c, this.d]; } nextUint32(): number { if (this.key) { if (this.used >= 16) { // This block is used up (also right after restoring a state saved at its end): move to the next one. this.blockNo = (this.blockNo + 1) >>> 0; this.used = 0; this.block = null; } this.block ??= chachaBlock(this.key, this.blockNo); return this.block[this.used++]!; } const t = (((this.a + this.b) >>> 0) + this.d) >>> 0; this.d = (this.d + 1) >>> 0; this.a = this.b ^ (this.b >>> 9); this.b = (this.c + (this.c << 3)) >>> 0; this.c = ((this.c << 21) | (this.c >>> 11)) >>> 0; this.c = (this.c + t) >>> 0; return t; } next(): number { return this.nextUint32() / 4294967296; } int(maxExclusive: number): number { if (!Number.isInteger(maxExclusive) || maxExclusive <= 0 || maxExclusive > 4294967296) { throw new Error(`rng.int: invalid bound ${maxExclusive}`); } // Rejection sampling to avoid modulo bias. const limit = 4294967296 - (4294967296 % maxExclusive); for (;;) { const x = this.nextUint32(); if (x < limit) return x % maxExclusive; } } shuffle(arr: readonly T[]): T[] { const out = arr.slice(); for (let i = out.length - 1; i > 0; i--) { const j = this.int(i + 1); const tmp = out[i]!; out[i] = out[j]!; out[j] = tmp; } return out; } }