# Hybrid snapshots (version 4)

Mixed physical/catalog packs use a version-4 wrapper with `source_mode: HYBRID`,
the existing version-1 or version-2 economics snapshot, and an ordered candidate
list. Each candidate commits its `source_mode`, identity, value and weight.
Catalog candidates additionally commit their frozen catalog snapshot.
Physical identities use `itm_…`; reusable identities use `catalog:<membershipId>`.
Historical versions 1–3 retain their exact canonical bytes.

The same deterministic weighted permutation is used. Physical claim failures
may advance the audited draw index; a reusable catalog candidate cannot be
skipped. Verification checks this restriction. Such fallback is conditional on
availability and does not preserve the original unconditional RTP.

# Provably Fair Pack Openings

Every mystery-pack opening made through the storefront or official API (`POST
/v1/packs/{id}/openings`) uses the same **provably fair** lifecycle: the outcome is fully
determined by values committed *before* you open, and you can reproduce every
pull yourself once the seed is revealed.

## The scheme

- **Server seed commitment.** Each pack runs under a *seed series*. When a
  series starts, the server generates a secret 32-byte `server_seed` and
  publishes `server_seed_hash = SHA-256(server_seed)` immediately — before any
  pack is sold under it. See `GET /v1/packs/{id}/fairness`.
- **Per-opening contribution.** After the series commitment is published, the
  server derives a unique contribution as
  `SHA-256("cc-opening-contribution/v1\n" + server_seed_hash + "\n" + source +
  "\n" + customer + "\n" + retry_key)`. It remains named `client_seed` in v1
  responses for wire compatibility. Request `client_seed` values are ignored;
  the contribution is fixed by the prior commitment and immutable request
  identity, so neither caller nor service can choose it after commitment.
- **Nonce.** Each committed opening burns one monotonically increasing `nonce`
  within its series.
