# Verifying a draw without trusting anyone

Closes audit item **M7** (block rule + independent script).

`scripts/verify-draw.mjs` is a single dependency-free file (Node ≥ 20) that **imports nothing from the
rest of the project**. It reimplements the rules on purpose: if the website and the verifier disagree, one of
them is wrong and it shows. The tests (`tests/verify-draw.test.mjs`) compare both implementations.

## Usage

```sh
node scripts/verify-draw.mjs --results https://polla21.org/results/NAVIDAD26.json \
     --sold sold.txt --tickets 1000 --confirmations 6
```

(`--confirmations` below 6 is raised to 6: see rule 4.)

**Everything from the public API, in one go (28/11/2026):**

```sh
node scripts/verify-draw.mjs --server https://polla21.org/api --draw 2511
```

It downloads `GET /api/results/2511`, `/api/results/2511/proof` (the signed result), `/api/commitment/2511` and
`/api/anchor/2511`, checks the **BIP340 signatures** of the commitment, the anchor and the result with its own code,
the block rule, the hashes of the list, that the result cites the commitment, and that each `.ots` is a SHA-256 stamp
of its event id. The **signed** result is the one verified; the plain JSON only has to agree with it. No keys are
asked for and nothing else of the website is needed.

Without network to the explorers (only signatures, hashes and stamps): add `--offline`. For saved files:

```sh
node scripts/verify-draw.mjs --results r.json --proof proof.json --commitment c.json --anchor a.json [--offline]
```

A draw with **no sales** verifies with `--offline` alone: an `n = 0` commitment and a signed `no-sales` result.

For agents: never parse the website's HTML. `GET /api/proof/<id>` returns, in one answer, the catalog entry, the
signed result, the commitment and the anchor (404 while there is no signed result); the walkthrough is in
[AGENT-BUY.md](AGENT-BUY.md) and the routes in [`/openapi.json`](../openapi.json).

