Make the draw a commit-reveal at a fixed, confirmed, quorum-agreed height with a public proof (B-73, RND-14 … RND-20, RND-33 … RND-37, DAT-61 … DAT-66, API-25, API-45, AUD-24 … AUD-27, AUD-37, ELC-15, SEC-56, ADR-24, ADR-25)

The seed was the hash of the first block seen after the close, so a miner holding tickets
could withhold blocks until one made them win, the active Electrum server could pick which
real block was used by not announcing another (a failed corroboration even moved the draw to
the next block), and the participant order was the server-only `broadcast_at` with no
tie-break, so nobody could recompute the result.

- Open: every round gets a 32-byte `server_seed`, stored only Fernet-encrypted with the
  master-xprv key (`server_seed_enc`), with its published `server_seed_hash`;
  `draw_confirmations` is copied from round_config. The plaintext column is written only by
  the reveal.
- Entering `drawing` (one transaction, `draw_committed` audit row): participants ordered by
  bet txid, each `draw_position`, `participants_hash` (sha256 of `txid:vout:address\n`
  lines; new `bet_vout`), `draw_height = tip_at_close + 1`. A tip of 0 keeps the round
  `closing` (`draw_baseline_tip_unknown`, once per round). All persisted, so a resumed draw
  reads rather than recomputes (the `_tick` branch itself is B-81).
- `_complete_draw` / `_wait_for_draw_block` replace `_wait_for_next_block`: wait for
  `draw_confirmations` blocks from `draw_height`, then `ElectrumListener.agreed_block_hash`
  asks every server, the active one included, for the header at that exact height (valid
  work, >= 2 other answers, strict majority of all); no agreement means the same height is
  asked again and `draw_header_corroboration_failed` is written once per distinct reported
  hash. `draw_stalled` now counts from the last tip advance, or from when the quorum started
  to fail. Seed = sha256(server_seed || block_hash || participants_hash), index = seed mod n.
- The winner, the seed and the reveal (`server_seed`, `winner_drawn` payload) are written in
  one transaction; a round closing with no participants reveals too. A round opened before
  this change (no commitment) is given a secret as it enters `drawing`.
- `GET /rounds/{id}/proof` (public, 404 `round_not_found`, translated in all 7 languages) and
  the new fields on `GET /rounds/current`; `draw_confirmations` in `/admin/config` and the
  /admin form; `server_seed_hash`/`draw_height` in `/admin/rounds`, never the secret.
- Alembic d3e8b15a7c42 (plain add_column / create_index, expression indexes untouched).
- Docs: the B-73 `*Stato:*`/`*Oggi:*` lines are gone, guides and CLAUDE.md describe the new
  draw. Ambiguities resolved in api.md: the proof's participants also carry `amount_sats`
  (RND-37 lists it); `seed` is decimal in the proof and hex in the audit row, as specified.

Tests changed because the spec changed: ElectrumListener.corroborate_header (asked only the
other servers about the block the active one announced) is replaced by agreed_block_hash and
its quorum tests ported; draw_winner takes the secret and the list fingerprint; the four
_wait_for_next_block scheduler tests are replaced by _wait_for_draw_block ones (fixed height,
confirmations, same-height retry, stall clock). New: test_draw_proof.py recomputes the winner
independently from the public proof, checks the plaintext secret is nowhere in the database,
the API or the log before the reveal, and that a second pass over a `drawing` round yields
the same winner. Mutation-checked: ordering by broadcast_at, an early reveal and asking the
tip instead of the draw height each fail tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-10-14 16:29:09 +02:00
1 parent 82d078e2d6
commit db24287ea5
42 files changed
+1715 -620

No files matched your search