- **Candidate commitment.** The exact table the draw ran over — item ids,
  USD values, and draw weights after the buy-in's value floor — is hashed at
  opening time and returned as `candidates_hash`. The full table is disclosed
  by `GET /v1/openings/{id}/verification` after the series' seed is revealed
  (publishing it live would leak the pack's hidden inventory).
- **Versioned economics evidence.** Legacy openings retain snapshot version 1
  and its original canonical JSON byte-for-byte. Advanced openings use snapshot
  version 2. Version 2 binds the immutable economics revision, machine
  generation, global revision pin, valuation/solver/fingerprint versions,
  targets, achieved metrics, exact positive-support card values and weights,
  valuation source/currency, and a claim-assumption digest.
  Both `GET /v1/openings/{id}/verification` and the authenticated admin audit
  export document `snapshot` as a union discriminated by `version`; version 1
  alone has `floor_cents`/`rtp_target`, while version 2 has
  `economics_mode`, `config`, `achieved`, and provenance-bearing candidates.
- **Atomic order record.** The series, nonce, contribution, candidate snapshot
  hash, exact snapshot, draw index, and result are inserted in the same database
  transaction as the pending order and its held card, while holding the series
  row lock. Series closure takes that same lock and refuses to reveal while an
  opening is pending. This happens before any wallet debit or hosted-payment
  session is started. A malformed or mismatched stored commitment fails closed.
- **Safe retries.** v1 POST requests support `Idempotency-Key` as before.
  Storefront pack checkout attempts require an `Idempotency-Key`; the server
  persists the response by authenticated customer, replays the exact response
  for the same payload, and rejects reuse with a different payload. Retry keys
  are also bound into the deterministic contribution; changing one creates a
  distinct attempt but cannot predict or steer an unrevealed series. Successful
  pack-mutation replay records do not expire independently of their permanent
  opening evidence.
- **Reveal.** When a series ends (supply exhausted, rotation, or manual), the
  `server_seed` is published on the fairness endpoint and every opening in
  the series becomes independently verifiable. A series is never revealed
  while an opening under it still awaits authoritative payment.

## The draw

1. Build a uniform float stream: for block = 0, 1, 2, …

   ```
   digest = HMAC-SHA256(key = server_seed, msg = `${client_seed}:${nonce}:${block}`)
   ```

   Each 32-byte digest yields eight big-endian uint32s; divide each by 2^32
   for floats in [0, 1). Floats are consumed in order.

2. Walk a weighted permutation of the committed candidate table (ordered by
   ascending internal item id before opaque public-id encoding): repeatedly draw the next candidate with
   probability proportional to its `weight` (without replacement), removing
   it from the pool. If all remaining weights are zero, fall back to a
   uniform pick: `floor(next_float × remaining_count)`. This zero-tail rule is
   retained only for version 1. Version 2 contains strict positive support and
   uses cumulative positive mass; a zero/non-finite weight makes the proof
   invalid instead of invoking a fallback.

3. The pull is the candidate at `draw_index` in that permutation — normally
   index 0. A `draw_index > 0` means a concurrent opening claimed one or more
   earlier picks a moment before; those cards are visible as *other*
   openings' pulls, so the skip itself is auditable.

The weights come from the same public odds solver as `GET
/v1/packs/{id}/odds` and the storefront — the fairness layer only replaces
the randomness source, never the odds.

For Advanced openings, public odds and checkout may use different inventory
snapshots. Public odds preserve anti-peek behavior; checkout excludes every
already-held membership and commits its private solved generation. Targets are
configuration, not a promise that they are currently achieved. The version-2
snapshot records both targets and achieved checkout metrics.

If a claim race makes the first committed candidate unavailable, the existing
permutation is walked forward and `draw_index` records the chosen position.
Randomness is never rerun and a newly valued candidate is never substituted.
Consequently a `draw_index > 0` is auditable but the realized race fallback is
not a fresh draw from the original one-draw marginal economics.

## Runnable verification snippet

After the series is revealed, fetch `GET /v1/openings/{id}/verification` and
run:

```js
// verify-opening.mjs — node verify-opening.mjs verification.json
import { createHash, createHmac } from "node:crypto";
import { readFileSync } from "node:fs";

const v = JSON.parse(readFileSync(process.argv[2], "utf8"));

// 1. The revealed seed matches the pre-sale commitment.
const hash = createHash("sha256").update(v.server_seed).digest("hex");
if (hash !== v.server_seed_hash) throw new Error("server seed hash mismatch!");

// 2. The candidate table matches its pre-reveal commitment.
const snapHash = createHash("sha256")
  .update(v.snapshot_canonical_json)
  .digest("hex");
if (snapHash !== v.candidates_hash) throw new Error("candidate table mismatch!");

// 3. Verify the deterministic contribution binding.
const contribution = createHash("sha256").update([
  "cc-opening-contribution/v1",
  v.server_seed_hash,
  v.source,
  v.customer,
  v.retry_key,
].join("\n")).digest("hex");
if (contribution !== v.client_seed) throw new Error("contribution binding mismatch!");

// 4. Rebuild the float stream.
function floatStream(serverSeed, clientSeed, nonce) {
  let block = 0, buf = Buffer.alloc(0), off = 0;
  return () => {
    if (off + 4 > buf.length) {
      buf = createHmac("sha256", serverSeed)
        .update(`${clientSeed}:${nonce}:${block}`)
        .digest();
      block += 1; off = 0;
    }
    const n = buf.readUInt32BE(off); off += 4;
    return n / 2 ** 32;
  };
}

// 5. Rebuild the weighted permutation.
function permutation(candidates, rng, version) {
  const pool = candidates.map((c) => ({ c, w: version === 1 ? Math.max(0, c.weight) : c.weight }));
  if (version === 2 && pool.some((p) => !Number.isFinite(p.w) || p.w <= 0))
    throw new Error("invalid Advanced positive support");
  const out = [];
  while (pool.length > 0) {
    const total = pool.reduce((a, p) => a + p.w, 0);
    let idx;
    if (total <= 0) idx = Math.floor(rng() * pool.length);
    else {
      let r = rng() * total;
      idx = pool.length - 1;
      for (let i = 0; i < pool.length; i++) {
        r -= pool[i].w;
        if ((version === 1 && r <= 0) || (version === 2 && r < 0)) { idx = i; break; }
      }
    }
    out.push(pool[idx].c);
    pool.splice(idx, 1);
  }
  return out;
}

const snap = JSON.parse(v.snapshot_canonical_json);
const rng = floatStream(v.server_seed, v.client_seed, v.nonce);
const perm = permutation(snap.candidates, rng, snap.version);
const expected = perm[v.draw_index].item;
if (expected !== v.result_item) throw new Error("pull does not reproduce!");
console.log("✔ verified: pull", v.result_item, "at draw_index", v.draw_index);
```

If any check throws, the opening was not fair — publish the verification
payload and hold us to it.

## Rollout and rollback

- Apply the additive fairness, entitlement, rate-limit, and storefront
  idempotency schema before serving the new code. Existing opening rows remain
  readable: their nullable `source` and `retry_key` fields identify them as
  historical records.
- Before rollout, grant every legitimate official-API key the customer
  entitlements it needs through the admin API-key entitlement endpoints. Do not
  restore the former caller-chosen-customer behavior as a compatibility
  shortcut.
- Current storefront clients send an `Idempotency-Key` for every pack checkout.
  Stale clients receive a clear 400 and must refresh; retries with the same key
  and payload receive the original response.
- Application rollback is code-only: leave the additive tables, columns, and
  indexes in place so openings created during the rollout remain auditable.
  Reverting or deleting fairness records, nonces, orders, or claimed inventory
  is not a supported rollback.