| Option | Purpose |
|---|---|
| `--results` | File or `https` URL of the published JSON |
| `--sold` | List of sold numbers (JSON or one per line). Without it some checks stay as warnings |
| `--tickets` | Total numbers in the draw (sets the digits; if missing, the winner's are used) |
| `--api` | Extra Esplora explorer, repeatable. Ideally: your own node's |
| `--bci` | blockchain.info-style explorer that must also agree (`https://blockchain.info` by default; `off` skips it, not recommended) |
| `--anchor` | File or `https` URL of the anchor event (or of `/api/anchor/<id>`) when the results do not carry it |
| `--pubkey` | Lottery public key (hex) that must sign the anchor, commitment and result (the official one by default) |
| `--server`, `--draw` | The lottery API and a draw id: fetches results, signed result, commitment and anchor |
| `--commitment` | File or URL of `/api/commitment/<id>` (signed list of participants + its `.ots`) |
| `--proof` | File or URL of `/api/results/<id>/proof` (signed result + its `.ots`) |
| `--offline` | Ask no explorer: only signatures, hashes and stamps (incomplete for a block result) |
| `--lookback` | Earlier blocks checked (36 by default) |
| `--confirmations` | Required confirmations (by default, what the results say; never fewer than 6) |
| `--json` | Machine-readable output |

Exit: `0` verified · `1` does not add up · `2` could not be fully checked.

## The block rule, in writing

Each event has a `blockRule`, fixed in its signed pre-draw commitment (so it cannot change after the block).

**`anchor-v1` (current).** A header timestamp is set by the miner and may run up to 2 h ahead: a block stamped
21:40:01 can appear at 21:39, so «the first block with timestamp ≥ the draw time» could be known before a 21:40
draw. Not valid for a live draw. Instead:

1. **Anchor.** At the exact draw time T the server asks mempool.space, blockstream.info and blockchain.info for
   their tip, in parallel (at least 2 answers; retried every few seconds until T + 60 s). H = the **highest** tip:
   if any of them already had a block, that block cannot decide. With three answers, a tip more than 1 above both
   others (a broken explorer) is ignored and recorded in `ignored`; with only two answers more than 1 apart there
   is no anchor. The server signs a Nostr event (kind 1, tags `t=lottobtc-<id>`, `k=anchor`, `d=anchor:<id>`,
   content `{ v:1, type:"anchor", d, blockRule:"anchor-v1", drawAt:T, at, height:H, tips, hash }`,
   `created_at = at`), publishes it at once, stamps its id with OpenTimestamps and serves it at `/api/anchor/<id>`.
   It is immutable and never made before T. Valid only if **T ≤ at ≤ T + 60**.
2. **The block at height H+1 of the main chain decides** (numbers: H+2… while the number was not sold; Lotto:
   always H+1). If block H is later orphaned, the rule is still height H+1 of the main chain.
3. **Fallback** (no valid anchor: server down, fewer than 2 explorers, or a late anchor): the first block (lowest
   height) whose timestamp is **≥ T + 7200 s**. Nodes reject blocks more than 2 h ahead, so it cannot appear
   before T. The result comes later, but skipping the anchor gives nobody an advantage: at T neither block exists.
   The results say `fallback: true`.

The results carry `blockRule`, `anchor { height, at, lagS, event, ots }` (the whole signed event) or
`fallback: true`, and `firstBlock` (= H+1 with an anchor).

**`timestamp-v0` (old).** Results **without** `blockRule`, and events whose commitment was signed before this rule
existed, use it:

1. **The deciding block is the lowest height whose header timestamp is ≥ `drawDate`.**
   Block times are not monotonic (a block may carry a time earlier than the previous one),
   so «the first» is defined by height, not by time.
2. **Numbers:** the block hash, written in decimal; the winner is its last digits (as many as
   the highest number has). If that number was not sold, the **next block** is used, and so on.
3. **Lotto:** the combination comes only from the first block: chained SHA-256 from
   `POLLA-lotto-v1|<id>|<hash>`, 32 bits per step, with rejection sampling and no repeats.
4. The result is final with **at least 6 confirmations** (the block plus 5; decided 23/11/2026), or more
   if the draw asks for more. Before that nothing is published: the website only says what it is waiting for.
5. The time condition applies to the **first** block. If there were skips, the following blocks may carry
   an earlier time (Bitcoin allows it) and are still valid.

## What is checked

- **Anchor** (`anchor-v1`): the event's id and its BIP340 signature by the lottery key (own BigInt implementation,
  tested with the official BIP340 vectors), its tags and content, and **T ≤ at ≤ T + 60**. The deciding block must
  be H+1 (then the skipped ones). With `fallback: true`: the first block with timestamp ≥ T + 2 h.
- The block exists: **three different explorers** (mempool.space, blockstream.info and blockchain.info, plus any
  `--api`) must give the same hash for each height used. If one does not answer, nothing is verified.
- The 80-byte header gives that hash and **meets its proof of work**: an explorer cannot invent
  a block, only (in theory) serve an orphan one; that is why the explorers must agree.
- No block in the earlier window already met the draw time.
- Winner and confirmations.
- **Mandatory accounts**: `pot`, `revenue` and `house` as integers ≥ 0. If they are missing, the result stays
  «incomplete», never «verified». Prizes with an integer amount ≥ 0 and no repeated numbers; if there is a pot, the
  winner must have a prize; the prizes fit in the pot; `revenue − house = pot`.
- **The house does not exceed 5 %** of revenue. With the current rule (`costs` published) nothing is kept at sale: `house` must be 0 and `costs` at most 5 % (deducted from each prize when it is collected, see [COSTS.md](COSTS.md)). Old results with `houseShare` must add up.
- **Audit trail of skipped blocks** (numbers game): the results carry `firstBlock`, `blocksUsed`, `skipped`
  (`[{ height, hash, n }]`, every block before the winner, whose number was not sold) and `unsoldDrawn` (those
  numbers). The verifier recomputes the list from the chain and fails if the published one differs.
- With `--sold`: that the winner was sold, that the skipped blocks gave **unsold** numbers
  and that the 1st/2nd split matches the rules.

## Draws with no sales (since 28/11/2026)

