# SoldOut Coin Flip — verifiable protocol `soldout-coinflip/2`

This document is normative. Two independent implementations follow it and are
held to the same fixed test vectors:

- server: `server/coinFlip/coinFlip.protocol.js` (+ `coinFlip.transparency.js`, `coinFlip.proof.service.js`)
- public verifier: `verifier.mjs` (browser at verify.sold-out.com, and `verify-flip.mjs` on the command line)

A Coin Flip settles a live-show purchase at one of two agreed prices: the buyer
and seller agree a **heads** price and a **tails** price, the buyer picks a side,
the buyer's card holds the higher price, and the coin decides which price is
charged. This protocol makes that coin publicly checkable.

## 1. What is proven, and what is not

| Claim | How it is established | Trust needed |
|---|---|---|
| The outcome is exactly `f(commitment, drand round)` | Recomputed by anyone (§7) | None (SHA-256) |
| Every outcome input was fixed before the randomness existed | Rekor's signed integration time ≤ deadline < round time (§5, §6) | Rekor's clock and log operators; drand (below) |
| The randomness was unknowable to SoldOut in advance | drand BLS threshold signature for a *future* round (§6) | Fewer than the threshold of League of Entropy members collude |
| SoldOut did not keep several candidate commitments for one flip | One commitment per flip, signed with a dedicated key; every Rekor entry under that key must appear in the public ledger (§9) | Auditors run the audit; Rekor's search index is complete |
| The right amount was charged | **Not proven.** Settlement is reported by SoldOut (closing record, §8) | SoldOut, Stripe |

Cryptography does not make the whole system "fully secure", and it does not
prove payment correctness. It proves the result and its timing.

## 2. Encodings

- **Canonical JSON**: UTF-8; object keys sorted by code unit order at every
  level; no whitespace; strings as produced by `JSON.stringify`; numbers are
  non-negative safe integers only (no floats, no exponents); no `null`
  (absent members are omitted). All protocol strings are ASCII.
- **Hash**: SHA-256, lowercase hex unless stated.
- **Amounts**: integer minor units (cents). **Times**: unix seconds.
- **Signatures**: ECDSA P-256 with SHA-256 over the canonical bytes, ASN.1 DER,
  base64. Key id = SHA-256 of the public key's SPKI DER, hex.

## 3. Commitment

```json
{
  "protocol": "soldout-coinflip/2",
  "environment": "production | staging | development",
  "flip": "cf_<22 base64url chars>",
  "terms": { "currency": "usd", "heads": 70000, "tails": 90000 },
  "assignment": { "buyer": "<32 hex>", "buyerSide": "heads | tails", "seller": "<32 hex>" },
  "outcomeRule": "soldout-coinflip/2/outcome-msb",
  "beacon": {
    "network": "drand-quicknet",
    "chainHash": "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971",
    "publicKey": "83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a",
    "scheme": "bls-unchained-g1-rfc9380",
    "genesisTime": 1692803367,
    "period": 3,
    "round": 34187141
  },
  "publication": { "log": "rekor.sigstore.dev", "logId": "<hex>", "publishBy": 1795364783 },
  "publisher": { "keyId": "<hex>" },
  "issuedAt": 1795364771
}
```

- `flip` — 128 random bits, base64url, prefixed `cf_`. Never a database id.
- `assignment.buyer` / `seller` — per-flip pseudonyms:
  `HMAC-SHA256(key, "soldout-coinflip/2/participant" ‖ 0x00 ‖ role ‖ 0x00 ‖ flip ‖ 0x00 ‖ accountId)[0..16]`.
  The key is a server secret, so pseudonyms cannot be reversed or linked
  across flips; the app shows each participant their own reference.
- `beacon` — fixed to drand **quicknet** (pinned above). `round` is the first
  round at least *lead* seconds (default 12) after the commitment is made.
