# Provable fairness & verification

Every BetPlug round commits to its randomness before any wager is placed (`api/openapi.yaml`). Operators, players, and auditors can replay any revealed round server-side via `GET /v1/rounds/{id}/verify` or offline using `@betrail/verifier`, the BetPlug Fairness Verifier web app, or standard SHA/HMAC primitives in any language.

## 1. Commit-reveal seed lifecycle

Each `(player_ref, game)` holds a `SeedState` (`GET /v1/players/{player_ref}/seeds/{game}` or `GET /v1/session/seeds`):

- **`current` (`SeedPairCommitted`):** `{ server_seed_hash, client_seed, nonces_used }`. `server_seed_hash` is lowercase hex `SHA-256(ascii(server_seed))` over the 64-character lowercase hex server seed (never hex-decoded 32 bytes).
- **`next` (`SeedPairCommitted`):** Pre-committed next server seed hash plus the player's chosen next `client_seed` (`PUT /v1/players/{player_ref}/client-seeds/{game}`).
- **`previous` (`SeedPairRevealed | null`):** After rotating (`POST /v1/players/{player_ref}/seeds/{game}/rotate` with an empty body), reveals `server_seed` alongside `server_seed_hash`, `client_seed`, and `nonces_used`.

> **Security:** Never trim or Unicode-normalize `client_seed` (`3..64` raw UTF-8 bytes, no C0/DEL/C1 controls or unpaired surrogates). NFC `"ñ"` (`c3 b1`) and NFD `"n\u0303"` (`6e cc 83`) hash to completely different outcomes. When displaying untrusted `client_seed` or `player_ref` values to humans, escape bidirectional overrides (`U+202A..U+202E`, `U+2066..U+2069`) and zero-width characters (`U+200B..U+200F`, `U+FEFF`).

### Seed rotation & `GET /v1/rounds/{id}/verify` rules

1. **Rotation blocked while unfinished (`409 round_open`):** Rotating while any round on the current pair is `reserved`, `debiting`, `open`, or has an unresolved placement returns `409 round_open` so an active round's seed never leaks mid-play.
2. **Pre-reveal check (`409 seed_not_revealed`):** Calling `/verify` before rotating returns `409 seed_not_revealed`.
3. **Server replay verdict (`200`):** Once rotated, `/verify` replays every step from the stored `engine.Record` (`v: 1`) and returns HTTP `200` `{ result: "ok", record }` — or `{ result: "verify_mismatch", detail, record }` (a mismatch is always a `200` verdict, never masked as a `5xx`). Verify `record.tables` SHA-256 fingerprints against the published game paytable and confirm `steps[0].outcome.trace.from === 0` with contiguous `trace.from`/`trace.to` across steps.

### Pre-draw vs post-draw `void` rounds

Nonces are reserved atomically **before** `engine.Open` and wallet debit, so failed attempts never reuse a nonce and may leave gaps:

| Void class | Trigger | Stored `record` | `GET /v1/rounds/{id}/verify` after rotation |
|---|---|---|---|
| **Post-draw `void`** | `debit_refused` or `debit_unknown` (wallet declined or timed out after draw) | Contains `record.steps[0]` | **`200` `{ result: "ok", record }`** — proves voiding never cherry-picked outcomes |
| **Pre-draw `void`** | `persist_error` or `engine_error` during `Open` (before any draw recorded) | Empty `{}` (`0` steps) | **`409 closed`** (`"This round voided before any draw recorded an outcome."`) — audit via `GET /v1/rounds/{id}` + rotated seed state |

## 2. RNG streams across the catalog

> **Warning:** BetPlug preserves five exact legacy RNG recipes alongside `FairRandom` and live reverse hash chains. Never substitute one game's RNG or rounding rule for another.

