A8: public results, reproducible proof, guide and rules (WEB-12, WEB-13, RND-37)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
42e5e33371
commit
58d1a38ac0
15 files changed
+454
-10
No files matched your search
@@ -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
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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())
|
||||
@@ -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; }
|
||||
@@ -15,6 +15,9 @@
|
||||
<a class="brand" href="{% url 'web:home' %}">PLM Lottery</a>
|
||||
<nav class="nav" aria-label="Principale">
|
||||
<a href="{% url 'web:home' %}">Home</a>
|
||||
<a href="{% url 'web:results' %}">Risultati</a>
|
||||
<a href="{% url 'web:guide' %}">Guida</a>
|
||||
<a href="{% url 'web:rules' %}">Regole</a>
|
||||
{% if user.is_authenticated %}
|
||||
{% with current=request.resolver_match.view_name %}
|
||||
<a href="{% url 'web:app-home' %}"{% if current == 'web:app-home' or current == 'web:bet' %} aria-current="page"{% endif %}>Gioca</a>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{% extends "web/base.html" %}
|
||||
{% block title %}Guida · PLM Lottery{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Guida</h1>
|
||||
<p class="lead">Come si gioca, in quattro passi. I termini sono gli stessi che trovi nell'area giocatore.</p>
|
||||
<ol class="steps">
|
||||
<li><strong>Registrati e accedi.</strong> Bastano nome utente e password: non chiediamo email.</li>
|
||||
<li><strong>Deposita.</strong> Dal <a href="{% url 'web:wallet' %}">portafoglio</a> trovi il tuo indirizzo. I fondi compaiono «in conferma» e diventano spendibili solo dopo le conferme: l'accredito non è immediato.</li>
|
||||
<li><strong>Punta.</strong> La quota è {{ bet_text }}. Una puntata per round, con una schermata di conferma prima dell'invio.</li>
|
||||
<li><strong>Attendi l'estrazione.</strong> 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.</li>
|
||||
</ol>
|
||||
<p>Ogni estrazione si può controllare: vedi i <a href="{% url 'web:results' %}">risultati</a> e le <a href="{% url 'web:rules' %}">regole</a>.</p>
|
||||
{% endblock %}
|
||||
@@ -7,4 +7,5 @@
|
||||
|
||||
{% url 'web:state' as poll_url %}
|
||||
{% include "web/_round_card.html" with poll_url=poll_url show_participate=True %}
|
||||
<p><a href="{% url 'web:results' %}">Risultati e prove delle estrazioni passate</a> · <a href="{% url 'web:guide' %}">Come si gioca</a></p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,85 @@
|
||||
{% extends "web/base.html" %}
|
||||
{% block title %}Round {{ p.round_id }} · PLM Lottery{% endblock %}
|
||||
{% block content %}
|
||||
<p><a href="{% url 'web:results' %}">← Tutti i risultati</a></p>
|
||||
<h1>Round {{ p.round_id }}</h1>
|
||||
|
||||
<section class="card" aria-labelledby="esito">
|
||||
<h2 id="esito">Esito</h2>
|
||||
{% if p.winner_address %}
|
||||
<p>Vincitore: posizione <strong>{{ p.winner_position }}</strong>, indirizzo <code class="break">{{ p.winner_address }}</code>.</p>
|
||||
{% if p.winner_amount_text %}<p>Montepremi {{ p.pool_text }}; al vincitore {{ p.winner_amount_text }} ({{ p.winner_amount_sats|default:0 }} sat), il resto alla piattaforma.</p>{% endif %}
|
||||
<p>
|
||||
{% if p.payout_confirmed %}Pagamento <strong>confermato</strong>{% if p.payout_txid %} · transazione <code class="break">{{ p.payout_txid }}</code>{% endif %}.
|
||||
{% elif p.payout_txid %}Pagamento inviato, <strong>in attesa di conferma</strong>.
|
||||
{% else %}Pagamento non ancora inviato.{% endif %}
|
||||
</p>
|
||||
{% elif round.status == "closed" %}
|
||||
<p>Nessun partecipante: non c'è stata estrazione e nulla da pagare.</p>
|
||||
{% else %}
|
||||
<p>L'estrazione non è ancora avvenuta: il round è «{{ round.get_status_display }}».</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% if p.checks %}
|
||||
<section class="card" aria-labelledby="ricalcolo">
|
||||
<h2 id="ricalcolo">Ricalcolo</h2>
|
||||
<ul class="plain checks">
|
||||
<li data-ok="{{ p.checks.commitment|yesno:'1,0' }}">Impegno: lo sha256 del segreto rivelato coincide con quello pubblicato prima dell'estrazione.</li>
|
||||
{% if p.checks.order is not None %}
|
||||
<li data-ok="{{ p.checks.order|yesno:'1,0' }}">Ordine: i partecipanti sono in ordine crescente di txid, posizioni da 0 a {{ p.participants|length|add:"-1" }}.</li>
|
||||
<li data-ok="{{ p.checks.fingerprint|yesno:'1,0' }}">Impronta: lo sha256 delle righe <code>txid:vout:indirizzo</code> coincide con l'impronta pubblicata.</li>
|
||||
<li data-ok="{{ p.checks.winner|yesno:'1,0' }}">Vincitore: la posizione {{ p.index }} è quella che ha ricevuto il premio.</li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
<section class="card" aria-labelledby="dati">
|
||||
<h2 id="dati">Dati della prova</h2>
|
||||
<dl class="facts">
|
||||
<dt>Impegno sul segreto (<code>server_seed_hash</code>)</dt><dd><code class="break">{{ p.server_seed_hash|default:"non ancora disponibile" }}</code></dd>
|
||||
<dt>Indirizzo del montepremi</dt><dd><code class="break">{{ p.pool_address|default:"non ancora disponibile" }}</code></dd>
|
||||
<dt>Impronta dei partecipanti</dt><dd><code class="break">{{ p.participants_hash|default:"non ancora disponibile" }}</code></dd>
|
||||
<dt>Altezza del blocco</dt><dd>{{ p.draw_height|default_if_none:"non ancora disponibile" }} (conferme attese: {{ p.draw_confirmations }})</dd>
|
||||
<dt>Hash del blocco</dt><dd><code class="break">{{ p.draw_block_hash|default:"non ancora disponibile" }}</code></dd>
|
||||
<dt>Segreto rivelato (<code>server_seed</code>)</dt><dd><code class="break">{{ p.server_seed|default:"si rivela all'estrazione" }}</code></dd>
|
||||
<dt>Seme</dt><dd><code class="break">{{ p.seed|default:"non ancora disponibile" }}</code></dd>
|
||||
<dt>Posizione estratta</dt><dd>{{ p.index|default_if_none:"non ancora disponibile" }}</dd>
|
||||
</dl>
|
||||
<p><a href="{% url 'web:result-proof' p.round_id %}">Scarica la prova in JSON</a></p>
|
||||
</section>
|
||||
|
||||
{% if p.participants %}
|
||||
<section class="card" aria-labelledby="lista">
|
||||
<h2 id="lista">Partecipanti ({{ p.participants|length }})</h2>
|
||||
<div class="table-wrap">
|
||||
<table class="movements">
|
||||
<caption class="visually-hidden">Lista pubblica dell'estrazione, in ordine di posizione</caption>
|
||||
<thead><tr><th scope="col" class="num">Posizione</th><th scope="col">Transazione</th><th scope="col" class="num">Uscita</th><th scope="col">Indirizzo</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in p.participants %}
|
||||
<tr{% if r.position == p.winner_position and p.winner_address %} class="winner"{% endif %}>
|
||||
<td data-label="Posizione" class="num">{{ r.position }}</td>
|
||||
<td data-label="Transazione"><code class="break">{{ r.txid }}</code></td>
|
||||
<td data-label="Uscita" class="num">{{ r.vout }}</td>
|
||||
<td data-label="Indirizzo"><code class="break">{{ r.address }}</code></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
<section class="card" aria-labelledby="come">
|
||||
<h2 id="come">Come rifare il calcolo</h2>
|
||||
<ol>
|
||||
<li>Verifica che lo sha256 dei 32 byte del segreto sia uguale all'impegno.</li>
|
||||
<li>Ricostruisci le righe <code>txid:vout:indirizzo</code>, ognuna terminata da un a capo, nell'ordine della lista, e verifica che il loro sha256 sia l'impronta.</li>
|
||||
<li>Calcola lo sha256 della concatenazione di segreto, hash del blocco e impronta (32 byte ciascuno) e leggilo come intero big-endian: è il seme.</li>
|
||||
<li>Il resto della divisione del seme per il numero di partecipanti è la posizione vincente.</li>
|
||||
</ol>
|
||||
<p class="hint">I dati sono quelli del protocollo e si controllano con un qualunque nodo o explorer PLM.</p>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,34 @@
|
||||
{% extends "web/base.html" %}
|
||||
{% block title %}Risultati · PLM Lottery{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Risultati</h1>
|
||||
<p class="lead">Ogni round concluso ha una prova che chiunque può ricalcolare. I giocatori compaiono solo con un indirizzo pseudonimo.</p>
|
||||
{% if rows %}
|
||||
<div class="table-wrap">
|
||||
<table class="movements">
|
||||
<caption class="visually-hidden">Round conclusi, dal più recente</caption>
|
||||
<thead><tr><th scope="col">Round</th><th scope="col">Chiuso (UTC)</th><th scope="col" class="num">Montepremi</th><th scope="col" class="num">Al vincitore</th><th scope="col">Prova</th></tr></thead>
|
||||
<tbody>
|
||||
{% for row in rows %}
|
||||
<tr>
|
||||
<td data-label="Round">{{ row.id }}</td>
|
||||
<td data-label="Chiuso (UTC)"><time datetime="{{ row.closed_at|date:'c' }}">{{ row.closed_at|date:"d/m/Y H:i:s" }}</time></td>
|
||||
<td data-label="Montepremi" class="num">{{ row.pool_text }}</td>
|
||||
<td data-label="Al vincitore" class="num">{% if row.has_winner %}{{ row.winner_text }}{% else %}<span class="hint">nessun partecipante</span>{% endif %}</td>
|
||||
<td data-label="Prova"><a href="{% url 'web:result' row.id %}">Vedi la prova</a></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if page.paginator.num_pages > 1 %}
|
||||
<nav class="pager" aria-label="Pagine dei risultati">
|
||||
{% if page.has_previous %}<a class="button secondary small" href="?pagina={{ page.previous_page_number }}">← Più recenti</a>{% endif %}
|
||||
<span class="hint">Pagina {{ page.number }} di {{ page.paginator.num_pages }}</span>
|
||||
{% if page.has_next %}<a class="button secondary small" href="?pagina={{ page.next_page_number }}">Meno recenti →</a>{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="card">Nessun round è ancora concluso. Torna dopo la prima estrazione.</p>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,13 @@
|
||||
{% extends "web/base.html" %}
|
||||
{% block title %}Regole · PLM Lottery{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Regole</h1>
|
||||
<ul class="rules">
|
||||
<li><strong>Quota.</strong> Ogni giocatore punta la stessa quota ({{ bet_text }}), al massimo una volta per round. Ogni puntata ha le stesse probabilità, qualunque sia il saldo.</li>
|
||||
<li><strong>Durata.</strong> Un round dura {{ duration_minutes }} minuti dall'apertura. Dopo la scadenza non si accettano più puntate; quelle già inviate vanno confermate.</li>
|
||||
<li><strong>Ripartizione.</strong> 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.</li>
|
||||
<li><strong>Attesa delle conferme.</strong> 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.</li>
|
||||
<li><strong>Estrazione verificabile.</strong> 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 <a href="{% url 'web:results' %}">prova pubblica</a>.</li>
|
||||
<li><strong>Pause.</strong> 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.</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
+6
-1
@@ -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/<int:round_id>/", public_views.result_detail, name="result"),
|
||||
path("risultati/<int:round_id>/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"),
|
||||
]
|
||||
+13
-5
@@ -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/<id>/` 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/<id>/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
|
||||
|
||||
+1
-1
@@ -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/<id>/` 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/<id>/` 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.
|
||||
|
||||
|
||||
@@ -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 <strong>confermato</strong>" 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 <strong>confermato</strong>" 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
|
||||
Reference in new issue
Block a user