diff --git a/CLAUDE.md b/CLAUDE.md index e06245c..b55011f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin ## Project status -All 10 stages of the original build order are code-complete and unit-tested — 1109 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. +All 10 stages of the original build order are code-complete and unit-tested — 1120 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. Verified on mainnet with real money: registration + address derivation, deposit crediting (at the time, 1-conf; deposits now need `deposit_confirmations`), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only. @@ -61,7 +61,7 @@ PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+pr PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace) PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip -python -m pytest # all 1109 tests +python -m pytest # all 1120 tests python -m pytest tests/unit/test_hd.py # one file python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test ``` diff --git a/README.md b/README.md index a6d8230..3e8ad6e 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ python -m pytest # all tests python -m pytest tests/unit/test_hd.py # one file ``` -1109 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +1120 unit tests cover HD derivation, PSBT building, the Electrum client, bets, deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config, the pending-inclusive balance calculation, and the SSE push channel. No automated integration tests against a live Electrum connection — mainnet diff --git a/apps/lottery/proof.py b/apps/lottery/proof.py new file mode 100644 index 0000000..d6c9414 --- /dev/null +++ b/apps/lottery/proof.py @@ -0,0 +1,63 @@ +"""The public proof of a round's draw (WEB-12, RND-37): everything anyone needs to recompute the winner, and the +recomputation itself. It carries no username and no account data — participants appear only under the pseudonymous +address of the public draw list (DAT-65) — and a field not yet available is `None`, never invented.""" + +from typing import Any + +from plm_engine.draw import draw_index, draw_seed, participants_hash, server_seed_commitment + +from .addresses import participant_address +from .format import plm_text +from .models import Participation, Round + + +def round_proof(round_: Round) -> dict[str, Any]: + drawn = round_.participants_hash is not None # the list is fixed once the round enters `drawing` (RND-14) + rows = [] + if drawn: + participants = (Participation.objects.filter(round=round_, draw_position__isnull=False) + .select_related("user").order_by("draw_position")) + rows = [{"position": p.draw_position, "txid": p.bet_txid, "vout": p.bet_vout, + "address": participant_address(p.user), "amount_sats": p.bet_amount_sats} for p in participants] + + data: dict[str, Any] = { + "round_id": round_.pk, "status": round_.status, + "server_seed_hash": round_.server_seed_hash, "pool_address": round_.pool_address or None, + "participants": rows, "participants_hash": round_.participants_hash, + "draw_height": round_.draw_height, "draw_confirmations": round_.draw_confirmations, + "server_seed": round_.server_seed, "draw_block_hash": round_.draw_block_hash, + "seed": None, "index": None, "winner_address": None, "winner_position": None, + "pool_amount_sats": round_.pool_amount_sats, "winner_amount_sats": round_.winner_amount_sats, + "fee_amount_sats": round_.fee_amount_sats, + "payout_txid": None, "payout_confirmed": False, + "checks": None, + } + if round_.pool_amount_sats is not None: + data["pool_text"] = plm_text(round_.pool_amount_sats) + if round_.winner_amount_sats is not None: + data["winner_amount_text"] = plm_text(round_.winner_amount_sats) + if round_.payout_transaction_id is not None: + payout = round_.payout_transaction + data["payout_txid"] = payout.current_txid + data["payout_confirmed"] = payout.status == "confirmed" # confirmed only when it is (WEB-12) + + if round_.server_seed and round_.draw_block_hash and drawn and rows: + seed = draw_seed(round_.server_seed, round_.draw_block_hash, round_.participants_hash) + index = draw_index(seed, len(rows)) + data.update(seed=f"{seed:064x}", index=index, winner_position=index, winner_address=rows[index]["address"]) + data["checks"] = _checks(round_, rows, index) + elif round_.server_seed: # closed with nobody in it: the secret is revealed, there is nothing to draw + data["checks"] = {"commitment": server_seed_commitment(round_.server_seed) == round_.server_seed_hash} + return data + + +def _checks(round_: Round, rows: list[dict[str, Any]], index: int) -> dict[str, bool]: + """The recomputation the page shows, done with the same primitives anyone can reimplement from the guide.""" + stored_winner = (Participation.objects.filter(round=round_, user_id=round_.winner_id).values_list("draw_position", flat=True) + .first() if round_.winner_id else None) + return { + "commitment": server_seed_commitment(round_.server_seed) == round_.server_seed_hash, + "order": [r["position"] for r in rows] == list(range(len(rows))) and [r["txid"] for r in rows] == sorted(r["txid"] for r in rows), + "fingerprint": participants_hash([(r["txid"], r["vout"], r["address"]) for r in rows]) == round_.participants_hash, + "winner": stored_winner == index, + } diff --git a/apps/web/public_views.py b/apps/web/public_views.py new file mode 100644 index 0000000..55631fd --- /dev/null +++ b/apps/web/public_views.py @@ -0,0 +1,48 @@ +from django.core.paginator import Paginator +from django.http import JsonResponse +from django.shortcuts import get_object_or_404, render +from django.views.decorators.cache import never_cache + +from apps.lottery.format import plm_text +from apps.lottery.models import LotteryConfig, Round +from apps.lottery.proof import round_proof +from apps.lottery.rules import WINNER_PERCENT + +PAGE_SIZE = 20 + + +def results(request): + """Concluded rounds, newest first (WEB-12): who won is only ever an address of the public draw list.""" + rounds = Round.objects.filter(status=Round.Status.CLOSED).order_by("-id") + page = Paginator(rounds, PAGE_SIZE).get_page(request.GET.get("pagina")) + rows = [{"id": r.pk, "closed_at": r.closed_at, "pool_text": plm_text(r.pool_amount_sats or 0), + "winner_text": plm_text(r.winner_amount_sats) if r.winner_amount_sats else "", + "has_winner": r.winner_id is not None} for r in page] + return render(request, "web/results.html", {"rows": rows, "page": page}) + + +@never_cache +def result_detail(request, round_id): + round_ = get_object_or_404(Round.objects.select_related("payout_transaction"), pk=round_id) + return render(request, "web/result_detail.html", {"p": round_proof(round_), "round": round_}) + + +@never_cache +def result_proof_json(request, round_id): + round_ = get_object_or_404(Round.objects.select_related("payout_transaction"), pk=round_id) + return JsonResponse(round_proof(round_)) + + +def _terms(): + config = LotteryConfig.get() + return {"bet_text": plm_text(config.bet_amount_sats), "winner_percent": WINNER_PERCENT, + "platform_percent": 100 - WINNER_PERCENT, "duration_minutes": max(1, config.round_duration_seconds // 60), + "confirmations": config.draw_confirmations} + + +def guide(request): + return render(request, "web/guide.html", _terms()) + + +def rules(request): + return render(request, "web/rules.html", _terms()) diff --git a/apps/web/static/web/site.css b/apps/web/static/web/site.css index 6f947fa..3098900 100644 --- a/apps/web/static/web/site.css +++ b/apps/web/static/web/site.css @@ -122,3 +122,14 @@ input[type=text].address { width: auto; } .movements td::before { content: attr(data-label); color: var(--muted); font-size: .9rem; text-align: left; } .movements td.num { text-align: right; } } + +/* A8 — public results, guide, rules */ +.break { overflow-wrap: anywhere; word-break: break-all; } +.facts dt { color: var(--muted); font-size: .9rem; margin-top: .8rem; } +.facts dd { margin: .15rem 0 0; } +.checks li { padding: .35rem 0 .35rem 1.6rem; position: relative; } +.checks li::before { position: absolute; left: 0; font-weight: 700; } +.checks li[data-ok="1"]::before { content: "✓"; color: var(--ok); } +.checks li[data-ok="0"]::before { content: "✗"; color: var(--error); } +.movements tr.winner td { font-weight: 600; } +.steps li, .rules li { margin-bottom: .7rem; max-width: 42rem; } diff --git a/apps/web/templates/web/base.html b/apps/web/templates/web/base.html index 8cbdea2..6f6a053 100644 --- a/apps/web/templates/web/base.html +++ b/apps/web/templates/web/base.html @@ -15,6 +15,9 @@ PLM Lottery Home + Risultati + Guida + Regole {% if user.is_authenticated %} {% with current=request.resolver_match.view_name %} Gioca diff --git a/apps/web/templates/web/guide.html b/apps/web/templates/web/guide.html new file mode 100644 index 0000000..e005c43 --- /dev/null +++ b/apps/web/templates/web/guide.html @@ -0,0 +1,13 @@ +{% extends "web/base.html" %} +{% block title %}Guida · PLM Lottery{% endblock %} +{% block content %} + Guida + Come si gioca, in quattro passi. I termini sono gli stessi che trovi nell'area giocatore. + + Registrati e accedi. Bastano nome utente e password: non chiediamo email. + Deposita. Dal portafoglio trovi il tuo indirizzo. I fondi compaiono «in conferma» e diventano spendibili solo dopo le conferme: l'accredito non è immediato. + Punta. La quota è {{ bet_text }}. Una puntata per round, con una schermata di conferma prima dell'invio. + Attendi l'estrazione. A scadenza si attende la conferma delle puntate, poi un blocco della catena sceglie il vincitore. Il premio arriva sul suo saldo quando il pagamento è confermato. + + Ogni estrazione si può controllare: vedi i risultati e le regole. +{% endblock %} diff --git a/apps/web/templates/web/home.html b/apps/web/templates/web/home.html index 63036c0..de51e92 100644 --- a/apps/web/templates/web/home.html +++ b/apps/web/templates/web/home.html @@ -7,4 +7,5 @@ {% url 'web:state' as poll_url %} {% include "web/_round_card.html" with poll_url=poll_url show_participate=True %} + Risultati e prove delle estrazioni passate · Come si gioca {% endblock %} diff --git a/apps/web/templates/web/result_detail.html b/apps/web/templates/web/result_detail.html new file mode 100644 index 0000000..b2676ec --- /dev/null +++ b/apps/web/templates/web/result_detail.html @@ -0,0 +1,85 @@ +{% extends "web/base.html" %} +{% block title %}Round {{ p.round_id }} · PLM Lottery{% endblock %} +{% block content %} + ← Tutti i risultati + Round {{ p.round_id }} + + + Esito + {% if p.winner_address %} + Vincitore: posizione {{ p.winner_position }}, indirizzo {{ p.winner_address }}. + {% if p.winner_amount_text %}Montepremi {{ p.pool_text }}; al vincitore {{ p.winner_amount_text }} ({{ p.winner_amount_sats|default:0 }} sat), il resto alla piattaforma.{% endif %} + + {% if p.payout_confirmed %}Pagamento confermato{% if p.payout_txid %} · transazione {{ p.payout_txid }}{% endif %}. + {% elif p.payout_txid %}Pagamento inviato, in attesa di conferma. + {% else %}Pagamento non ancora inviato.{% endif %} + + {% elif round.status == "closed" %} + Nessun partecipante: non c'è stata estrazione e nulla da pagare. + {% else %} + L'estrazione non è ancora avvenuta: il round è «{{ round.get_status_display }}». + {% endif %} + + + {% if p.checks %} + + Ricalcolo + + Impegno: lo sha256 del segreto rivelato coincide con quello pubblicato prima dell'estrazione. + {% if p.checks.order is not None %} + Ordine: i partecipanti sono in ordine crescente di txid, posizioni da 0 a {{ p.participants|length|add:"-1" }}. + Impronta: lo sha256 delle righe txid:vout:indirizzo coincide con l'impronta pubblicata. + Vincitore: la posizione {{ p.index }} è quella che ha ricevuto il premio. + {% endif %} + + + {% endif %} + + + Dati della prova + + Impegno sul segreto (server_seed_hash){{ p.server_seed_hash|default:"non ancora disponibile" }} + Indirizzo del montepremi{{ p.pool_address|default:"non ancora disponibile" }} + Impronta dei partecipanti{{ p.participants_hash|default:"non ancora disponibile" }} + Altezza del blocco{{ p.draw_height|default_if_none:"non ancora disponibile" }} (conferme attese: {{ p.draw_confirmations }}) + Hash del blocco{{ p.draw_block_hash|default:"non ancora disponibile" }} + Segreto rivelato (server_seed){{ p.server_seed|default:"si rivela all'estrazione" }} + Seme{{ p.seed|default:"non ancora disponibile" }} + Posizione estratta{{ p.index|default_if_none:"non ancora disponibile" }} + + Scarica la prova in JSON + + + {% if p.participants %} + + Partecipanti ({{ p.participants|length }}) + + + Lista pubblica dell'estrazione, in ordine di posizione + PosizioneTransazioneUscitaIndirizzo + + {% for r in p.participants %} + + {{ r.position }} + {{ r.txid }} + {{ r.vout }} + {{ r.address }} + + {% endfor %} + + + + + {% endif %} + + + Come rifare il calcolo + + Verifica che lo sha256 dei 32 byte del segreto sia uguale all'impegno. + Ricostruisci le righe txid:vout:indirizzo, ognuna terminata da un a capo, nell'ordine della lista, e verifica che il loro sha256 sia l'impronta. + Calcola lo sha256 della concatenazione di segreto, hash del blocco e impronta (32 byte ciascuno) e leggilo come intero big-endian: è il seme. + Il resto della divisione del seme per il numero di partecipanti è la posizione vincente. + + I dati sono quelli del protocollo e si controllano con un qualunque nodo o explorer PLM. + +{% endblock %} diff --git a/apps/web/templates/web/results.html b/apps/web/templates/web/results.html new file mode 100644 index 0000000..aa28697 --- /dev/null +++ b/apps/web/templates/web/results.html @@ -0,0 +1,34 @@ +{% extends "web/base.html" %} +{% block title %}Risultati · PLM Lottery{% endblock %} +{% block content %} + Risultati + Ogni round concluso ha una prova che chiunque può ricalcolare. I giocatori compaiono solo con un indirizzo pseudonimo. + {% if rows %} + + + Round conclusi, dal più recente + RoundChiuso (UTC)MontepremiAl vincitoreProva + + {% for row in rows %} + + {{ row.id }} + {{ row.closed_at|date:"d/m/Y H:i:s" }} + {{ row.pool_text }} + {% if row.has_winner %}{{ row.winner_text }}{% else %}nessun partecipante{% endif %} + Vedi la prova + + {% endfor %} + + + + {% if page.paginator.num_pages > 1 %} + + {% if page.has_previous %}← Più recenti{% endif %} + Pagina {{ page.number }} di {{ page.paginator.num_pages }} + {% if page.has_next %}Meno recenti →{% endif %} + + {% endif %} + {% else %} + Nessun round è ancora concluso. Torna dopo la prima estrazione. + {% endif %} +{% endblock %} diff --git a/apps/web/templates/web/rules.html b/apps/web/templates/web/rules.html new file mode 100644 index 0000000..24fcb87 --- /dev/null +++ b/apps/web/templates/web/rules.html @@ -0,0 +1,13 @@ +{% extends "web/base.html" %} +{% block title %}Regole · PLM Lottery{% endblock %} +{% block content %} + Regole + + Quota. Ogni giocatore punta la stessa quota ({{ bet_text }}), al massimo una volta per round. Ogni puntata ha le stesse probabilità, qualunque sia il saldo. + Durata. Un round dura {{ duration_minutes }} minuti dall'apertura. Dopo la scadenza non si accettano più puntate; quelle già inviate vanno confermate. + Ripartizione. Il montepremi si divide {{ winner_percent }}% al vincitore e {{ platform_percent }}% alla piattaforma; l'eventuale resto dell'arrotondamento va alla piattaforma. Le commissioni di rete sono a carico del vincitore. + Attesa delle conferme. Depositi, puntate e pagamento contano quando la catena li conferma. L'estrazione usa un blocco che non esisteva alla chiusura del round, con {{ confirmations }} conferme. + Estrazione verificabile. Il segreto è impegnato prima dell'apertura delle puntate e rivelato dopo l'estrazione; la lista dei partecipanti è fissata prima del blocco. Chiunque ricalcola il vincitore dalla prova pubblica. + Pause. La lotteria può fermarsi dopo il round in corso, o sospendere le nuove puntate; i round avviati si concludono e i fondi restano dei giocatori. + +{% endblock %} diff --git a/apps/web/urls.py b/apps/web/urls.py index 2b5d44b..1bc6b92 100644 --- a/apps/web/urls.py +++ b/apps/web/urls.py @@ -1,6 +1,6 @@ from django.urls import path -from . import player_views, views +from . import player_views, public_views, views app_name = "web" urlpatterns = [ @@ -13,5 +13,10 @@ urlpatterns = [ path("app/portafoglio/qr.svg", player_views.wallet_qr, name="wallet-qr"), path("app/portafoglio/deposito-prova/", player_views.simulated_deposit, name="simulated-deposit"), path("app/movimenti/", player_views.movements, name="movements"), + path("risultati/", public_views.results, name="results"), + path("risultati//", public_views.result_detail, name="result"), + path("risultati//prova.json", public_views.result_proof_json, name="result-proof"), + path("guida/", public_views.guide, name="guide"), + path("regole/", public_views.rules, name="rules"), path("health/live", views.health_live, name="health-live"), ] diff --git a/docs/sito-e-app.md b/docs/sito-e-app.md index 88e5c41..b6de452 100644 --- a/docs/sito-e-app.md +++ b/docs/sito-e-app.md @@ -88,12 +88,20 @@ backend FastAPI (vedi [architettura.md](architettura.md)). puntata richiede una conferma esplicita. *Stato:* implementato (A5, [WEB-52], e A6): «Partecipa» compare solo quando le puntate sono aperte e porta a `/app/` · *Test:* `tests/django/test_home.py::test_participate_leads_to_the_player_area`, `test_participate_is_hidden_when_betting_is_not_possible` -- **[WEB-12]** `/risultati/` pubblica esito e prova dell'estrazione, - riproducibile con i dati del protocollo ([RND-14]…[RND-20]), senza - username né dati dell'account. Il pagamento risulta confermato solo quando lo è. -- **[WEB-13]** Guida e regole usano gli stessi termini dell'area giocatore +- **[WEB-12]** `/risultati/` elenca i round conclusi (dal più recente, a pagine) e `/risultati//` pubblica esito e prova + dell'estrazione, riproducibile con i dati del protocollo ([RND-14]…[RND-20]), senza username né dati dell'account: i + partecipanti e il vincitore compaiono solo con l'indirizzo pseudonimo della lista pubblica ([DAT-65]). La pagina mostra + l'impegno, la lista ordinata, l'impronta, l'altezza e l'hash del blocco, il segreto rivelato, il seme e la posizione estratta, + con il ricalcolo (impegno, ordine, impronta, vincitore) e i passi per rifarlo da soli; `/risultati//prova.json` dà gli stessi + dati in JSON. Ciò che non esiste ancora è «non ancora disponibile», mai un valore inventato. Il pagamento risulta confermato solo + quando lo è. Un round che non esiste dà 404. + *Stato:* implementato (A8) · + *Codice:* `apps/lottery/proof.py:round_proof`, `apps/web/public_views.py` · + *Test:* `tests/django/test_public.py` +- **[WEB-13]** Guida (`/guida/`) e regole (`/regole/`) usano gli stessi termini dell'area giocatore (quota, ripartizione 70/30, commissioni, attesa delle conferme) e non - promettono l'accredito immediato. + promettono l'accredito immediato. Le cifre (quota, ripartizione, durata) sono lette dalla configurazione, non scritte a mano. + *Stato:* implementato (A8) · *Test:* `tests/django/test_public.py` - **[WEB-14]** **Aggiornamento della home.** `GET /stato/` restituisce, pubblico e mai in cache, lo stesso stato che la pagina mostra (una sola funzione li alimenta: non possono raccontare cose diverse), senza dati di account né del segreto del round; porta l'ora del server. `home.js` (esterno, senza dipendenze) fa scorrere il conto alla rovescia sull'**ora del server**, non su diff --git a/roadmap.md b/roadmap.md index 0c5d95b..6367ce8 100644 --- a/roadmap.md +++ b/roadmap.md @@ -31,7 +31,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore - [x] **A5 · Autenticazione e base grafica.** `/registrati/`, `/accedi/`, `/app/profilo/` (password, logout), CSRF, cookie di sessione, ritorno alla destinazione interna (`next`) solo se interna, template base e CSS responsivo. *Requisiti:* WEB-02, WEB-06. *Test:* redirect aperto rifiutato, cookie, throttling dei tentativi. - [x] **A6 · Home pubblica.** `/` con quota, montepremi confermato, chiusura (ora server) e i sei stati, «Partecipa», aggiornamento a polling. *Requisiti:* WEB-05, WEB-10, WEB-11. *Test:* un test per stato, polling dell'endpoint. - [x] **A7 · Area giocatore.** `/app/` (puntata con conferma esplicita), `/app/portafoglio/` (saldo spendibile e in conferma, deposito simulato **solo fuori da mainnet**), `/app/movimenti/`. *Requisiti:* WEB-03, WEB-20, WEB-21, WEB-22. *Test:* isolamento tra utenti (404 su dati altrui), stato salvato dopo ricarica. -- [ ] **A8 · Pagine pubbliche di risultato e guida.** `/risultati/`, `/risultati//` con prova riproducibile senza dati dell'account, `/guida/`, `/regole/` con gli stessi termini dell'app. *Requisiti:* WEB-12, WEB-13. *Test:* la prova ricalcola il vincitore; nessuno username nelle pagine. +- [x] **A8 · Pagine pubbliche di risultato e guida.** `/risultati/`, `/risultati//` con prova riproducibile senza dati dell'account, `/guida/`, `/regole/` con gli stessi termini dell'app. *Requisiti:* WEB-12, WEB-13. *Test:* la prova ricalcola il vincitore; nessuno username nelle pagine. - [ ] **A9 · Console operativa e audit.** `/ops/` con stato del round, scadenza, salute del worker, operazioni in ritardo; i tre comandi di pausa con conferma e motivazione; `/admin/` per utenti e segnalazioni con record di gioco in sola lettura; **segnalazioni**: modello, sezione nel profilo del giocatore (invio e stato delle proprie) e gestione da `/admin/`; ogni comando registrato nell'audit. *Requisiti:* WEB-30…WEB-33, WEB-40…WEB-44, WEB-55. *Test:* giocatore e staff senza permesso non eseguono i comandi; la pausa si riflette sul sito. - [ ] **A10 · Percorso completo e chiusura di fase.** Test end-to-end `home → login → deposito → puntata → estrazione → risultato pubblico`; verifica su telefono e desktop, tastiera, stati di errore, attesa e conferma (checklist in `docs/`); guida di avvio in locale in `docs/setup.md`. *Requisiti:* WEB-06. diff --git a/tests/django/test_public.py b/tests/django/test_public.py new file mode 100644 index 0000000..f325a38 --- /dev/null +++ b/tests/django/test_public.py @@ -0,0 +1,160 @@ +"""A8 — public results, proof, guide and rules: WEB-12, WEB-13, RND-14..RND-20, RND-37, DAT-65.""" + +import hashlib +import re +from datetime import timedelta +from uuid import uuid4 + +import pytest +from django.contrib.auth import get_user_model +from django.urls import reverse +from django.utils import timezone +from plm_engine.draw import draw_index, draw_seed, participants_hash, server_seed_commitment + +from apps.lottery import lifecycle +from apps.lottery.addresses import participant_address +from apps.lottery.ledger import SimulatedLedger +from apps.lottery.models import LotteryConfig, Round +from apps.lottery.proof import round_proof +from apps.lottery.simulation import SimulatedChain + +pytestmark = pytest.mark.django_db +ledger = SimulatedLedger() +NAMES = ["marta_rossi", "luca_bianchi", "giorgio_verdi"] + + +class FakeChain: + tip = 1000 + + def tip_height(self, now=None): + return self.tip + + def agreed_block_hash(self, height, now=None): + return "cd" * 32 + + +def finished_round(names=NAMES, *, confirm_payout=True): + """A round played to the end with real lifecycle code: open, bets, close, draw, pay.""" + t0 = timezone.now() + round_ = lifecycle.open_new_round_if_needed(t0) + for name in names: + user = get_user_model().objects.create_user(name, password="x" * 12) + ledger.deposit(user, round_.bet_amount_sats) + ledger.confirm_bet(ledger.place_bet(user, round_.pk, request_id=uuid4()).obj) + later = t0 + timedelta(seconds=round_.duration_seconds + 1) + chain = FakeChain() + lifecycle.tick(now=later, chain=chain) # closing, then drawing: waits for the block that does not exist yet + chain.tip += 10 + lifecycle.tick(now=later, chain=chain) # draw, payout created (or closed, with nobody in it) + round_.refresh_from_db() + if confirm_payout and round_.payout_transaction_id: + ledger.confirm_payout(round_.pk) + lifecycle.tick(now=later, chain=chain) + round_.refresh_from_db() + return round_ + + +def test_the_proof_recomputes_the_winner_from_public_data_alone(): + """WEB-12: with only the public proof, a stranger gets the same winner the platform paid.""" + round_ = finished_round() + p = round_proof(round_) + assert round_.status == "closed" and p["checks"] == { + "commitment": True, "order": True, "fingerprint": True, "winner": True} + # Recompute from the proof dict only, using the documented steps (no database object). + assert hashlib.sha256(bytes.fromhex(p["server_seed"])).hexdigest() == p["server_seed_hash"] + rows = [(r["txid"], r["vout"], r["address"]) for r in p["participants"]] + assert participants_hash(rows) == p["participants_hash"] + seed = int.from_bytes(hashlib.sha256( + bytes.fromhex(p["server_seed"]) + bytes.fromhex(p["draw_block_hash"]) + bytes.fromhex(p["participants_hash"]) + ).digest(), "big") + assert p["seed"] == f"{seed:064x}" + winner = p["participants"][seed % len(rows)] + assert winner["address"] == p["winner_address"] == participant_address(round_.winner) + + +def test_the_proof_page_and_json_show_the_same_winner_without_any_username(client): + round_ = finished_round() + page = client.get(reverse("web:result", args=[round_.pk])) + data = client.get(reverse("web:result-proof", args=[round_.pk])) + assert page.status_code == data.status_code == 200 + body = page.content.decode() + data.content.decode() + for name in NAMES: + assert name not in body # WEB-12: no username anywhere + assert data.json()["winner_address"] in page.content.decode() + assert "Pagamento confermato" in page.content.decode() + assert page.content.decode().count('data-ok="1"') == 4 and 'data-ok="0"' not in page.content.decode() + + +def test_results_list_shows_only_closed_rounds_and_no_username(client): + done = finished_round() + page = client.get(reverse("web:results")).content.decode() + assert f'href="{reverse("web:result", args=[done.pk])}"' in page + assert not any(n in page for n in NAMES) + open_round = lifecycle.open_new_round_if_needed(timezone.now() + timedelta(hours=1)) # past the cooldown + assert open_round is not None and f'href="{reverse("web:result", args=[open_round.pk])}"' not in client.get(reverse("web:results")).content.decode() + + +def test_the_payout_is_confirmed_only_when_it_is(client): + round_ = finished_round(confirm_payout=False) + assert round_.status == "paying_out" + html = client.get(reverse("web:result", args=[round_.pk])).content.decode() + assert "in attesa di conferma" in html and "Pagamento confermato" not in html + + +def test_an_open_round_publishes_only_the_commitment_and_never_the_secret(client): + """RND-34, RND-37: before the draw the secret stays hidden; the missing fields say so.""" + round_ = lifecycle.open_new_round_if_needed(timezone.now()) + p = client.get(reverse("web:result-proof", args=[round_.pk])).json() + assert p["server_seed_hash"] == round_.server_seed_hash + assert p["server_seed"] is None and p["draw_block_hash"] is None and p["participants"] == [] and p["checks"] is None + assert round_.server_seed_enc not in str(p) + html = client.get(reverse("web:result", args=[round_.pk])).content.decode() + assert "non ancora disponibile" in html and "L'estrazione non è ancora avvenuta" in html + + +def test_a_round_nobody_joined_says_so(client): + round_ = finished_round(names=[]) + assert round_.status == "closed" and round_.winner_id is None + html = client.get(reverse("web:result", args=[round_.pk])).content.decode() + assert "Nessun partecipante" in html and "Vincitore:" not in html + assert round_proof(round_)["checks"] == {"commitment": True} + + +def test_an_unknown_round_is_a_404(client): + assert client.get(reverse("web:result", args=[999])).status_code == 404 + assert client.get(reverse("web:result-proof", args=[999])).status_code == 404 + + +def test_tampering_with_the_stored_list_fails_the_recomputation(): + """The checks are real: a changed winner or fingerprint shows as failed instead of being rubber-stamped.""" + round_ = finished_round() + other = get_user_model().objects.exclude(pk=round_.winner_id).first() + Round.objects.filter(pk=round_.pk).update(winner=other) + assert round_proof(Round.objects.get(pk=round_.pk))["checks"]["winner"] is False + Round.objects.filter(pk=round_.pk).update(participants_hash="00" * 32) + assert round_proof(Round.objects.get(pk=round_.pk))["checks"]["fingerprint"] is False + + +def test_public_pages_need_no_login_and_proof_is_not_cached(client): + round_ = finished_round() + for name, args in [("web:results", []), ("web:guide", []), ("web:rules", []), ("web:result", [round_.pk])]: + assert client.get(reverse(name, args=args)).status_code == 200 + assert "no-store" in client.get(reverse("web:result-proof", args=[round_.pk]))["Cache-Control"] + + +def test_guide_and_rules_use_the_live_terms_and_do_not_promise_instant_credit(client): + """WEB-13: figures come from the configuration; the wording matches the player area.""" + LotteryConfig.get() + LotteryConfig.objects.filter(pk=1).update(bet_amount_sats=25 * 100_000_000, round_duration_seconds=900) + guide = client.get(reverse("web:guide")).content.decode() + rules = client.get(reverse("web:rules")).content.decode() + assert "25 PLM" in guide and "25 PLM" in rules and "15 minuti" in rules + assert "70%" in rules and "30%" in rules and "commissioni" in rules.lower() and "conferme" in rules + assert "l'accredito non è immediato" in guide + assert not re.search(r"accredito immediato|istantane", guide + rules, re.I) + + +def test_home_and_menu_link_to_the_public_pages(client): + html = client.get(reverse("web:home")).content.decode() + for name in ("web:results", "web:guide", "web:rules"): + assert f'href="{reverse(name)}"' in html
Come si gioca, in quattro passi. I termini sono gli stessi che trovi nell'area giocatore.
Ogni estrazione si può controllare: vedi i risultati e le regole.
Risultati e prove delle estrazioni passate · Come si gioca
← Tutti i risultati
Vincitore: posizione {{ p.winner_position }}, indirizzo {{ p.winner_address }}.
{{ p.winner_address }}
Montepremi {{ p.pool_text }}; al vincitore {{ p.winner_amount_text }} ({{ p.winner_amount_sats|default:0 }} sat), il resto alla piattaforma.
+ {% if p.payout_confirmed %}Pagamento confermato{% if p.payout_txid %} · transazione {{ p.payout_txid }}{% endif %}. + {% elif p.payout_txid %}Pagamento inviato, in attesa di conferma. + {% else %}Pagamento non ancora inviato.{% endif %} +
{{ p.payout_txid }}
Nessun partecipante: non c'è stata estrazione e nulla da pagare.
L'estrazione non è ancora avvenuta: il round è «{{ round.get_status_display }}».
txid:vout:indirizzo
server_seed_hash
{{ p.server_seed_hash|default:"non ancora disponibile" }}
{{ p.pool_address|default:"non ancora disponibile" }}
{{ p.participants_hash|default:"non ancora disponibile" }}
{{ p.draw_block_hash|default:"non ancora disponibile" }}
server_seed
{{ p.server_seed|default:"si rivela all'estrazione" }}
{{ p.seed|default:"non ancora disponibile" }}
Scarica la prova in JSON
{{ r.txid }}
{{ r.address }}
I dati sono quelli del protocollo e si controllano con un qualunque nodo o explorer PLM.
Ogni round concluso ha una prova che chiunque può ricalcolare. I giocatori compaiono solo con un indirizzo pseudonimo.
Nessun round è ancora concluso. Torna dopo la prima estrazione.