| `record.stream.kind` | Games | Digest construction (`server_seed` = 64 ASCII hex chars) | `trace` counter |
|---|---|---|---|
| `dice-sha512` | `dice` (`DICE`) | Plain `SHA-512(server_seed + ":" + client_seed + ":" + nonce)` (128 lowercase hex chars) | digests (`0..1`) |
| `hmac-nonce` | `limbo`, `roulette`, `diamonds` | `HMAC-SHA256(key = ascii(server_seed), msg = client_seed + ":" + nonce)` (32 bytes, **no** `:cursor`) | digests (`0..1`) |
| `plinko-hmac` | `plinko` (`PLINKO`) | `HMAC-SHA256(key = ascii(server_seed), msg = client_seed + ":" + nonce + ":" + c)` (`c = 0` for 8 pins; `c = 0, 1` for 9..16 pins) | digests (`1` or `2`) |
| `fairrandom` | All other Instant, Stateful, Originals Slots & `stack-o-pass` | `HMAC-SHA256(key = ascii(server_seed), msg = client_seed + ":" + nonce + ":" + cursor)` (8 big-endian `uint32` words/block) | `u32` words |
| Reverse `SHA-256` hash chain | Shared live shows (`trapdoor`, `kombat-multiplayer`, `crash`, `meme-trade`) | `link_{k} = SHA-256(ascii(link_{k+1}))` anchored at `s_0` + external public block `salt` | per-show `FairRandom` |

### Legacy recipe 1 — `DICE` (`dice-sha512`)

1. **Multiplier & paytable:** `chance` in `"0.01".."94.05"` (`W = chance * 100` in `1..9405`), `P = floor(950_000_000 / W)` in `10^-5` units (`W = 4798` -> `"1.97999"`). Paytable fingerprint: `7c145a94276eb256705c4c6d326824f70891fbc1120b33eea0433f432f702b4e`.
2. **Roll (`0..9999`):** Compute `H = hex(SHA-512("${server_seed}:${client_seed}:${nonce}"))`. Scan 25 windows `k = 0..24` of 5 hex chars (`H[5k .. 5k+5]`); the first value `< 1_000_000` is `lucky`. If all 25 are `>= 1_000_000`, take the 3-hex tail `parseInt(H.slice(125, 128), 16)` (`0..4095`). Then `roll = lucky % 10_000`.
3. **Settlement:** `"under"` wins iff `roll < W`; `"over"` wins iff `roll >= 10_000 - W`. Winning profit in atoms for stake `b` and max-profit cap `C`: `profit = min(floor(b * P / 100_000) - b, C)`, `payout = b + profit`.

### Legacy recipe 2 — `LIMBO` (`hmac-nonce`, 12-decimal `bcdiv` trap)

- Compute `D = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}")` (no `:cursor`).
- From the first 4 bytes `b0, b1, b2, b3`, compute the exact 12-decimal truncated byte sum:
  ```text
  S = floor(b0 * 10^12 / 256) + floor(b1 * 10^12 / 65536) + floor(b2 * 10^12 / 16777216) + floor(b3 * 10^12 / 4294967296)
  roll = floor(S / 10^6)                     // 0 .. 999,999
  crash_hundredths = floor(97_000_000 / (roll + 1))
  ```
- **Critical `bcmath-12` trap:** Never replace `floor(S / 10^6)` with `floor(u * 10^6 / 2^32)` — per-byte 12-decimal truncation differs at **4,224** values of `u`! Wins iff `crash_hundredths >= target_hundredths` (`101..100_000_000`, i.e. `1.01x`..`1000000.00x`).

### Legacy recipe 3 — `ROULETTE` (`hmac-nonce`)

- Compute `D = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}")` and `S` from `D[0..3]`. Pocket `spin = floor(37 * S / 10^12)` (`0..36`, proven identical to `floor(37 * u / 2^32)`).
- Two-floor settlement over total stake `B` and winning-chip return sum `W`: `q8 = floor(W * 10^8 / B)`, `gross = floor(B * q8 / 10^8)`, capped at `B + max_profit_atoms`.

### Legacy recipe 4 — `DIAMONDS` (`hmac-nonce`)