- `publication.log` — `rekor.sigstore.dev` for production, `rekor.sigstage.dev`
  (Sigstore's staging log) for staging and development. A verifier rejects any
  other pairing, so test flips can never pass as production ones.
- `publication.publishBy` — `time(round) − margin` (default margin 4 s, protocol
  minimum **3 s**).

`commitmentHash = SHA-256(canonical bytes of the commitment)`.

Nothing in the commitment is secret and nothing secret affects the outcome.
There is **no server seed** and **no client seed**: drand is the only
randomness. (Protocol 1 used both; see §11.)

## 4. Time of a drand round

`time(round) = genesisTime + (round − 1) × period` (unix seconds).

## 5. Publication

SoldOut signs the canonical commitment with its publication key and submits a
Rekor `hashedrekord` (API v1) entry: `{hash: sha256:<commitmentHash>,
signature, publicKey}`. Rekor returns, and the proof keeps verbatim:

- `integratedTime` — when Rekor added the entry, by Rekor's clock;
- `signedEntryTimestamp` (SET) — Rekor's ECDSA signature over the canonical
  JSON `{"body","integratedTime","logID","logIndex"}`;
- `inclusionProof` — RFC 6962 audit path to a tree root, plus a signed-note
  checkpoint over that root.

Checks (all against the **pinned** Rekor key; fetching over HTTPS is not trusted):

1. The entry body is a `hashedrekord` for `commitmentHash`, carrying the
   commitment's signature and the publisher key.
2. The SET verifies; `logID = SHA-256(Rekor key SPKI DER)` equals the pinned log id.
3. `leaf = SHA-256(0x00 ‖ body)`; the audit path reaches `rootHash`
   (RFC 9162 §2.1.3.2); the checkpoint signature verifies and names the same
   size and root.
4. **Timing:** `integratedTime ≤ publishBy` and `publishBy ≤ time(round) − 3`.

Submitting the identical entry again is idempotent: Rekor answers `409` with
the original entry and its original time. A fresh `201` therefore proves no
earlier entry existed.

Pinned logs:

| log | log id | key |
|---|---|---|
| rekor.sigstore.dev | `c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d` | `MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==` |
| rekor.sigstage.dev | `d32f30a3c32d639c2b762205a21c7bb07788e68283a4ae6f42118723a1bea496` | `MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDODRU688UYGuy54mNUlaEBiQdTE9nYLr0lg6RXowI/QV/RE1azBn4Eg5/2uTOMbhB1/gfcHzijzFi9Tk+g1Prg==` |

**Why not OpenTimestamps alone.** A Bitcoin anchor can take hours to confirm, so
a pending OTS receipt or a later Bitcoin timestamp cannot show that publication
happened seconds before a round. Rekor's signed integration time can.

## 6. Beacon

For the committed `round` only: verify the BLS12-381 signature on G1
(`bls-unchained-g1-rfc9380`, DST `BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_`)
over `SHA-256(round as 8-byte big-endian)` with the pinned quicknet public key.
`randomness = SHA-256(signature)`. Verification uses
[@noble/curves](https://github.com/paulmillr/noble-curves) (audited,
maintained); the browser build is `vendor/noble-bls12-381.mjs`.

The round is published by drand at `time(round)`; because publication must be
logged at least 3 s before that (§5), the commitment provably predates the
randomness.

## 7. Outcome

```
digest  = SHA-256( ASCII("soldout-coinflip/2/outcome") ‖ 0x00 ‖ commitmentHash (32 bytes) ‖ randomness (32 bytes) )
outcome = (digest[0] & 0x80) == 0 ? "heads" : "tails"
charged = terms[outcome]
```

One bit of SHA-256 output: unbiased, and fixed the moment the round exists.

## 8. Decision rules (fixed in advance)

- **R1** If the commitment's Rekor entry is timely (`integratedTime ≤ publishBy`),
  the outcome of §7 is binding. SoldOut must apply it and may not cancel it.
- **R2** If the entry is late or absent, the flip is **void**: no outcome
  applies, the hold is released, nobody is charged. This depends only on
  timing, which is decided before the round exists, never on the outcome.
- **R3** After `publishBy`, SoldOut decides R1/R2 only from Rekor: it re-submits
  the identical entry (409 → original entry and time; 201 → none existed).
- **R4** If Rekor cannot be reached to decide, the flip stays *publication
  undetermined*, the hold stays, and SoldOut keeps asking. If still
  undecidable 6 days after the round (card holds last 7), the flip is voided
  with reason `publication_undetermined`.
- **R5** The beacon is fetched for the committed round only. Rounds are never
  substituted and flips are never re-rolled. If the round cannot be obtained
  within 6 days, the flip is voided with `beacon_unavailable`. (drand catches
  up missed rounds after an outage, so this is not expected.)
- **R6** A failed payment never changes the outcome. A transient Stripe error is
  retried with the same idempotency key; a definitive failure ends the flip as
  `payment_failed` with its outcome intact.

Every committed flip ends with one signed **closing record**, also logged in Rekor:

```json
{ "protocol": "soldout-coinflip/2", "environment": "...", "flip": "cf_...", "commitment": "<commitmentHash>",
  "event": "closed", "result": "outcome | void", "outcome": "heads | tails", "reason": "publication_late | publication_undetermined | beacon_unavailable",
  "settlement": "captured | payment_failed | not_charged", "closedAt": 0, "publisher": { "keyId": "..." } }
```

`settlement` is SoldOut's claim about money, not a proof. A verifier flags a
closing record that contradicts R1/R2.

## 9. One authoritative commitment per flip

- The server stores exactly one commitment per flip (unique index) and the flip
  id is inside it.
- The publication key is used **only** for Coin Flip documents, and every
  document it signs is listed in the public ledger
  `GET /api/public/coinflips/ledger`.
- `verify-flip.mjs --audit` lists every Rekor entry under that key straight
  from Rekor and checks that each is in the ledger and that no flip has two
  commitments. An undisclosed entry is evidence of misbehaviour.
- Remaining assumption: Rekor's search index (`/api/v1/index/retrieve`) is
  operated by Sigstore and is not itself covered by the Merkle proof; a full
  audit would scan the log.
- The buyer's app shows the commitment hash and round when the flip starts,
  before the round exists.

## 10. Proof bundle (`soldout-coinflip-proof/1`)

`GET /api/public/coinflips/<flip>` (no login, no app key), also the
downloadable file:

```
format, protocol, publicId, environment, verifyUrl,
context.productTitle            — reported by SoldOut, NOT part of the proof
commitment { document, hash, signature, publisherPublicKey }
commitmentPublication           — Rekor entry (§5) or null while pending
beacon { network, chainHash, round, signature, randomness } or null
closing { document, hash, signature, publisherPublicKey } or null
closingPublication              — Rekor entry or null
status { phase, terminal, publication, outcome, voidReason, settlement, updatedAt }
```

The bundle contains no names, emails, phone numbers, addresses, payment
references or internal account ids. `GET /api/public/coinflips/publisher`
returns the environment's publication key id.

## 11. Protocol 1 (`soldout-coinflip/1`, before November 2026)

`outcome = parity of the first hex digit of HMAC-SHA256(key=serverSeed, message=clientSeed)` (even → heads),
with `SHA-256(serverSeed)` committed before the flip. **Both seeds were
generated by SoldOut's server, nothing was published externally, and no
independent randomness was used.** The verifier checks only internal
consistency and never shows a protocol-1 flip as fully verified. Seeds are
disclosed only after the flip has ended.

## 12. Test vectors

`test-vectors/vectors.json` — canonical encoding, outcome derivation (both
sides), real drand beacons, legacy outcomes.
`test-vectors/v2-complete-development.json` — a complete real proof:
commitment logged in rekor.sigstage.dev (entry 57031641) 14 s before drand
quicknet round 34187141, which landed **heads**; closing record entry 57031645.

```
node verify-flip.mjs test-vectors/v2-complete-development.json --online \
  --publisher-key-id e63d12ad300f620da43c3aed45c29cad13e479157094247f40452083acac2dd3
```

## 13. Operational limits

- The proof records are append-only at the application level. That does not
  stop a database administrator; the Rekor entries are what make tampering
  detectable.
- A flip whose commitment never reached Rekor (R2/R4) is still listed in the
  ledger and on its public page.
- Timing defaults (lead 12 s, margin 4 s) may change between flips; each
  commitment carries its own round and deadline, and the 3 s minimum is fixed
  by this version.
