Provably Fair Casino
A casino back end where neither operator nor player can steer an outcome.
- Fintech
- Security & governance
- Role
- Architect and sole engineer
- Client
- Prospective licensed operator (unnamed)
- Timeline
- Aug - Sep 2026
- Status
- Prototype

- tests green against real Postgres and Redis
- 1,791
- tests green against real Postgres and Redis
- commits in 37 days
- 347
- commits in 37 days
- SQL migrations
- 36
- SQL migrations
- games, each priced in TypeScript and in SQL
- 10
- games, each priced in TypeScript and in SQL
- Dice settings checked at exactly 99% RTP
- 19,998
- Dice settings checked at exactly 99% RTP
The problem
'Provably fair' crypto casinos let a player check one bet after the fact, but the operator still controls the inputs. It picks the default client seed and when seeds rotate, and it can mint and discard seeds, skip nonces or refuse a draw behind an 'outage'. Every single bet still verifies under those attacks, so per-bet verification is not the property that matters: sequence and commitment integrity are.
Casino money paths are also a classic source of double-spend, overdraft, idempotency and deadlock bugs. The goal was a codebase an operator could buy, with security treated as named attacks and structural defences rather than happy paths.
Architecture
Commit before the block
At rotation the operator commits the seed hash and a future block height (tip+3). The seed is sealed under a per-seed KMS data key, and only one pending seed per player can exist.
- Service
- Data
- AI model
- External
Hard problems I solved
Removing every free variable from the operator
Per-bet verification still passes when an operator mints 50 seeds and keeps the best, aborts deniably, or swaps the block height. Design review found that last one: choosing among the last ~200 known blocks gave about 7.6 bits of hidden choice per rotation.
Approach. Three-stage commitment where each party commits after the one before it: seed hash and future height, then the block hash, then the player's seed. The height is bound inside the HMAC message, a partial unique index allows one pending seed per player, and the seed is irrevocable once the block exists. The verifier checks SHA256d(header) and the difficulty target instead of trusting two explorers that 'agree'.
Exact, float-free game maths
An early spec priced 10,001 outcomes against 10,000, silently giving 98.9901% RTP instead of 99%; two reviewers caught it. The widely copied bustabit crash formula turned out not to have flat RTP across targets.
Approach. Rejection sampling over a uint32 gives an exactly uniform 0-9999 roll, and the crash point is one integer division over a 52-bit draw. RTP is asserted exactly, with no tolerance, and every game's TypeScript price is checked against its SQL price over the whole draw space.
Exactly 99.00% over all 19,998 Dice settings. The bustabit formula (99.01% falling to 98.02%) stays in the suite as a negative control.
Money conservation enforced by Postgres, not app discipline
Double-spends, overdrafts and deadlocks are the classic failures of casino money paths, and code review alone does not prevent them.
Approach. One ledger_post() chokepoint granted only to the worker role. It locks user balance rows in ascending order (house rows excluded, since locking them caps a tenant at about 50 bets per second) and re-checks funds under lock. A deferred constraint trigger asserts every transaction sums to zero per currency at COMMIT, and evidence tables are append-only.
A real 40P01 deadlock was reproduced for the reversed lock order; the concurrency test asserts both that the correct order cannot deadlock and that the reversed order does.
A temp table that minted money
Deferred triggers fire at COMMIT under the session's search_path, where pg_temp is searched first and CREATE TEMP TABLE is granted to PUBLIC. A temp table named ledger_entries let an unbalanced insert commit: a balance went from 999,900 to 1,999,899. A shadow bets table also burned nonces silently.
Approach. search_path pinned to public, pg_temp on every trigger function, TEMPORARY revoked, and the warm-plan-cache case asserted in tests.
Green tests over a broken security model
SECURITY DEFINER functions under forced RLS could not write a single money row, yet all 272 tests passed: Testcontainers made the migration role a superuser, and superusers bypass RLS.
Approach. Migrations re-run as a NOSUPERUSER, NOBYPASSRLS role reproduced the failure. Per-table owner policies derived from pg_class.relowner fixed it, and a second test database now runs the whole migration set unprivileged.
Privilege separation for the operator money path
Review found the credit-reversal marker in a column that two player-facing roles could UPDATE. Both footholds were exploited end to end: a player balance went from 180 to 130.
Approach. The backoffice runs as a separate process on its own port, with a role that holds zero table privileges and reaches money only through definer functions. The marker moved to its own table, and a grant sweep test fails loudly if any HTTP-facing role gains a privilege.
Code
Rejection sampling instead of a float modulo, and multiplication instead of a shift that turns half of all draws negative. The browser verifier runs this byte-identical code.
export const OUTCOMES = 10_000
export const BUCKET = Math.floor(2 ** 32 / OUTCOMES) // 429_496
export const REJECT_AT = OUTCOMES * BUCKET // 4_294_960_000
export function mapDraw(x: number): number | null {
return x < REJECT_AT ? Math.floor(x / BUCKET) : null // rejection sampling: exactly uniform
}
export function drawAt(effectiveKeyHex: EffectiveKey, clientSeed: ClientSeed,
nonce: number, cursor: number): number {
const digest = hmac(sha512, utf8ToBytes(effectiveKeyHex),
utf8ToBytes(`${DOMAINS.roll}${clientSeed}:${nonce}:${cursor}`))
// `*` not `<<`: JS bitwise ops are signed 32-bit, so digest[0] << 24 goes NEGATIVE
return (digest[0]! * 2 ** 24) + (digest[1]! * 2 ** 16)
+ (digest[2]! * 2 ** 8) + digest[3]!
}
export function rollAt(effectiveKeyHex: EffectiveKey, clientSeed: ClientSeed,
nonce: number, startCursor = 0): RollResult {
assertRollInputs(effectiveKeyHex, clientSeed, nonce, startCursor)
for (let cursor = startCursor; cursor < startCursor + MAX_DRAW_ATTEMPTS; cursor++) {
const roll = mapDraw(drawAt(effectiveKeyHex, clientSeed, nonce, cursor))
if (roll !== null) return { roll, cursor }
}
throw new Error(`rollAt: ${MAX_DRAW_ATTEMPTS} consecutive rejections: indicates a bug`)
}create function assert_entries_balance() returns trigger
language plpgsql
set search_path = public, pg_temp
as $$
declare bad record;
begin
select le.transaction_id, le.currency, sum(le.amount) as s into bad
from ledger_entries le
where le.transaction_id = new.transaction_id
group by le.transaction_id, le.currency
having sum(le.amount) <> 0
limit 1;
if found then
raise exception 'ledger entries do not balance: transaction % currency % sums to %',
bad.transaction_id, bad.currency, bad.s;
end if;
return null;
end $$;
create constraint trigger entries_balance
after insert on ledger_entries
deferrable initially deferred
for each row execute function assert_entries_balance();-- Lock ONLY user rows, ascending by account_id. House/fee/bonus rows are excluded:
-- locking them serialises every bet of a tenant onto one row (~50/sec regardless of
-- hardware), and §4.3 permits them to go negative, so no invariant needs the lock.
select array_agg(distinct en.account_id order by en.account_id) into v_lock
from unnest(v_entries) en join balances b on b.account_id = en.account_id
where not b.allow_negative;
if v_lock is not null then
perform 1 from balances where account_id = any(v_lock)
order by account_id for update;
for r in select en.account_id, sum(en.amount) as d
from unnest(v_entries) en where en.account_id = any(v_lock)
group by en.account_id loop
if (select amount from balances where account_id = r.account_id) + r.d < 0 then
raise exception 'ledger_post: insufficient funds';
end if;
end loop;
end if;
...
-- NOT granted to api. A caller who chooses the entries chooses the amount.
grant execute on function ledger_post(uuid, jsonb) to worker;What I built
Fairness engine
- HMAC-SHA512 derivation with domain-tagged messages and rejection sampling for an exactly uniform roll
- Three-stage commitment: operator seed hash, then a future Bitcoin block, then the player's browser seed
- Server seeds sealed with AES-256-GCM envelope encryption and per-seed data keys from KMS
- Standalone verifier: one HTML file, zero network calls, re-derives every bet and checks block proof-of-work
Ledger and wallet
- Double-entry ledger with a single ledger_post() chokepoint and integer money end to end
- Idempotency gate, and reconciliation that freezes and reports but never repairs
- Reserve-then-settle bets whose win and loss paths run identical statement sequences
- Sweeper that settles abandoned rounds instead of refunding them
Games and player app
- Dice, Limbo, Crash, Mines, Plinko, Wheel, Roulette, Slots, Coin Flip and Hi-Lo
- Each game priced by a pure TypeScript module and a SQL function, cross-checked over the whole draw space
- Hi-Lo chained rounds: one stake rides several draws until cash-out or bust
- Physics-based animation checked frame by frame in headless Chromium
Security and operations
- Five least-privilege Postgres login roles, RLS forced with tenant and user isolation
- Operator API as a separate process with its own database role and SHA-256-digested keys
- Hash-chained per-tenant audit log written by triggers
- Merkle sealing and Bitcoin anchoring written and tested, not yet scheduled by the running app
Screens
Hi-Lo chained round: one stake rides each draw with a compounding multiplier until cash-out or bust. Balances are play BTC on a private test network (regtest).
Stack
Runtime
- Node 22
- TypeScript 5.7
- Fastify 5
- pnpm workspaces
Database
- PostgreSQL 16
- PL/pgSQL
- Forced row-level security
- Deferred constraint triggers
- Redis 7
Crypto
- @noble/hashes (HMAC-SHA512)
- AES-256-GCM envelope encryption
- KMS (LocalStack in dev)
- Bitcoin Core regtest
Front end
- Vanilla TypeScript
- Inline SVG
- Web Audio API
- Deterministic single-file bundler
Quality
- Vitest
- Testcontainers (real Postgres + Redis)
- Mutation sweeps
- Playwright frame audits
- ESLint boundary rules
How it was built
Built with an AI-native workflow: I directed the design (9 specs and 8 implementation plans, each through adversarial review) and owned acceptance, and Claude Code implemented: 304 of 347 commits carry its co-author trailer. Every chunk went plan, build, attack against real Postgres, fix, then a mutation sweep that disables each guard to prove a test goes red.
Built as a codebase for a prospective licensed operator who is not named. It has only run on a private Bitcoin test network (regtest) with play balances: no real money, no players, no licence.