If sales close and this server charged **no** invoice of that draw, it still signs, before the draw time, an
immutable commitment with `n: 0`, `sold: []` and the hashes of the empty list (`sha256("")`), publishes it like any
other (third-party relays, OpenTimestamps of the event id) and, at the draw time, a signed result with
`method: "no-sales"` (no block, no winner, no prizes) that cites it. An auditor can tell the two cases apart:

| What is public | Meaning |
|---|---|
| `GET /api/commitment/<id>` → 200 with `n: 0`, and a `no-sales` result | 0 tickets, **signed** before the draw time |
| `GET /api/commitment/<id>` → 404 after the close | the list was **never fixed** (no verifiable result) |

It only applies to draws that close after this change and before their draw time: draws already held without a
commitment (`PP`, `PRUEBA10-20261121`) are not committed afterwards, and keep answering 404.

## Publication: our own relay is never enough (since 28/11/2026)

A commitment, close notice, anchor, seed record or result only counts as **published** when relays on at least
`POLLA_MIN_COMMIT_RELAYS` (2) **different hosts** accepted it and **at least one is not ours** (a second endpoint
on `polla21.org` does not count as diversity). Until then the server retries the same signed event (every 5 min
after 10 attempts) and logs why; `GET /api/commitment|anchor/<id>` and `/api/results/<id>/proof` carry
`published: true|false`, and `/api/health` → `publication` says whether the configured relays can ever meet it.
The old shortcut (a one-relay list lowered the minimum to 1) is gone for the real relay publisher.

## The 60 s window of anchor-v1: what it does and does not close

With `anchor-v1` the anchor is valid only if `T ≤ at ≤ T + 60`; without it the fallback decides (the first block
whose timestamp is ≥ T + 2 h). **Not publishing the anchor is a one-time veto**: the operator cannot pick the
winning block, but an operator who signs the anchor at T, keeps it private, waits for block H+1 (≈ 10 min) and only
then decides whether to publish it (claiming `at ≤ T + 60`) or to let the fallback re-roll, has one re-roll.

What was analysed (28/11/2026), and why no new rule ships in this change:

- Every rule in which the deciding block depends on something the operator **reveals** (an anchor, a stamp, a
  notice of «missed anchor») keeps that veto: hiding it is always an option, and no public clock proves *when*
  the world first saw a Nostr event (`created_at` is set by the signer; relays do not sign their receive time).
- OpenTimestamps does not bind it tightly either: the calendars commit to Bitcoin minutes to hours later, often
  after H+1, and a stamp can also be made and kept private.
- The only rules without that veto are those where the operator reveals nothing: e.g. «the first block whose
  timestamp is ≥ T + 2 h», always (it cannot exist before T, because nodes reject blocks more than 2 h ahead).
  That is today's fallback. Making it the **only** rule removes the veto at the cost of results ~2 h later, and the
  anchor would stop deciding. That is a product decision for the owner, not a hardening detail: it is left as a
  documented option (a future `blockRule`, opt-in per event), not implemented halfway here.

What does bind it today, and how a third party checks an anchor on time versus a fallback:

- The rule is fixed in the commitment (`blockRule`), signed and stamped **before** T: it cannot be switched later.
- The anchor's height is not free: H must be the tip at T. `verify-draw` rejects an anchor whose H+1 already
  existed (`H ≤ anchor height`), and a page open at T compares the anchor with the tips the viewer's browser read.
- Anchor on time: the result says `anchor: { height, at, lagS, event }`; `verify-draw` checks the BIP340 signature,
  `T ≤ at ≤ T + 60` and that H+1 decides. Fallback: the result says `fallback: true`; `verify-draw` checks that the
  block is the lowest one with timestamp ≥ T + 2 h. A fallback in a draw whose anchor later appears on a relay is
  public evidence of withholding (two contradictory signed facts).
- The anchor is published at once to several relays (now: at least one third party) and stamped; watchers who log
  when they first saw it (relays, the website at T + 60) make a late publication visible, even if not provable.

## What it cannot check