- Compute `D = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}")`. Read the first 20 bytes as 5 groups `g = 0..4` (`u_g = uint32be(D[4g..4g+4])`): `gem_g = floor(7 * u_g / 2^32)` (`0..6`).
- Sorted colour counts map to the 7 canonical hands: `[5]` -> `ALL_DIAMONDS` (`40x`), `[4,1]` -> `FOUR_DIAMONDS` (`5x`), `[3,2]` -> `THREE_DIAMONDS_TWO_DIAMONDS` (`4x`), `[3,1,1]` -> `THREE_DIAMONDS` (`3x`), `[2,2,1]` -> `TWO_DIAMONDS_TWO_DIAMONDS` (`2x`), `[2,1,1,1]` -> `TWO_DIAMONDS` (`0.1x`), `[1,1,1,1,1]` -> `NOTHING` (`0x`).

### Legacy recipe 5 — `PLINKO` (`plinko-hmac`)

- Compute `D_c = HMAC-SHA256(ascii(server_seed), "${client_seed}:${nonce}:${c}")` for `c = 0 .. Math.floor((pins + 7) / 8) - 1` (`1` digest for `8` pins, `2` digests `D_0 || D_1` for `9..16` pins).
- Concatenate bytes `B`. Pin `i` (`0..pins-1`) steps right (`1`) iff `B[4 * i] >= 128`. `bucket = sum(step_i)` (`0..pins`) indexes the `(pins, risk)` paytable.

### `FairRandom` cursor stream

- **`FairRandom` (`HMAC-SHA256(server_seed, client_seed:nonce:cursor)`):** Default byte stream across all other Instant games (`PACKS`, `RANGEDICE`, `WHEEL`, `DRILL`, `SLIDE`, `CASES`, `BARS`, `KENO`, `DARTS`, `TAROT`, `BACCARAT`, `KABOOM`, `TILT`), every Stateful Session game (`CHICKEN`, `PUMP`, `MINES`, `TOWERS`, `BLACKJACK`, `HILO`, `SNAKES`, `FLIP`, `RPS`, `MOLES`, `VIDEOPOKER`, `SKYRUSH`, `DEADSHOT`, `KOMBAT`, `STACKPACKS`), every Originals Slot (`GRIMOIRE`, `PHARAOH`, `SHOGUN` — one nonce per paid spin including bonus rounds), and `STACKOPASS` table hands.
- Primitives: `Int(n) = (u * n) >> 32` (for games like `mines`, `towers`, `blackjack`, `snakes`); exact rejection `Uniform(n, maxDraws)` (rejecting `u >= n * floor(2^32 / n)` into `trace.rejected` for `baccarat`, `video-poker`, `moles`, `darts`, `hilo`, `stack-packs`, `trapdoor`, and all Originals Slots); `SuffixedBlock(cursor, k)` (`hilo` rehash when all 8 words reject); splice Fisher-Yates `PickUnique(n, k)` / `Shuffle(n)`; and `AlignToCursor()` advancing to the next 8-word boundary.

### Live hash chains vs `stack-o-pass` per-player seeds

- **Shared live shows (`trapdoor`, `kombat-multiplayer`, `crash`, `meme-trade`):** Pre-commit a reverse `SHA-256` chain (`SHA-256(ascii(seed)) === commit`, walking back to terminal anchor `s_0`) salted by an external public block beacon (`salt_source`, e.g. `"bitcoin:<height>"`) announced before betting opens. Any unplayed link is broadcast via `skipped_link`. Seed derivation: `trapdoor` uses `Client = "trapdoor:" + salt, Nonce = gate`; `kombat-multiplayer` uses `Client = salt, Nonce = index`; `crash` uses `Client = "crash:" + salt, Nonce = index`; `meme-trade` uses `Client = "meme-trade:" + salt, Nonce = index`.
- **Per-operator live tables (`stack-o-pass`):** Uses **each player's own `FairRandom` seed pair** (not a shared show hash chain), verified after the player rotates their seed pair.

> **Tip:** All catalog games are mounted and served across `sandbox` and `live` (`404 unknown_game` applies only to unrecognized slugs; `409 not_offered` applies to disabled brand games, missing live hourly FX rates, live demo launches, or the `MINES (12, 11)` preset).

