/** * Provably fair deck order (DESIGN §4-1, §4-2, §4-5). This module is what the verifier page runs; keep it small and readable. * * seed 16 raw bytes (128 bits) from crypto.getRandomValues, shown and typed as 32 lowercase hex characters. * fingerprint first 8 lowercase hex characters of SHA-256 over the 16 raw seed bytes (not over the hex text), * shown before the first card ("Impronta del mazzo"). * daily seed first 16 bytes of SHA-256(utf8("scopa-daily-v1|YYYY-MM-DD")); Briscola uses "briscola-daily-v1|". * The date is the device's local date, passed in as text. * PRNG xoshiro128** (128-bit state). The state is the first 16 bytes of SHA-256("scopa-deck-v1|" + seed bytes); * the domain prefix keeps the shown fingerprint from revealing any bit of the state. * shuffle Fisher–Yates from the last position down, each index drawn by rejection sampling (no modulo bias). * redeal a redeal (three kings on the opening table, `redealThreeKings`) keeps drawing from the same stream: * deck `n` is what n + 1 successive shuffles of the reference order give. * * Deal order from the 40-card order (index 0 = top, dealt first). "First" = the non-dealer, who leads: * Scopa 0-2 first player's hand, 3-5 dealer's hand, 6-9 table (face up); * then each later deal takes the next 6: 3 to the first player, 3 to the dealer (10-15, 16-21, … 34-39). * Briscola 0-2 first player's hand, 3-5 dealer's hand, 6 the face-up trump card (it goes under the stock and is * the last card drawn); 7-39 the stock, drawn in pairs, trick winner first. * * The deck depends on the seed alone: no level, score, player history or clock goes in (tested in shuffle.test.ts). */ import { FULL_DECK, type Card, type Seat } from './cards.ts'; import { fromHex, sha256, sha256Hex, toHex, utf8 } from './sha256.ts'; export const SEED_BYTES = 16; const DECK_DOMAIN = utf8('scopa-deck-v1|'); /** A fresh 128-bit seed from the platform's crypto RNG (Web Crypto: browsers, WebViews, Node ≥ 19). Never time or a counter. */ export function newSeed(): string { const b = new Uint8Array(SEED_BYTES); globalThis.crypto.getRandomValues(b); return toHex(b); } /** Seed of the "Mano del giorno": the same for everyone on that date and recomputable by hand (header above). */ export function dailySeed(ymd: string, game: 'scopa' | 'briscola' = 'scopa'): string { if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) throw new Error(`bad date: ${ymd}`); return sha256Hex(`${game}-daily-v1|${ymd}`).slice(0, SEED_BYTES * 2); } /** Seed (32 hex characters, any case, spaces ignored, or the 16 raw bytes) -> the 16 raw bytes. Throws on anything else. */ export function seedBytes(seed: string | Uint8Array): Uint8Array { const b = typeof seed === 'string' ? fromHex(seed.replace(/\s+/g, '')) : seed; if (b.length !== SEED_BYTES) throw new Error(`seed must be ${SEED_BYTES} bytes`); return b; } /** "Impronta del mazzo": the first 8 hex characters of SHA-256 over the 16 raw seed bytes. */ export function fingerprint(seed: string | Uint8Array): string { return sha256Hex(seedBytes(seed)).slice(0, 8); } /** First dealer of a match (DESIGN §3-3 C2): the CPU (seat 1) in the first-ever match, else the first bit of the match seed. */ export function firstDealer(matchSeed: string, firstEverMatch: boolean): Seat { return firstEverMatch ? 1 : ((seedBytes(matchSeed)[0] >> 7) as Seat); } /** xoshiro128** by Blackman and Vigna: returns a generator of uint32 values. */ export function xoshiro128ss(s0: number, s1: number, s2: number, s3: number): () => number { if ((s0 | s1 | s2 | s3) === 0) s0 = 1; // the all-zero state is the one fixed point; SHA-256 makes it unreachable anyway return () => { const r = Math.imul(rotl(Math.imul(s1, 5), 7), 9) >>> 0; const t = s1 << 9; s2 ^= s0; s3 ^= s1; s1 ^= s2; s0 ^= s3; s2 ^= t; s3 = rotl(s3, 11); return r; }; } function rotl(x: number, k: number): number { return (x << k) | (x >>> (32 - k)); } /** The uint32 stream for a seed. */ export function streamFor(seed: string | Uint8Array): () => number { const sb = seedBytes(seed); const msg = new Uint8Array(DECK_DOMAIN.length + sb.length); msg.set(DECK_DOMAIN); msg.set(sb, DECK_DOMAIN.length); const dv = new DataView(sha256(msg).buffer); return xoshiro128ss(dv.getUint32(0, true), dv.getUint32(4, true), dv.getUint32(8, true), dv.getUint32(12, true)); } /** * Uniform integer in [0, n) from a uint32 source, by rejection: values at or above the largest multiple of n below 2^32 * are thrown away and redrawn, so every result has exactly the same number of source values behind it. */ export function randBelow(next: () => number, n: number): number { if (!(n >= 1 && n <= 0x100000000 && Number.isInteger(n))) throw new Error(`bad range ${n}`); const limit = 0x100000000 - (0x100000000 % n); for (;;) { const x = next(); if (x < limit) return x % n; } } /** Fisher–Yates in place, from the last position down. */ export function fisherYates(arr: T[], next: () => number): T[] { for (let i = arr.length - 1; i > 0; i--) { const j = randBelow(next, i + 1); const t = arr[i]; arr[i] = arr[j]; arr[j] = t; } return arr; } /** The deck order for a seed (index 0 = top card, dealt first). `redeal` = how many redeals came before (0 for the first deal). */ export function deckFromSeed(seed: string, redeal = 0): Card[] { const next = streamFor(seed); const deck = FULL_DECK.slice(); for (let k = 0; k <= redeal; k++) fisherYates(deck, next); return deck; }