+29 -58
View File
@@ -111,10 +111,9 @@ richiesta di scommessa (vedi
round successivo, mai per quello in corso.
*Codice:* `app/rounds/service.py:open_new_round_if_needed`, `app/rounds/service.py:round_deadline` ·
*Test:* `tests/unit/test_rounds_service.py`, `tests/unit/test_scheduler.py` (solo durata e pausa)
*Stato:* da implementare (B-95, B-73) · *Oggi:* sono fotografate solo durata
e pausa; costo della scommessa e `fee_address` sono letti dalla
configurazione a ogni uso, `draw_confirmations` e `max_round_pool_sats` non
esistono.
*Stato:* da implementare (B-95) · *Oggi:* sono fotografate durata, pausa e
`draw_confirmations`; costo della scommessa e `fee_address` sono letti dalla
configurazione a ogni uso, `max_round_pool_sats` non esiste.
- **[RND-06]** Pause e configurazione non pagabile bloccano solo l'apertura
del *prossimo* round: un round già in corso prosegue fino al pagamento con i
valori fotografati all'apertura ([RND-05]), quindi una modifica di
@@ -143,10 +142,8 @@ richiesta di scommessa (vedi
`GET /rounds/current` e dalla prova pubblica ([RND-37]) fin dall'apertura.
`server_seed` non è esposto da nessun endpoint, `/admin` compreso, finché il
vincitore non è salvato ([RND-18]).
*Codice:* `app/rounds/service.py:open_new_round_if_needed`, `app/api/routes/rounds.py:current_round` ·
*Test:* —
*Stato:* da implementare (B-73) · *Oggi:* il round non ha alcun segreto;
il seme dipende solo dall'hash del blocco.
*Codice:* `app/rounds/service.py:open_new_round_if_needed`, `app/rounds/draw.py:new_server_seed`, `app/wallet/keystore.py:encrypt_round_seed`, `app/api/routes/rounds.py:current_round` ·
*Test:* `tests/unit/test_rounds_service.py`, `tests/unit/test_draw_proof.py`
- **[RND-35]** **Un indirizzo del montepremi per round**: all'apertura il
round riceve un proprio indirizzo `m/84'/746'/0'/2/<round_id>`, salvato in
`rounds.pool_address` ed esposto da `GET /rounds/current`. Le scommesse del
@@ -241,20 +238,14 @@ giocata, ma il montepremi pubblicizzato non supera mai quello che verrà pagato.
Dopo il commit si invia una notifica SSE; da quel momento `participants_hash`
e `draw_height` sono pubblici ([RND-37]).
*Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw` ·
*Test:* — (nessun test porta `_close_and_draw` con partecipanti confermati fino a `drawing`)
*Stato:* da implementare (B-73, B-81) · *Oggi:* l'elenco è ordinato per
`broadcast_at` (che il pubblico non vede e che non ha spareggio) e resta
solo in memoria; non esistono `draw_position` né `participants_hash`.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw`, `app/rounds/draw.py:participants_hash` ·
*Test:* `tests/unit/test_scheduler.py`, `tests/unit/test_draw.py`, `tests/unit/test_draw_proof.py`
- **[RND-33]** L'altezza del blocco di estrazione è fissata all'ingresso in
`drawing` come `draw_height = tip_at_close + 1`, dove `tip_at_close` è
l'altezza della catena nota in quell'istante, e non cambia più: né per una
conferma mancata, né per un errore, né per un riavvio.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw` ·
*Test:* —
*Stato:* da implementare (B-73) · *Oggi:* si usa la punta vista al primo
controllo utile, che può essere un blocco successivo; dopo una
corroborazione fallita il riferimento avanza all'altezza rifiutata.
*Test:* `tests/unit/test_scheduler.py`
## 3 · Estrazione
@@ -290,12 +281,11 @@ flowchart TB
`draw_height + draw_confirmations − 1`. La condizione si controlla a ogni
passo dello scheduler, rileggendo dal database tutto ciò che serve
([RND-36]).
*Codice:* `app/rounds/scheduler.py:RoundScheduler._wait_for_next_block` ·
*Test:* `tests/unit/test_scheduler.py` (solo il comportamento attuale)
*Stato:* da implementare (B-73, B-81) · *Oggi:* si attende che la punta
superi l'altezza di riferimento e si usa la punta stessa, con una sola
conferma; per tutta l'attesa lo scheduler resta bloccato dentro
`_close_and_draw` e non esegue altri passi.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._wait_for_draw_block` ·
*Test:* `tests/unit/test_scheduler.py`
*Stato:* da implementare (B-81) · *Oggi:* la condizione si controlla dentro
`_close_and_draw`, che resta in attesa per tutta la durata senza che
`_tick` la riprenda: dopo un errore o un riavvio non riparte.
- **[RND-16]** **Header concordato**: raggiunte le conferme, l'header
all'altezza `draw_height` (e non la punta corrente) viene chiesto a tutti i
server configurati, attivo compreso, e lo si usa solo se il quorum concorda
@@ -308,12 +298,8 @@ flowchart TB
riportato dal server attivo per quell'altezza, non a ogni richiesta, così
un disaccordo che dura non scrive una riga ogni 5 secondi; la durata
dell'attesa resta visibile tramite `draw_stalled` ([RND-20]).
*Codice:* `app/rounds/scheduler.py:RoundScheduler._wait_for_next_block`, `app/electrum/listener.py:ElectrumListener.corroborate_header` ·
*Test:* `tests/unit/test_scheduler.py` (solo il comportamento attuale)
*Stato:* da implementare (B-73) · *Oggi:* si usa l'header della punta
ricevuto dal server attivo, chiedendo agli altri solo di confermarlo; se la
conferma manca, si attende un blocco ulteriore e si usa quello, così il
server attivo può scegliere quale blocco reale seminare tacendone uno.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._wait_for_draw_block`, `app/electrum/listener.py:ElectrumListener.agreed_block_hash` ·
*Test:* `tests/unit/test_scheduler.py`, `tests/unit/test_electrum_listener.py`
- **[RND-17]** **Algoritmo**: seme = sha256 della concatenazione di
`server_seed` (32 byte), hash del blocco a `draw_height` (32 byte,
nell'ordine mostrato dagli explorer) e `participants_hash` (32 byte),
@@ -321,10 +307,8 @@ flowchart TB
partecipanti; vincitore = il partecipante con `draw_position` uguale
all'indice. **Probabilità uguale per tutti**: ogni partecipante ha una e
una sola posizione nell'elenco, indipendentemente dall'importo.
*Codice:* `app/rounds/draw.py:draw_winner`, `app/rounds/scheduler.py:RoundScheduler._close_and_draw` ·
*Test:* `tests/unit/test_draw.py` (solo `draw_winner`; nessun test lato scheduler)
*Stato:* da implementare (B-73) · *Oggi:* seme = hash del blocco letto come
numero esadecimale, applicato all'elenco ordinato per `broadcast_at`.
*Codice:* `app/rounds/draw.py:draw_seed`, `app/rounds/draw.py:draw_index`, `app/rounds/draw.py:draw_winner`, `app/rounds/scheduler.py:RoundScheduler._complete_draw` ·
*Test:* `tests/unit/test_draw.py`, `tests/unit/test_draw_proof.py`
- **[RND-18]** **Verificabile**: in un'unica transazione del database il
round salva altezza e hash del blocco (`draw_block_height` = `draw_height`,
`draw_block_hash`), il seme (`seed_int`), il vincitore e il montepremi
@@ -339,11 +323,8 @@ flowchart TB
e ottenere lo stesso vincitore (vedi
[Come si verifica un'estrazione](#come-si-verifica-unestrazione)). Il primo
tentativo di pagamento parte subito dopo, nello stesso passo.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw` ·
*Test:* — (nessun test porta `_close_and_draw` con partecipanti confermati fino a `paying_out`)
*Stato:* da implementare (B-73) · *Oggi:* il calcolo non è ripetibile da
terzi: l'ordine dei partecipanti è per `broadcast_at`, noto solo al server
e senza spareggio fra valori uguali.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._complete_draw` ·
*Test:* `tests/unit/test_draw_proof.py`
- **[RND-19]** **Altezza sconosciuta alla chiusura**: se, quando il round
sarebbe pronto per `drawing`, l'altezza della catena non è nota (valore 0),
il round resta `closing` e il passaggio viene ritentato al passo
@@ -351,11 +332,8 @@ flowchart TB
`draw_height` si fissa solo su un'altezza realmente nota ([RND-33]). In
condizioni normali non accade, perché la connessione è resa disponibile solo
con l'altezza già nota ([ELC-07](connessione-electrum.md#3-caduta-rilevata)).
*Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw`, `app/rounds/scheduler.py:RoundScheduler._adopt_baseline_tip` ·
*Test:* `tests/unit/test_scheduler.py` (solo il comportamento attuale)
*Stato:* da implementare (B-73) · *Oggi:* il round entra comunque in
`drawing`, attende il primo header, ne adotta l'altezza come riferimento,
scrive `draw_baseline_tip_unknown` e aspetta un blocco successivo.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw` ·
*Test:* `tests/unit/test_scheduler.py`
- **[RND-20]** **Attesa lunga ma visibile**: l'attesa non ha un limite,
perché dipende davvero dall'arrivo dei blocchi. Ogni 60 secondi
(`_DRAW_PROGRESS_LOG_INTERVAL_SECONDS`) se ne registra l'avanzamento nei
@@ -365,11 +343,8 @@ flowchart TB
secondi finché la situazione dura. Durante `drawing`, `GET /rounds/current`
espone `draw_waiting_since` (l'orario di inizio dell'attesa); negli altri
stati il campo è assente.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._wait_for_next_block`, `app/api/routes/rounds.py:current_round` ·
*Codice:* `app/rounds/scheduler.py:RoundScheduler._wait_for_draw_block`, `app/api/routes/rounds.py:current_round` ·
*Test:* `tests/unit/test_scheduler.py`, `tests/unit/test_rounds_route.py`
*Stato:* da implementare (B-73) · *Oggi:* i 360 secondi si contano
dall'inizio dell'attesa; con 3 conferme richieste l'evento scatterebbe in
quasi ogni round.
- **[RND-36]** **Estrazione ripresa**: tutto ciò che l'estrazione usa
(`server_seed`, elenco con `draw_position`, `participants_hash`,
`draw_height`, `draw_confirmations`) è nel database dall'ingresso in
@@ -378,12 +353,11 @@ flowchart TB
precedente o un riavvio del server. La ripresa è idempotente: l'estrazione
ripresa dà sempre lo stesso vincitore, e un round già passato a
`paying_out` non viene estratto di nuovo.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._tick`, `app/rounds/scheduler.py:RoundScheduler._close_and_draw` ·
*Test:* —
*Stato:* da implementare (B-81) · *Oggi:* elenco dei partecipanti e altezza
di riferimento esistono solo in memoria e `_tick` salta i round in
`drawing`: dopo un errore o un riavvio il round resta in `drawing` per
sempre.
*Codice:* `app/rounds/scheduler.py:RoundScheduler._tick`, `app/rounds/scheduler.py:RoundScheduler._complete_draw` ·
*Test:* `tests/unit/test_draw_proof.py` (solo `_complete_draw`)
*Stato:* da implementare (B-81) · *Oggi:* tutto ciò che serve è nel database
e `_complete_draw` è idempotente, ma `_tick` salta i round in `drawing`:
dopo un errore o un riavvio il round resta in `drawing` per sempre.
- **[RND-37]** **Prova pubblica**: `GET /rounds/{id}/proof`, senza
autenticazione, restituisce per un round: `server_seed_hash` e
`pool_address` (dall'apertura); dall'ingresso in `drawing` l'elenco dei
@@ -392,11 +366,8 @@ flowchart TB
del vincitore `server_seed`, `draw_block_hash`, il seme, l'indice, il
vincitore e, quando esiste, il txid del pagamento. Un campo non ancora
disponibile è `null`. Il formato della risposta è in [api.md](api.md) (B-73).
*Codice:* `app/api/routes/rounds.py` ·
*Test:* —
*Stato:* da implementare (B-73) · *Oggi:* non esiste alcun endpoint di
prova; `GET /rounds/current` non espone partecipanti né dati
dell'estrazione, e i round chiusi non sono consultabili pubblicamente.
*Codice:* `app/api/routes/rounds.py:round_proof` ·
*Test:* `tests/unit/test_draw_proof.py`
### Come si verifica un'estrazione