- **That the server really published the anchor at its time.** The signature proves that the lottery signed
  «at = 21:40:03, latest block H», not when the world saw it. That is trust in the operator, mitigated by the
  immediate publication on Nostr, the OpenTimestamps seal of its id (it proves the event existed before a later
  Bitcoin block), and anyone watching live: a page open at the draw time reads the three tips itself and says
  whether they match the published anchor.

- **That the sold list is the real one.** A dishonest operator could remove a number from the list
  to skip a block. The signed pre-draw commitment (A5) solves that: the list is published and
  signed **before** the block exists. See [PRE-DRAW-COMMITMENT.md](PRE-DRAW-COMMITMENT.md).
- Lotto prizes (they depend on every combination played).
- That the prizes were paid.
- A `manual-test` result does not come from a block: the verifier always rejects it.

## Website and verifier

`common.js` (`firstBlockAfter`) looks **36** blocks back (`DRAW_LOOKBACK`), the same as the verifier's default
`--lookback`, so both pick the same block even with timestamps up to ~6 h ahead.

The website uses the same three explorers, with fewer requests: it reads each header of the window from
an Esplora explorer (each header must give its hash, meet its proof of work and point to the previous one),
and asks the **three** for the hash of the **last** block used and for their tip (the lowest one counts). As
every earlier block of the window is linked to that last one, an explorer cannot change any of them without
the other two noticing. If one does not answer, the page waits and says which; if they disagree, it stops
with an error (`confirmChain` in `common.js`, tests in `tests/explorers.test.mjs`).

## Results signed by the server (since 23/11/2026)

The server computes the result itself (`resultDraws` in `server/lib/core.mjs`, `POLLA_AUTO_RESULTS`, on by default
outside test mode). It does so only when:

- there is a signed pre-draw commitment that is not late, and the sales still give exactly its hashes;
- the draw block has at least 6 confirmations and the three explorers agree (the same `runDraw` / `runDrawLotto` as
  the website).

It then stores the result (immutable), signs it with the lottery key as a **kind 1** event (`k = results`,
`d = results:<id>`, not replaceable), publishes it to at least 2 relays and stamps the event id with OpenTimestamps.
The result names its commitment (`commitment`: event id), the explorers used and the confirmations required.
Read it in `/api/results/<id>`; the signed event and the stamp are in `/api/results/<id>/proof`.

## The website shows the signed result first (since 25/11/2026)

Before, the page only showed a result after computing it itself from the three explorers. When one of them did not
answer (for instance one that blocks the visitor's VPN), the draw box kept loading forever. Now:

1. The page asks our server for `/api/results/<id>/proof` and takes the result from the **signed event**, never from
   the unsigned copy. It must be signed by the lottery key (`checkSignedResult` in `common.js`: kind 1,
   `k = results`, `d = results:<id>`, `method: "block"`, the required confirmations). Before showing it, the page
   checks what needs no explorer (`signedSelfCheck`): each number is the last digits of its block hash, and the
   Lotto combination comes from the block hash. The result is shown at once: «✔ Result signed by the lottery», with
   a link to the event on Nostr.
2. Then the browser computes the result by itself as before and compares it (`signedMatches`): same block and same
   winner → «✔ Same result as the one signed by the lottery». A different result → a red warning, and «My numbers»
   stops marking winners. A match is remembered in this browser (`localStorage`, `polla-verified:<id>`), so the
   next visit shows «✔ Checked by this browser on …» without asking the explorers again.
3. A signed result that is not valid (another key, a bad signature, numbers that do not match their block hashes)
   is not shown: the page says why and computes the result by itself.

Every request to an explorer now has a time limit of 10 s (`EXPLORER_TIMEOUT_MS`), in the website and in the
server: an explorer that never answers counts as «not responding» instead of holding the page or the server's round.
Tests: `tests/signed-result.test.mjs`.

## Pending

- Test it against the real network (the tests use a simulated chain and the genesis block). Includes the
  blockchain.info answers (`/q/getblockcount`, `/block-height/<h>?format=json`), written from its public API documentation.
- ~~Publish the sold list next to the results, or link the signed commitment.~~ `--server` / `--commitment` (28/11/2026).
- Run `--server https://polla21.org/api --draw 2511` from a machine with access to the site (the tests use a
  simulated chain and a test key).