## 3. Standalone multi-recipe verifier (runnable sample)

Verify `SHA-256` server-seed commitments, `DICE` (`dice-sha512` including paytable fingerprint & 26th-read tail), `LIMBO` (`hmac-nonce` exact `bcmath-12` byte sum), and `PLINKO` (`plinko-hmac`) in pure `BigInt`:

```ts
import assert from "node:assert/strict";
import crypto from "node:crypto";

const TEN12 = 1_000_000_000_000n;
const B_POW = [256n, 65_536n, 16_777_216n, 4_294_967_296n] as const;

function diceMultiplierScaled(w: bigint): bigint {
  return 950_000_000n / w; // exact floor in 10^-5 units
}

function diceRollFromDigest(digestHex: string): { lucky: number; roll: number; windowsRead: number } {
  for (let k = 0; k < 25; k++) {
    const v = Number.parseInt(digestHex.slice(5 * k, 5 * k + 5), 16);
    if (v < 1_000_000) return { lucky: v, roll: v % 10_000, windowsRead: k + 1 };
  }
  const tail = Number.parseInt(digestHex.slice(125, 128), 16);
  return { lucky: tail, roll: tail % 10_000, windowsRead: 26 };
}

function limboCrashHundredths(serverSeed: string, clientSeed: string, nonce: number): bigint {
  const d = crypto.createHmac("sha256", Buffer.from(serverSeed, "ascii")).update(`${clientSeed}:${nonce}`, "utf8").digest();
  let s = 0n;
  for (let k = 0; k < 4; k++) s += (BigInt(d[k]!) * TEN12) / B_POW[k]!;
  const roll = s / 1_000_000n;
  return 97_000_000n / (roll + 1n);
}

function plinkoBucket(pins: number, serverSeed: string, clientSeed: string, nonce: number): number {
  const count = Math.floor((pins + 7) / 8);
  const bytes = Buffer.concat(
    Array.from({ length: count }, (_, c) =>
      crypto.createHmac("sha256", Buffer.from(serverSeed, "ascii")).update(`${clientSeed}:${nonce}:${c}`, "utf8").digest(),
    ),
  );
  let bucket = 0;
  for (let i = 0; i < pins; i++) if (bytes[4 * i]! >= 128) bucket += 1;
  return bucket;
}

// 1. DICE paytable fingerprint across all 9,405 targets
const fpLines = Array.from({ length: 9405 }, (_, i) => `${i + 1}|${diceMultiplierScaled(BigInt(i + 1))}`);
const fingerprint = crypto.createHash("sha256").update(`betrail-dice-paytable/1\n${fpLines.join("\n")}`, "utf8").digest("hex");
assert.equal(fingerprint, "7c145a94276eb256705c4c6d326824f70891fbc1120b33eea0433f432f702b4e");

// 2. DICE commitment + reference vector (roll = 3317, payout = 0.00019799 BTC) + 26th-read tail
const seed = crypto.createHash("sha256").update("betrail/l2/dice/boundary", "utf8").digest("hex");
const seedHash = crypto.createHash("sha256").update(seed, "ascii").digest("hex");
assert.equal(crypto.createHash("sha256").update(seed, "ascii").digest("hex"), seedHash);

const diceDigest = crypto.createHash("sha512").update(`${seed}:betrail-dice:1`, "utf8").digest("hex");
assert.equal(diceRollFromDigest(diceDigest).roll, 3317);
assert.equal((10_000n * diceMultiplierScaled(4798n)) / 100_000n, 19_799n);
assert.deepEqual(diceRollFromDigest(`${"f".repeat(125)}abc`), { lucky: 0xabc, roll: 2748, windowsRead: 26 });

// 3. LIMBO bcmath-12 & PLINKO plinko-hmac determinism checks
assert.ok(limboCrashHundredths(seed, "betrail-limbo", 0) >= 97n);
const b16 = plinkoBucket(16, seed, "betrail-plinko", 0);
assert.ok(b16 >= 0 && b16 <= 16);
```
