A7: player area - play, wallet, movements (WEB-03, WEB-05, WEB-20..27)

Gioca: the round, the player's funds and their bet; the bet is two steps
(a confirmation screen that sends nothing, then an explicit confirm) with a
fresh idempotency key per screen, and the server re-checks everything.
Portafoglio: spendable apart from in-confirmation, deposit address with a QR
of the player's own address, copy button, simulated test deposits.
Movimenti: the player's own ledger, paged, stacked as cards on a phone.
GET /app/stato/ feeds the page and its polling. Every view takes the user from
the session only. Checked end to end in a real browser (Playwright): status
moves from pending to confirmed without a reload, a double click is one bet.
Mutation checks: cross-account leak, non-idempotent POST and unrestricted
test-deposit amounts are all caught.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 14:41:27 +01:00
1 parent 939c113043
commit 42e5e33371
21 files changed
+1192 -48

No files matched your search

+2 -2
View File
@@ -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 — 1041 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 — 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.
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 1041 tests
python -m pytest # all 1109 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
```
+1 -1
View File
@@ -62,7 +62,7 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file
```
1041 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
1109 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
+23
View File
@@ -0,0 +1,23 @@
"""The words for a ledger error: the code is stable, the text is Italian (ADR-60)."""
from .format import plm_text
def ledger_error_text(code: str, params: dict) -> str:
texts = {
"no_round_open": "Non c'è un round aperto in questo momento. Riprova fra poco.",
"round_closing": "Le puntate di questo round sono chiuse. Attendi il prossimo round.",
"already_betting": "Hai già una puntata in questo round.",
"bets_suspended": "Le nuove puntate sono sospese. Riprova più tardi.",
"missing_request_id": "La richiesta non è valida. Ricarica la pagina e riprova.",
"idempotency_conflict": "Questa richiesta è già stata usata per un'altra operazione. Ricarica la pagina e riprova.",
"invalid_amount": "L'importo non è valido.",
}
if code == "insufficient_balance":
return f"Saldo insufficiente: servono {plm_text(params.get('required_sats', 0))} spendibili."
if code == "balance_pending_confirmation":
return (f"Il saldo che vedi include {plm_text(params.get('pending_sats', 0))} ancora in conferma: "
"potrai puntare quando saranno confermati.")
if code == "round_full":
return "Questo round ha raggiunto il limite di giocatori o di montepremi. Attendi il prossimo."
return texts.get(code, "Non è stato possibile completare l'operazione. Riprova.")
+78
View File
@@ -0,0 +1,78 @@
"""What one player sees of the game right now (WEB-20 .. WEB-22): their funds, their bet in the round, and how
their last round ended. One function feeds the page and `/app/stato/`, like `public_state` does for the home."""
from datetime import datetime
from typing import Any
from django.utils import timezone
from .balances import balance_of
from .format import plm_text
from .models import Participation, Round
from .status import public_state
PARTICIPATION_LABELS = {
Participation.Status.PENDING: ("In attesa di conferma", "La tua puntata è stata inviata e aspetta la conferma. "
"Fino ad allora non partecipi ancora all'estrazione."),
Participation.Status.CONFIRMED: ("Confermata", "Partecipi all'estrazione di questo round."),
Participation.Status.REJECTED: ("Rifiutata", "La puntata non è stata accettata: i fondi sono tornati disponibili."),
Participation.Status.EXCLUDED: ("Esclusa dall'estrazione", "La puntata è stata esclusa dall'estrazione e l'importo ti è stato rimborsato."),
}
def _participation_block(participation: Participation) -> dict[str, Any]:
label, message = PARTICIPATION_LABELS[participation.status]
return {"status": participation.status, "label": label, "message": message, "round_id": participation.round_id,
"amount_text": plm_text(participation.bet_amount_sats)}
def _last_result(user, active_round_id: int | None) -> str:
"""How the player's most recent finished round ended, in one sentence ('' if there is nothing to say)."""
last = (Participation.objects.filter(user=user).exclude(round_id=active_round_id).select_related("round")
.order_by("-round_id").first())
if last is None or last.round.status != Round.Status.CLOSED:
return ""
if last.status == Participation.Status.CONFIRMED:
if last.round.winner_id == user.pk:
return f"Round {last.round_id}: hai vinto {plm_text(last.round.winner_amount_sats or 0)}."
return f"Round {last.round_id}: non hai vinto questa volta."
if last.status == Participation.Status.REJECTED:
return f"Round {last.round_id}: la tua puntata è stata rifiutata e i fondi ti sono tornati."
if last.status == Participation.Status.EXCLUDED:
return f"Round {last.round_id}: la tua puntata è stata esclusa e rimborsata."
return ""
def player_state(user, now: datetime | None = None, public: dict[str, Any] | None = None) -> dict[str, Any]:
now = now or timezone.now()
public = public or public_state(now)
balance = balance_of(user)
participation = (Participation.objects.filter(user=user, round_id=public["round_id"]).first()
if public["round_id"] else None)
can_bet = public["can_participate"] and participation is None and balance.spendable_sats >= public["bet_amount_sats"]
blocker = ""
if not can_bet:
if participation is not None:
blocker = "" # the bet's own status already says it
elif not public["can_participate"]:
blocker = public["message"] if public["state"] != "open" else ""
elif balance.total_sats >= public["bet_amount_sats"]:
blocker = "Il saldo include fondi ancora in conferma: potrai puntare quando saranno confermati."
else:
blocker = f"Per puntare servono {public['bet_amount_text']} spendibili: deposita dal portafoglio."
return {
"spendable_sats": balance.spendable_sats, "spendable_text": plm_text(balance.spendable_sats),
"incoming_sats": balance.incoming_sats, "incoming_text": plm_text(balance.incoming_sats),
"participation": _participation_block(participation) if participation else None,
"can_bet": can_bet, "bet_blocker": blocker,
"last_result": _last_result(user, public["round_id"]),
}
def full_state(user, now: datetime | None = None) -> dict[str, Any]:
"""The public state plus the player's own block, for `/app/stato/`."""
now = now or timezone.now()
public = public_state(now)
return {**public, "me": player_state(user, now, public)}
+176
View File
@@ -0,0 +1,176 @@
"""The player area (WEB-20 .. WEB-27, roadmap A7). Every view needs a session and reads or changes only the
signed-in player's own data (WEB-03): no view takes a user id from the request."""
import io
from uuid import UUID, uuid4
import qrcode
import qrcode.image.svg
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from apps.lottery.addresses import participant_address
from apps.lottery.balances import balance_of
from apps.lottery.errors import LedgerError
from apps.lottery.format import plm_text
from apps.lottery.ledger import get_ledger
from apps.lottery.messages import ledger_error_text
from apps.lottery.models import SATS_PER_PLM, Movement
from apps.lottery.player import full_state, player_state
from apps.lottery.status import public_state
# The test deposits a player can ask for on the simulated ledger (WEB-26): fixed, so a tampered form gets nothing else.
SIMULATED_DEPOSITS_PLM = (10, 50, 100)
KIND_LABELS = {"deposit": "Deposito", "bet": "Puntata", "win": "Vincita", "refund": "Rimborso", "withdrawal": "Prelievo"}
STATUS_LABELS = {"pending": "In conferma", "confirmed": "Confermato", "failed": "Non riuscito"}
MOVEMENTS_PER_PAGE = 25
def _uuid(value: str | None) -> UUID | None:
try:
return UUID(value or "")
except ValueError:
return None
# --- play --------------------------------------------------------------------------------------
@never_cache
@login_required
def play(request):
"""«Gioca»: the round, the player's funds and their bet in it (WEB-20)."""
state = full_state(request.user)
return render(request, "web/app_home.html", {"s": state, "me": state["me"], "poll_url": "/app/stato/"})
@never_cache
@login_required
def player_state_json(request):
"""The same, as JSON, for the page to poll (WEB-05, WEB-27): the player's own data only."""
return JsonResponse(full_state(request.user))
@never_cache
@login_required
def bet(request):
"""The bet in two steps (WEB-22): GET shows round and amount and asks for an explicit confirmation; POST sends
it. The server decides — round, deadline, quota, limits and funds are all checked again in the ledger — and
the request carries its own idempotency key, so a double send is one bet (WEB-23)."""
public = public_state()
if request.method == "POST":
round_id = request.POST.get("round_id", "")
request_id = _uuid(request.POST.get("request_id"))
if not round_id.isdigit() or request_id is None:
messages.error(request, ledger_error_text("missing_request_id", {}))
return redirect("web:app-home")
try:
result = get_ledger().place_bet(request.user, int(round_id), request_id=request_id)
except LedgerError as error:
messages.error(request, ledger_error_text(error.code, error.params))
return redirect("web:app-home")
if result.replayed:
messages.info(request, "Questa puntata era già stata registrata: non è stata addebitata due volte.")
else:
messages.success(request, "Puntata inviata: è in attesa di conferma.")
return redirect("web:app-home")
me = player_state(request.user, public=public)
if not me["can_bet"]:
if me["participation"] is not None:
text = ledger_error_text("already_betting", {})
else:
text = me["bet_blocker"] or ledger_error_text("round_closing", {})
messages.error(request, text)
return redirect("web:app-home")
return render(request, "web/bet_confirm.html", {"s": public, "me": me, "request_id": uuid4()})
# --- wallet ------------------------------------------------------------------------------------
def _network_label() -> str:
return {"regtest": "PLM regtest (rete di prova)", "mainnet": "PLM mainnet"}[settings.PLM_NETWORK]
@never_cache
@login_required
def wallet(request):
"""«Portafoglio»: spendable funds apart from funds in confirmation, and where to deposit (WEB-21)."""
balance = balance_of(request.user)
pending = Movement.objects.filter(user=request.user, kind="deposit", status="pending").order_by("-created_at")
context = {
"spendable_text": plm_text(balance.spendable_sats), "incoming_text": plm_text(balance.incoming_sats),
"pending_deposits": [{"amount_text": plm_text(m.amount_sats), "since": m.created_at} for m in pending],
"address": participant_address(request.user), "network_label": _network_label(),
"simulated": settings.LEDGER_BACKEND == "simulated",
"simulated_amounts": [{"plm": n, "text": plm_text(n * SATS_PER_PLM)} for n in SIMULATED_DEPOSITS_PLM],
"request_id": uuid4(),
}
return render(request, "web/wallet.html", context)
@never_cache
@login_required
def wallet_qr(request):
"""The QR of the player's own deposit address — never an address taken from the request (WEB-03, WEB-21)."""
image = qrcode.make(participant_address(request.user), image_factory=qrcode.image.svg.SvgPathImage, box_size=10)
buffer = io.BytesIO()
image.save(buffer)
return HttpResponse(buffer.getvalue(), content_type="image/svg+xml")
@never_cache
@login_required
@require_POST
def simulated_deposit(request):
"""Test funds for the simulated ledger (WEB-26): they arrive «in conferma» and the worker confirms them a few
seconds later, so the whole path can be seen. Not available when the ledger is real."""
if settings.LEDGER_BACKEND != "simulated":
raise Http404
request_id = _uuid(request.POST.get("request_id"))
amount = request.POST.get("amount", "")
if request_id is None or not amount.isdigit() or int(amount) not in SIMULATED_DEPOSITS_PLM:
messages.error(request, "La richiesta di deposito non è valida.")
return redirect("web:wallet")
try:
result = get_ledger().deposit(request.user, int(amount) * SATS_PER_PLM, request_id=request_id, confirmed=False)
except LedgerError as error:
messages.error(request, ledger_error_text(error.code, error.params))
return redirect("web:wallet")
if result.replayed:
messages.info(request, "Questo deposito era già stato registrato.")
else:
messages.success(request, f"Deposito di prova di {plm_text(int(amount) * SATS_PER_PLM)} in conferma.")
return redirect("web:wallet")
# --- history -----------------------------------------------------------------------------------
@never_cache
@login_required
def movements(request):
"""«Movimenti»: deposits, bets, wins and withdrawals of this player, newest first (WEB-25)."""
queryset = (Movement.objects.filter(user=request.user).select_related("chain_transaction")
.order_by("-created_at", "-id"))
page = Paginator(queryset, MOVEMENTS_PER_PAGE).get_page(request.GET.get("pagina"))
rows = []
for movement in page:
txid = movement.chain_transaction.current_txid if movement.chain_transaction_id else None
rows.append({
"when": movement.created_at, "kind": KIND_LABELS[movement.kind], "status": STATUS_LABELS[movement.status],
"status_code": movement.status, "amount_text": ("+" if movement.amount_sats > 0 else "") + plm_text(movement.amount_sats),
"credit": movement.amount_sats > 0, "round_id": movement.round_id,
"txid": txid, "txid_short": f"{txid[:10]}…{txid[-6:]}" if txid else "",
"txid_url": settings.EXPLORER_TX_URL.replace("{txid}", txid) if txid and settings.EXPLORER_TX_URL else "",
"simulated": bool(txid) and settings.LEDGER_BACKEND == "simulated",
})
return render(request, "web/movements.html", {"rows": rows, "page": page})
+23
View File
@@ -36,7 +36,30 @@ if (typeof document !== "undefined") {
const setText = (name, value) => { const el = field(name); if (el && el.textContent !== String(value)) el.textContent = value; };
const setHidden = (name, hidden) => { const el = field(name); if (el) el.hidden = hidden; };
const me = (name) => document.querySelector(`[data-me="${name}"]`);
const setMe = (name, value) => { const el = me(name); if (el && el.textContent !== String(value)) el.textContent = value; };
const hideMe = (name, hidden) => { const el = me(name); if (el) el.hidden = hidden; };
/* The player's own block (play screen only): funds, the bet's status, whether a bet can be placed. */
function renderMe(m) {
setMe("spendable_text", m.spendable_text);
setMe("incoming_text", m.incoming_text);
hideMe("incoming-line", !m.incoming_sats);
const p = m.participation;
hideMe("participation-box", !p);
setMe("participation_label", p ? p.label : "");
const badge = me("participation_label");
if (badge) badge.dataset.status = p ? p.status : "";
setMe("participation_message", p ? p.message : "");
hideMe("bet-form", !m.can_bet);
setMe("bet_blocker", m.bet_blocker);
hideMe("bet_blocker", !m.bet_blocker);
setMe("last_result", m.last_result);
hideMe("last_result", !m.last_result);
}
function render(s) {
if (s.me) renderMe(s.me);
card.dataset.state = s.state;
offsetMs = serverOffsetMs(s.server_now, Date.now());
closesAt = s.closes_at || "";
+35
View File
@@ -87,3 +87,38 @@ input[type=text], input[type=password] { width: 100%; min-height: 2.75rem; paddi
.stats dd .hint { font-size: .85rem; font-weight: 400; }
.actions { margin: 0; }
.button.big { min-height: 3.25rem; padding-inline: 2.2rem; font-size: 1.15rem; }
/* Player area (WEB-20 .. WEB-27) */
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.nav a[aria-current="page"] { font-weight: 700; border-bottom: 2px solid var(--accent); }
.message.info { background: var(--bg); color: var(--text); border: 1px solid var(--line); }
.status-box { margin: 0 0 1rem; }
.badge { display: inline-block; margin: 0 0 .4rem; padding: .15rem .7rem; border-radius: 999px; font-size: .9rem; font-weight: 600;
background: var(--bg); border: 1px solid var(--line); color: var(--text); }
.badge[data-status="confirmed"] { background: var(--ok-bg); color: var(--ok); border-color: var(--ok); }
.badge[data-status="pending"] { border-color: var(--accent); color: var(--accent); }
.badge[data-status="rejected"], .badge[data-status="excluded"], .badge[data-status="failed"] { background: var(--error-bg); color: var(--error); border-color: var(--error); }
.result { font-weight: 600; margin: 1rem 0 0; }
select { min-height: 2.75rem; padding: .5rem .75rem; font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--line); border-radius: 8px; }
.copy-row { display: flex; gap: .5rem; align-items: stretch; flex-wrap: wrap; }
.address { flex: 1 1 14rem; min-width: 0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .9rem; }
input[type=text].address { width: auto; }
.qr { display: block; margin: 1rem 0; background: #fff; padding: .5rem; border-radius: 8px; max-width: 100%; height: auto; }
.plain { list-style: none; padding: 0; margin: 0; }
.table-wrap { overflow-x: auto; }
.movements { width: 100%; border-collapse: collapse; background: var(--surface); }
.movements th, .movements td { padding: .6rem .7rem; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
.movements .num { text-align: right; font-variant-numeric: tabular-nums; }
.credit { color: var(--ok); } .debit { color: var(--text); }
.pager { display: flex; flex-wrap: wrap; gap: .8rem; align-items: center; justify-content: space-between; margin-block: 1rem; }
.button.secondary.big { margin-left: .5rem; }
/* On a phone the movements are stacked cards, so the amount is never scrolled out of sight. */
@media (max-width: 40rem) {
.movements, .movements tbody, .movements tr, .movements td { display: block; width: 100%; }
.movements thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
.movements tr { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); margin-bottom: .8rem; padding: .3rem .8rem; }
.movements td { display: flex; justify-content: space-between; gap: 1rem; padding: .4rem 0; border: 0; white-space: normal; text-align: right; }
.movements td::before { content: attr(data-label); color: var(--muted); font-size: .9rem; text-align: left; }
.movements td.num { text-align: right; }
}
+28
View File
@@ -0,0 +1,28 @@
/* The wallet's «Copia» button (WEB-21). Without JavaScript the address is a read-only field the visitor can select
and copy; with it, a button appears that copies it and says so. No dependencies, no inline code. */
function copyText(text, clipboard) {
if (clipboard && typeof clipboard.writeText === "function") return clipboard.writeText(text);
return Promise.reject(new Error("clipboard unavailable"));
}
if (typeof module !== "undefined") module.exports = { copyText };
if (typeof document !== "undefined") {
document.querySelectorAll("[data-copy-target]").forEach((button) => {
const input = document.getElementById(button.dataset.copyTarget);
const status = document.querySelector("[data-copy-status]");
if (!input) return;
button.hidden = false;
button.addEventListener("click", async () => {
let message = "Indirizzo copiato.";
try {
await copyText(input.value, navigator.clipboard);
} catch (error) {
input.select(); // the clipboard is not available here: leave the address selected for the visitor to copy
message = "Non riesco a copiare da solo: l'indirizzo è selezionato, copialo a mano.";
}
if (status) { status.textContent = message; status.hidden = false; }
});
});
}
+26
View File
@@ -0,0 +1,26 @@
{# The state of the round, shared by the public home and the play screen. `s` = public_state, `poll_url` = what the page polls. #}
<section id="round-card" class="card round-card" data-state="{{ s.state }}" data-poll-url="{{ poll_url }}"
data-server-now="{{ s.server_now }}" data-closes-at="{{ s.closes_at|default:'' }}" aria-labelledby="round-state">
<p class="state-label" id="round-state" data-field="label" aria-live="polite">{{ s.label }}</p>
<p class="state-message" data-field="message">{{ s.message }}</p>
<p class="countdown"{% if s.seconds_left is None %} hidden{% endif %} data-field="countdown-line">
Chiude fra <strong class="clock" data-field="countdown">{{ s.countdown_text|default:'00:00' }}</strong>
<span class="hint">(ora del server)</span>
</p>
<dl class="stats">
<div><dt>Quota</dt><dd data-field="bet_amount_text">{{ s.bet_amount_text }}</dd></div>
<div><dt>Montepremi confermato</dt><dd data-field="jackpot_text">{{ s.jackpot_text }}</dd></div>
<div><dt>Giocatori</dt><dd><span data-field="confirmed_players">{{ s.confirmed_players }}</span>
<span class="hint" data-field="pending"{% if not s.pending_players %} hidden{% endif %}>+<span data-field="pending_players">{{ s.pending_players }}</span> in conferma</span></dd></div>
</dl>
{% if show_participate %}
<p class="actions"{% if not s.can_participate %} hidden{% endif %} data-field="participate-line">
<a class="button big" href="{% url 'web:app-home' %}" data-field="participate">Partecipa</a>
</p>
{% endif %}
<p class="hint" data-field="connection" role="status" hidden>Connessione persa: i dati potrebbero non essere aggiornati. Riprovo…</p>
<noscript><p class="hint">Senza JavaScript la pagina non si aggiorna da sola: ricaricala per vedere lo stato più recente.</p></noscript>
</section>
+25 -2
View File
@@ -1,6 +1,29 @@
{% extends "web/base.html" %}
{% load static %}
{% block title %}Gioca · PLM Lottery{% endblock %}
{% block head %}<script src="{% static 'web/home.js' %}" defer></script>{% endblock %}
{% block content %}
<h1>Area giocatore</h1>
<p>Ciao {{ user.get_username }}. La schermata di gioco è in costruzione.</p>
<h1>Gioca</h1>
{% include "web/_round_card.html" with poll_url=poll_url show_participate=False %}
<section class="card" aria-labelledby="your-bet">
<h2 id="your-bet">La tua puntata</h2>
<dl class="stats">
<div><dt>Saldo spendibile</dt><dd data-me="spendable_text">{{ me.spendable_text }}</dd></div>
<div data-me="incoming-line"{% if not me.incoming_sats %} hidden{% endif %}><dt>In conferma</dt><dd data-me="incoming_text">{{ me.incoming_text }}</dd></div>
</dl>
<div data-me="participation-box" class="status-box"{% if not me.participation %} hidden{% endif %}>
<p class="badge" data-me="participation_label" data-status="{{ me.participation.status }}">{{ me.participation.label }}</p>
<p data-me="participation_message">{{ me.participation.message }}</p>
</div>
<p class="actions" data-me="bet-form"{% if not me.can_bet %} hidden{% endif %}>
<a class="button big" href="{% url 'web:bet' %}">Punta {{ s.bet_amount_text }}</a>
</p>
<p class="hint" data-me="bet_blocker"{% if not me.bet_blocker %} hidden{% endif %}>{{ me.bet_blocker }}</p>
{% if not me.can_bet and not me.participation and not me.bet_blocker %}<p class="hint" data-me="idle"></p>{% endif %}
<p class="result" data-me="last_result"{% if not me.last_result %} hidden{% endif %}>{{ me.last_result }}</p>
</section>
{% endblock %}
+6 -2
View File
@@ -16,8 +16,12 @@
<nav class="nav" aria-label="Principale">
<a href="{% url 'web:home' %}">Home</a>
{% if user.is_authenticated %}
<a href="{% url 'web:app-home' %}">Gioca</a>
<a href="{% url 'accounts:profile' %}">Profilo</a>
{% 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>
<a href="{% url 'web:wallet' %}"{% if current == 'web:wallet' %} aria-current="page"{% endif %}>Portafoglio</a>
<a href="{% url 'web:movements' %}"{% if current == 'web:movements' %} aria-current="page"{% endif %}>Movimenti</a>
<a href="{% url 'accounts:profile' %}"{% if current == 'accounts:profile' %} aria-current="page"{% endif %}>Profilo</a>
{% endwith %}
<form class="inline" method="post" action="{% url 'accounts:logout' %}">
{% csrf_token %}
<button class="link-button" type="submit">Esci ({{ user.get_username }})</button>
+21
View File
@@ -0,0 +1,21 @@
{% extends "web/base.html" %}
{% block title %}Conferma la puntata · PLM Lottery{% endblock %}
{% block content %}
<h1>Conferma la puntata</h1>
<section class="card narrow">
<dl class="facts">
<dt>Round</dt><dd>{{ s.round_id }}</dd>
<dt>Importo</dt><dd><strong>{{ s.bet_amount_text }}</strong></dd>
<dt>Il round chiude alle</dt><dd>{{ s.closes_at_text }}</dd>
<dt>Saldo spendibile</dt><dd>{{ me.spendable_text }}</dd>
</dl>
<p class="hint">La puntata verrà addebitata subito e partecipa all'estrazione appena confermata. Il montepremi si divide 70% al vincitore e 30% alla piattaforma.</p>
<form method="post" action="{% url 'web:bet' %}">
{% csrf_token %}
<input type="hidden" name="round_id" value="{{ s.round_id }}">
<input type="hidden" name="request_id" value="{{ request_id }}">
<button class="button big" type="submit">Conferma e punta {{ s.bet_amount_text }}</button>
<a class="button secondary big" href="{% url 'web:app-home' %}">Annulla</a>
</form>
</section>
{% endblock %}
+2 -23
View File
@@ -5,27 +5,6 @@
<h1>PLM Lottery</h1>
<p class="lead">Una lotteria a round: ogni giocatore punta la stessa quota, si estrae un vincitore, il montepremi si divide 70% a lui e 30% alla piattaforma.</p>
<section id="round-card" class="card round-card" data-state="{{ s.state }}" data-poll-url="{% url 'web:state' %}"
data-server-now="{{ s.server_now }}" data-closes-at="{{ s.closes_at|default:'' }}" aria-labelledby="round-state">
<p class="state-label" id="round-state" data-field="label" aria-live="polite">{{ s.label }}</p>
<p class="state-message" data-field="message">{{ s.message }}</p>
<p class="countdown"{% if s.seconds_left is None %} hidden{% endif %} data-field="countdown-line">
Chiude fra <strong class="clock" data-field="countdown">{{ s.countdown_text|default:'00:00' }}</strong>
<span class="hint">(ora del server)</span>
</p>
<dl class="stats">
<div><dt>Quota</dt><dd data-field="bet_amount_text">{{ s.bet_amount_text }}</dd></div>
<div><dt>Montepremi confermato</dt><dd data-field="jackpot_text">{{ s.jackpot_text }}</dd></div>
<div><dt>Giocatori</dt><dd><span data-field="confirmed_players">{{ s.confirmed_players }}</span>
<span class="hint" data-field="pending"{% if not s.pending_players %} hidden{% endif %}>+<span data-field="pending_players">{{ s.pending_players }}</span> in conferma</span></dd></div>
</dl>
<p class="actions"{% if not s.can_participate %} hidden{% endif %} data-field="participate-line">
<a class="button big" href="{% url 'web:app-home' %}" data-field="participate">Partecipa</a>
</p>
<p class="hint" data-field="connection" role="status" hidden>Connessione persa: i dati potrebbero non essere aggiornati. Riprovo…</p>
<noscript><p class="hint">Senza JavaScript la pagina non si aggiorna da sola: ricaricala per vedere lo stato più recente.</p></noscript>
</section>
{% url 'web:state' as poll_url %}
{% include "web/_round_card.html" with poll_url=poll_url show_participate=True %}
{% endblock %}
+33
View File
@@ -0,0 +1,33 @@
{% extends "web/base.html" %}
{% block title %}Movimenti · PLM Lottery{% endblock %}
{% block content %}
<h1>Movimenti</h1>
{% if rows %}
<div class="table-wrap">
<table class="movements">
<caption class="visually-hidden">I tuoi movimenti, dal più recente</caption>
<thead><tr><th scope="col">Data (UTC)</th><th scope="col">Operazione</th><th scope="col">Stato</th><th scope="col" class="num">Importo</th><th scope="col">Transazione</th></tr></thead>
<tbody>
{% for row in rows %}
<tr>
<td data-label="Data (UTC)"><time datetime="{{ row.when|date:'c' }}">{{ row.when|date:"d/m/Y H:i:s" }}</time></td>
<td data-label="Operazione">{{ row.kind }}{% if row.round_id %} <span class="hint">round {{ row.round_id }}</span>{% endif %}</td>
<td data-label="Stato"><span class="badge" data-status="{{ row.status_code }}">{{ row.status }}</span></td>
<td data-label="Importo" class="num {% if row.credit %}credit{% else %}debit{% endif %}">{{ row.amount_text }}</td>
<td data-label="Transazione">{% if row.txid %}{% if row.txid_url %}<a href="{{ row.txid_url }}" rel="noopener" title="{{ row.txid }}">{{ row.txid_short }}</a>{% else %}<span title="{{ row.txid }}">{{ row.txid_short }}</span>{% endif %}{% if row.simulated %} <span class="hint">(simulata)</span>{% endif %}{% else %}<span class="hint">—</span>{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if page.paginator.num_pages > 1 %}
<nav class="pager" aria-label="Pagine dei movimenti">
{% 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">Non ci sono ancora movimenti. Deposita dal <a href="{% url 'web:wallet' %}">portafoglio</a> per iniziare.</p>
{% endif %}
{% endblock %}
+66
View File
@@ -0,0 +1,66 @@
{% extends "web/base.html" %}
{% load static %}
{% block title %}Portafoglio · PLM Lottery{% endblock %}
{% block head %}<script src="{% static 'web/wallet.js' %}" defer></script>{% endblock %}
{% block content %}
<h1>Portafoglio</h1>
<section class="card">
<h2>Il tuo saldo</h2>
<dl class="stats">
<div><dt>Spendibile</dt><dd>{{ spendable_text }}</dd></div>
<div><dt>In conferma</dt><dd>{{ incoming_text }}</dd></div>
</dl>
<p class="hint">Il saldo spendibile è quello che puoi usare subito per puntare. I fondi in conferma si aggiungono quando la rete li conferma.</p>
{% if pending_deposits %}
<h3>Depositi in conferma</h3>
<ul class="plain">
{% for deposit in pending_deposits %}<li>{{ deposit.amount_text }} · ricevuto alle {{ deposit.since|time:"H:i:s" }} UTC</li>{% endfor %}
</ul>
{% endif %}
</section>
<section class="card" aria-labelledby="deposit">
<h2 id="deposit">Deposita</h2>
<dl class="facts">
<dt>Rete</dt><dd>{{ network_label }}</dd>
<dt>Indirizzo</dt>
<dd>
<div class="copy-row">
<input id="deposit-address" class="address" type="text" readonly value="{{ address }}" aria-label="Il tuo indirizzo di deposito">
<button class="button secondary small" type="button" data-copy-target="deposit-address" hidden>Copia</button>
</div>
<p class="hint" data-copy-status role="status" hidden></p>
</dd>
</dl>
<img class="qr" src="{% url 'web:wallet-qr' %}" width="200" height="200" alt="QR code del tuo indirizzo di deposito">
{% if simulated %}
<p class="hint">Questo è un indirizzo simulato: in prova nessuna moneta reale si muove.</p>
{% else %}
<p class="hint">Invia solo PLM a questo indirizzo. Il deposito è spendibile dopo le conferme richieste.</p>
{% endif %}
</section>
{% if simulated %}
<section class="card narrow" aria-labelledby="test-deposit">
<h2 id="test-deposit">Fondi di prova</h2>
<p class="hint">Solo in prova: ricevi un deposito simulato che arriva «in conferma» e diventa spendibile pochi secondi dopo.</p>
<form method="post" action="{% url 'web:simulated-deposit' %}">
{% csrf_token %}
<input type="hidden" name="request_id" value="{{ request_id }}">
<div class="field">
<label for="test-amount">Importo</label>
<select id="test-amount" name="amount">
{% for option in simulated_amounts %}<option value="{{ option.plm }}">{{ option.text }}</option>{% endfor %}
</select>
</div>
<button class="button" type="submit">Ricevi fondi di prova</button>
</form>
</section>
{% endif %}
<section class="card">
<h2>Prelievo</h2>
<p class="hint">Il prelievo verso un indirizzo esterno sarà disponibile con l'integrazione della rete.</p>
</section>
{% endblock %}
+8 -2
View File
@@ -1,11 +1,17 @@
from django.urls import path
from . import views
from . import player_views, views
app_name = "web"
urlpatterns = [
path("", views.home, name="home"),
path("stato/", views.state, name="state"),
path("app/", views.app_home, name="app-home"),
path("app/", player_views.play, name="app-home"),
path("app/stato/", player_views.player_state_json, name="player-state"),
path("app/punta/", player_views.bet, name="bet"),
path("app/portafoglio/", player_views.wallet, name="wallet"),
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("health/live", views.health_live, name="health-live"),
]
-8
View File
@@ -1,4 +1,3 @@
from django.contrib.auth.decorators import login_required
from django.db import connection
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
@@ -20,13 +19,6 @@ def state(request):
return JsonResponse(public_state())
@never_cache
@login_required
def app_home(request):
"""Placeholder of the player area (WEB-20): the play screen arrives with A7."""
return render(request, "web/app_home.html")
def health_live(request):
"""Liveness for the container healthcheck: the process answers and the database opens (ARC-73)."""
try:
+3
View File
@@ -164,3 +164,6 @@ if LEDGER_BACKEND == "simulated" and PLM_NETWORK == "mainnet":
# runs in a few minutes on localhost. Real chains ignore both.
SIMULATED_BLOCK_SECONDS = int(os.environ.get("SIMULATED_BLOCK_SECONDS", "20"))
SIMULATED_CONFIRM_SECONDS = int(os.environ.get("SIMULATED_CONFIRM_SECONDS", "5"))
# Where a transaction can be looked up (WEB-24). Empty = no link. `{txid}` is replaced; e.g. https://explorer.example/tx/{txid}
EXPLORER_TX_URL = os.environ.get("EXPLORER_TX_URL", "")
+40 -7
View File
@@ -37,7 +37,9 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
*Codice:* `config/settings.py`, `apps/web/views.py:csrf_failure` ·
*Test:* `tests/django/test_accounts.py::test_the_session_cookie_is_httponly_secure_and_samesite`, `test_a_form_without_the_csrf_token_is_refused`
- **[WEB-03]** Ogni richiesta dell'area giocatore legge o modifica soltanto i
dati dell'utente autenticato; un identificativo di un altro utente dà 404.
dati dell'utente autenticato; **nessuna vista prende un utente dalla richiesta**: un parametro `user` costruito a mano non cambia nulla.
*Stato:* implementato per l'area giocatore (A7) ·
*Test:* `tests/django/test_player.py::test_a_player_never_sees_another_players_data`, `test_user_ids_in_the_request_are_ignored`, `test_every_player_page_needs_a_session`
- **[WEB-04]** Importi e saldi si rappresentano in unità minime intere
([ADR-35](adr/ADR-35-aritmetica-satoshi-interi.md)); i parametri economici e
temporali del round sono fissati alla sua apertura ([ADR-10](adr/ADR-10-parametri-round-fotografati-all-apertura.md)).
@@ -46,7 +48,7 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
- **[WEB-05]** I dati che cambiano (stato del round, saldo, esito) si
aggiornano con richieste periodiche mirate e si recuperano al rientro nella
pagina; ricaricare non perde lo stato salvato.
*Stato:* implementato per la home (A6, [WEB-14]); per l'area giocatore con l'A7.
*Stato:* implementato per la home (A6, [WEB-14]) e per l'area giocatore (A7, [WEB-27]).
- **[WEB-06]** Le pagine sono utilizzabili da smartphone e da desktop e
navigabili da tastiera, con stati distinti di errore, attesa e conferma.
*Stato:* base implementata (A5): layout fluido da 400 px, foglio di stile unico con tema chiaro/scuro, collegamento «Vai al
@@ -105,23 +107,54 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
## 3 · Area giocatore
- **[WEB-20]** «Gioca», «Portafoglio» e «Movimenti» sono schermate separate;
nel flusso principale hanno priorità quota, stato del round e puntata dell'utente.
nel flusso principale hanno priorità quota, stato del round e puntata dell'utente. Il menu segna la sezione corrente (`aria-current`).
*Stato:* implementato (A7) · *Codice:* `apps/web/player_views.py:play`, `apps/web/templates/web/app_home.html` ·
*Test:* `tests/django/test_player.py::test_the_play_screen_shows_the_round_the_funds_and_the_bet_button`, `test_the_bet_button_is_hidden_without_funds_and_says_why`
- **[WEB-21]** Saldo spendibile e fondi in conferma sono distinti. Il deposito
mostra rete, indirizzo, QR, copia e stato delle conferme.
Il **QR** è sempre quello dell'indirizzo del giocatore (mai un indirizzo preso dalla richiesta); «Copia» è un pulsante che compare solo con
JavaScript, e senza di esso l'indirizzo resta un campo di sola lettura da selezionare. Il saldo mostrato include i fondi in conferma
ma la puntata usa solo il saldo spendibile ([BET-07], [ADR-34](adr/ADR-34-saldo-spendibile-saldo-mostrato-due-numeri.md)). Il prelievo arriva con la Fase B (B9).
*Stato:* implementato (A7; indirizzo simulato fino alla B4) ·
*Codice:* `apps/web/player_views.py:wallet`, `wallet_qr`, `apps/web/static/web/wallet.js` ·
*Test:* `tests/django/test_player.py::test_the_wallet_separates_spendable_funds_from_funds_in_confirmation`, `test_the_wallet_shows_network_address_qr_and_a_copy_control`, `test_the_qr_takes_no_address_from_the_request`
- **[WEB-22]** Prima di inviare una puntata si mostrano round e importo; il
server valida disponibilità, quota, limiti e stato del round. Dopo l'invio
si mostra lo stato effettivo (attesa, conferma, rifiuto o esclusione).
*Stato:* validazione e stati implementati nel ledger (A3: round, scadenza, quota del round, limiti, fondi,
`round_closing`, `already_betting`, `round_full`, `bets_suspended`, `balance_pending_confirmation`, rifiuto ed esclusione);
la schermata con l'A7 ·
*Codice:* `apps/lottery/ledger.py:SimulatedLedger.place_bet` · *Test:* `tests/django/test_ledger.py`
anche la schermata (A7): la puntata è in due passi — la schermata di conferma mostra round e importo e non invia nulla; l'invio avviene solo
con «Conferma e punta», e il server ricontrolla tutto (una pagina rimasta aperta mentre il round cambiava è rifiutata con un messaggio chiaro).
Dopo l'invio la pagina mostra lo stato reale e un aggiornamento della pagina, anche da un altro browser, lo ritrova ·
*Codice:* `apps/lottery/ledger.py:SimulatedLedger.place_bet`, `apps/web/player_views.py:bet` ·
*Test:* `tests/django/test_ledger.py`, `tests/django/test_player.py::test_the_confirmation_screen_shows_round_amount_and_funds_and_sends_nothing`, `test_a_stale_confirmation_is_refused_by_the_server_with_a_clear_message`, `test_a_page_reload_recovers_the_saved_state`
- **[WEB-23]** Un doppio invio della stessa richiesta produce una sola
operazione logica (chiave di idempotenza associata alla richiesta).
*Stato:* implementato nel ledger (A3, [ARC-76]); il modulo di invio con l'A7 ·
*Test:* `tests/django/test_ledger.py::test_the_same_bet_request_is_one_bet`
*Stato:* implementato nel ledger (A3, [ARC-76]) e nel modulo di invio (A7): ogni schermata di conferma porta una chiave nuova, e inviarla due volte
è una sola puntata; la stessa conferma aperta in due schede è rifiutata come «hai già una puntata» ·
*Test:* `tests/django/test_ledger.py::test_the_same_bet_request_is_one_bet`, `tests/django/test_player.py::test_sending_the_same_confirmation_twice_makes_one_bet`, `test_the_same_confirmation_opened_in_two_tabs_makes_one_bet`
- **[WEB-24]** Il prelievo mostra, prima della conferma, indirizzo, importo
richiesto, commissione e importo netto previsto. Lo storico distingue lo stato
dell'operazione dal TXID corrente e lo collega all'explorer quando disponibile.
- **[WEB-25]** **Movimenti.** `/app/movimenti/` elenca depositi, puntate, vincite, rimborsi e prelievi del solo giocatore, dal più recente, a pagine di 25,
con data (UTC), operazione, stato (in conferma, confermato, non riuscito), importo con segno e transazione: il TXID abbreviato, collegato all'explorer
se `EXPLORER_TX_URL` è configurato, e marcato «simulata» sul ledger simulato. Da telefono le righe diventano schede, così l'importo non esce mai
dallo schermo; la tabella ha didascalia e intestazioni di colonna.
*Stato:* implementato (A7) ·
*Codice:* `apps/web/player_views.py:movements`, `apps/web/templates/web/movements.html` ·
*Test:* `tests/django/test_player.py::test_the_movements_are_listed_newest_first_with_sign_and_status`, `test_movements_are_paged`, `test_the_txid_links_to_the_explorer_when_one_is_configured`
- **[WEB-26]** **Fondi di prova.** Con il ledger simulato il portafoglio offre un deposito di prova da 10, 50 o 100 PLM che arriva «in conferma» e il worker conferma
pochi secondi dopo ([RND-42]); un importo diverso da quelli offerti non dà nulla, il doppio invio è un solo deposito, e con un ledger reale l'indirizzo non esiste (404)
e il modulo non compare.
*Stato:* implementato (A7) ·
*Codice:* `apps/web/player_views.py:simulated_deposit` ·
*Test:* `tests/django/test_player.py::test_a_test_deposit_arrives_in_confirmation_and_becomes_spendable`, `test_only_the_offered_amounts_are_accepted`, `test_test_deposits_exist_only_on_the_simulated_ledger`
- **[WEB-27]** **Stato del giocatore.** `GET /app/stato/` (solo con sessione, mai in cache) è lo stato pubblico ([WEB-14]) più un blocco `me` con i soli dati del giocatore:
saldo spendibile e in conferma, la sua puntata nel round (stato e testo), se può puntare e perché no, e come è finito il suo ultimo round («hai vinto 21 PLM»,
«non hai vinto»). Una sola funzione (`player_state`) alimenta la pagina e l'endpoint; `home.js` aggiorna lo stato della puntata e i saldi senza ricaricare.
*Stato:* implementato (A7); verificato in un browser reale: dalla conferma «In attesa» a «Confermata» in circa 9 secondi senza ricaricare ·
*Codice:* `apps/lottery/player.py:player_state`, `apps/web/player_views.py:player_state_json`, `apps/web/static/web/home.js` ·
*Test:* `tests/django/test_player.py::test_the_page_and_the_endpoint_tell_the_same_story`, `test_the_player_is_told_how_their_round_ended`
## 4 · Console operativa
+1 -1
View File
@@ -30,7 +30,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore
- [x] **A4 · Ciclo del round e worker.** Apertura, chiusura, estrazione e pagamento 70/30 nel worker (`manage.py run_worker`), con l'estrazione commit-reveal dello stesso algoritmo del motore. *Requisiti:* RND esistenti riletti sul modello nuovo. *Test:* round completo deterministico, ripresa dopo riavvio del worker.
- [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.
- [ ] **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.
- [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.
- [ ] **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.
+595
View File
@@ -0,0 +1,595 @@
"""A7 — the player area: WEB-03, WEB-05, WEB-20..WEB-27, BET-07, ADR-34, ADR-35."""
import html as htmllib
import json
import re
import shutil
import subprocess
from datetime import timedelta
from pathlib import Path
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.test import Client
from django.utils import timezone
from apps.lottery import lifecycle, simulation
from apps.lottery.addresses import participant_address
from apps.lottery.balances import balance_of
from apps.lottery.ledger import SimulatedLedger
from apps.lottery.models import AuditEntry, LotteryConfig, Movement, Participation, Round
ROOT = Path(__file__).resolve().parents[2]
User = get_user_model()
PLM = 100_000_000
BET = 10 * PLM
PASSWORD = "correct-horse-battery"
pytestmark = pytest.mark.django_db
ledger = SimulatedLedger()
PLAYER_URLS = ["/app/", "/app/stato/", "/app/punta/", "/app/portafoglio/", "/app/portafoglio/qr.svg", "/app/movimenti/"]
def make_user(name="mario", funds=BET):
user = User.objects.create_user(name, password=PASSWORD)
if funds:
ledger.deposit(user, funds)
return user
def logged_in(name="mario", funds=BET):
user = make_user(name, funds)
client = Client()
client.force_login(user)
return client, user
def open_round(**kwargs):
kwargs.setdefault("opened_at", timezone.now() - timedelta(seconds=60))
return Round.objects.create(**kwargs)
def post_bet(client, round_, request_id=None):
return client.post("/app/punta/", {"round_id": round_.pk, "request_id": request_id or uuid4()})
def text(response):
"""The visible text of a page: tags removed, entities decoded, whitespace collapsed."""
return re.sub(r"\s+", " ", htmllib.unescape(re.sub(r"<[^>]+>", " ", response.content.decode())))
def messages_of(response):
return re.findall(r'class="message [^"]*">([^<]+)<', response.content.decode())
# --- access: only a signed-in player, only their own data (WEB-03) ----------------------------
@pytest.mark.parametrize("url", PLAYER_URLS)
def test_every_player_page_needs_a_session(client, url):
response = client.get(url)
assert response.status_code == 302 and response["Location"].startswith("/accedi/?next=")
def test_posting_without_a_session_is_refused(client):
assert client.post("/app/punta/", {"round_id": 1, "request_id": uuid4()})["Location"].startswith("/accedi/")
assert client.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": uuid4()})["Location"].startswith("/accedi/")
def test_the_forms_need_the_csrf_token():
user = make_user()
open_round()
csrf = Client(enforce_csrf_checks=True)
csrf.force_login(user)
assert csrf.post("/app/punta/", {"round_id": 1, "request_id": uuid4()}).status_code == 403
assert csrf.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": uuid4()}).status_code == 403
assert Participation.objects.count() == 0 and Movement.objects.filter(kind="deposit").count() == 1
def test_a_player_never_sees_another_players_data():
"""WEB-03: balances, bets, movements and the QR are always the signed-in player's own."""
round_ = open_round()
mario, luigi = Client(), Client()
a, b = make_user("mario"), make_user("luigi", funds=3 * BET)
mario.force_login(a)
luigi.force_login(b)
assert post_bet(luigi, round_).status_code == 302
state = mario.get("/app/stato/").json()["me"]
assert state["participation"] is None and state["spendable_sats"] == BET # not luigi's 2 x BET, not his bet
assert "luigi" not in text(mario.get("/app/movimenti/")) and "luigi" not in text(mario.get("/app/"))
assert "Non ci sono ancora movimenti" not in text(mario.get("/app/movimenti/")) # mario has his own deposit
assert "Puntata" not in text(mario.get("/app/movimenti/")) # luigi's bet is not in mario's history
assert "Puntata" in text(luigi.get("/app/movimenti/"))
assert participant_address(a) != participant_address(b)
assert participant_address(b) not in mario.get("/app/portafoglio/").content.decode()
def test_user_ids_in_the_request_are_ignored():
"""No view takes a user from the request: a forged parameter changes nothing."""
client, mario = logged_in("mario")
other = make_user("luigi", funds=5 * BET)
forged = f"?user={other.pk}&user_id={other.pk}"
assert client.get("/app/stato/" + forged).json()["me"]["spendable_sats"] == BET
assert "luigi" not in text(client.get("/app/movimenti/" + forged)) and "50 PLM" not in text(client.get("/app/movimenti/" + forged))
assert participant_address(other) not in client.get("/app/portafoglio/" + forged).content.decode()
# --- the play screen (WEB-20) -----------------------------------------------------------------
def test_the_play_screen_shows_the_round_the_funds_and_the_bet_button(client):
open_round()
c, _ = logged_in()
page = text(c.get("/app/"))
assert "Puntate aperte" in page and "Saldo spendibile" in page and "10 PLM" in page and "Punta 10 PLM" in page
assert 'href="/app/punta/"' in c.get("/app/").content.decode()
def test_the_bet_button_is_hidden_without_funds_and_says_why():
open_round()
c, _ = logged_in(funds=0)
html = c.get("/app/").content.decode()
assert re.search(r'data-me="bet-form" hidden', html)
assert "servono 10 PLM spendibili" in text(c.get("/app/"))
def test_funds_still_in_confirmation_ask_to_wait():
"""BET-07, ADR-34: the balance on screen is not the balance that can be spent."""
open_round()
user = make_user(funds=0)
ledger.deposit(user, BET, confirmed=False)
c = Client()
c.force_login(user)
page = text(c.get("/app/"))
assert "ancora in conferma" in page and "In conferma" in page
assert not c.get("/app/stato/").json()["me"]["can_bet"]
def test_the_play_screen_says_so_when_betting_is_closed():
open_round(status="drawing")
c, _ = logged_in()
me = c.get("/app/stato/").json()["me"]
assert not me["can_bet"] and "Il vincitore sarà scelto" in me["bet_blocker"]
# --- placing a bet: two steps, explicit confirmation (WEB-22) ---------------------------------
def test_the_confirmation_screen_shows_round_amount_and_funds_and_sends_nothing():
round_ = open_round()
c, user = logged_in()
response = c.get("/app/punta/")
page = text(response)
assert response.status_code == 200
assert re.search(rf"Round {round_.pk} Importo 10 PLM", page)
assert "10 PLM" in page and "Conferma e punta" in page and "Saldo spendibile" in page
assert Participation.objects.count() == 0 and balance_of(user).spendable_sats == BET # looking costs nothing
def test_opening_the_confirmation_does_not_place_the_bet_by_itself():
open_round()
c, user = logged_in()
for _ in range(3):
c.get("/app/punta/")
assert Participation.objects.count() == 0
def test_confirming_places_the_bet_and_shows_its_real_state():
"""WEB-22: after sending, the page says what actually happened — here, waiting for confirmation."""
round_ = open_round()
c, user = logged_in()
response = post_bet(c, round_)
assert response.status_code == 302 and response["Location"] == "/app/"
page = c.get("/app/")
assert "Puntata inviata" in text(page) and "In attesa di conferma" in text(page)
assert re.search(r'data-me="bet-form" hidden', page.content.decode())
bet = Participation.objects.get()
assert (bet.user, bet.round, bet.status, bet.bet_amount_sats) == (user, round_, "pending", BET)
assert balance_of(user).spendable_sats == 0
def test_a_page_reload_recovers_the_saved_state():
"""WEB-22: the state lives on the server; reloading (or coming back) shows the same thing."""
round_ = open_round()
c, _ = logged_in()
post_bet(c, round_)
first = text(c.get("/app/"))
second = text(c.get("/app/"))
assert "In attesa di conferma" in first and "In attesa di conferma" in second
fresh = Client()
fresh.force_login(User.objects.get()) # a new browser, same player
assert "In attesa di conferma" in text(fresh.get("/app/"))
def test_the_status_follows_the_bet_to_confirmation():
round_ = open_round()
c, _ = logged_in()
post_bet(c, round_)
simulation.settle(timezone.now() + timedelta(seconds=30))
page = text(c.get("/app/"))
assert "Confermata" in page and "Partecipi all'estrazione" in page
assert c.get("/app/stato/").json()["me"]["participation"]["status"] == "confirmed"
def test_a_rejected_bet_says_so_and_the_funds_are_back():
round_ = open_round()
c, user = logged_in()
post_bet(c, round_)
ledger.reject_bet(Participation.objects.get(), "refused")
page = text(c.get("/app/"))
assert "Rifiutata" in page and "i fondi sono tornati disponibili" in page
assert balance_of(user).spendable_sats == BET
def test_an_excluded_bet_says_so_and_is_refunded():
round_ = open_round()
c, user = logged_in()
post_bet(c, round_)
bet = Participation.objects.get()
ledger.confirm_bet(bet)
ledger.exclude_bet(bet, "gone from the chain")
page = text(c.get("/app/"))
assert "Esclusa dall'estrazione" in page and "rimborsato" in page
assert balance_of(user).spendable_sats == BET
# --- the double send (WEB-23) ------------------------------------------------------------------
def test_sending_the_same_confirmation_twice_makes_one_bet():
round_ = open_round()
c, user = logged_in(funds=3 * BET)
key = uuid4()
first, second = post_bet(c, round_, key), post_bet(c, round_, key)
assert first.status_code == second.status_code == 302
assert Participation.objects.count() == 1 and Movement.objects.filter(kind="bet").count() == 1
assert balance_of(user).spendable_sats == 2 * BET # charged once
assert "già stata registrata" in " ".join(messages_of(c.get("/app/")))
def test_the_same_confirmation_opened_in_two_tabs_makes_one_bet():
"""Two tabs, two keys: the second is refused as «already betting», nothing is charged twice."""
round_ = open_round()
c, user = logged_in(funds=3 * BET)
post_bet(c, round_)
again = post_bet(c, round_)
assert again["Location"] == "/app/"
assert "Hai già una puntata" in text(c.get("/app/"))
assert Participation.objects.count() == 1 and balance_of(user).spendable_sats == 2 * BET
def test_each_confirmation_screen_carries_its_own_fresh_key():
open_round()
c, _ = logged_in()
keys = {re.search(r'name="request_id" value="([^"]+)"', c.get("/app/punta/").content.decode()).group(1) for _ in range(3)}
assert len(keys) == 3
# --- the server decides (WEB-22) --------------------------------------------------------------
@pytest.mark.parametrize("prepare,expected", [
(lambda r: Round.objects.filter(pk=r.pk).update(status="closing"), "chiuse"),
(lambda r: Round.objects.filter(pk=r.pk).update(opened_at=timezone.now() - timedelta(seconds=700)), "chiuse"),
(lambda r: setattr(LotteryConfig.get(), "new_bets_suspended", True) or LotteryConfig.objects.update(new_bets_suspended=True), "sospese"),
])
def test_a_stale_confirmation_is_refused_by_the_server_with_a_clear_message(prepare, expected):
"""The page was open while the round changed: the server checks everything again."""
round_ = open_round()
c, user = logged_in()
prepare(round_)
response = post_bet(c, round_)
assert response["Location"] == "/app/"
assert expected in " ".join(messages_of(c.get("/app/")))
assert Participation.objects.count() == 0 and balance_of(user).spendable_sats == BET
def test_a_bet_without_enough_funds_is_refused():
round_ = open_round()
c, _ = logged_in(funds=BET - 1)
post_bet(c, round_)
assert "Saldo insufficiente: servono 10 PLM" in " ".join(messages_of(c.get("/app/")))
assert Participation.objects.count() == 0
@pytest.mark.parametrize("data", [
{"round_id": "abc", "request_id": "not-a-uuid"}, {"round_id": "", "request_id": ""}, {"request_id": "x"}, {},
])
def test_a_malformed_request_is_refused_politely(data):
open_round()
c, user = logged_in()
response = c.post("/app/punta/", data)
assert response.status_code == 302 and Participation.objects.count() == 0
assert balance_of(user).spendable_sats == BET
def test_the_confirmation_screen_redirects_when_betting_is_not_possible():
open_round(status="drawing")
c, _ = logged_in()
assert c.get("/app/punta/")["Location"] == "/app/"
assert "Il vincitore sarà scelto" in " ".join(messages_of(c.get("/app/")))
def test_a_player_with_a_bet_cannot_open_a_second_confirmation():
round_ = open_round()
c, _ = logged_in(funds=2 * BET)
post_bet(c, round_)
assert c.get("/app/punta/")["Location"] == "/app/"
assert "Hai già una puntata" in " ".join(messages_of(c.get("/app/")))
# --- polling (WEB-05, WEB-27) -----------------------------------------------------------------
def test_the_player_state_adds_the_players_block_to_the_public_one():
open_round()
c, _ = logged_in()
body = c.get("/app/stato/").json()
assert body["state"] == "open" and set(body["me"]) >= {
"spendable_sats", "spendable_text", "incoming_sats", "incoming_text", "participation", "can_bet", "bet_blocker", "last_result"}
assert "no-store" in c.get("/app/stato/")["Cache-Control"] or "no-cache" in c.get("/app/stato/")["Cache-Control"]
def test_the_page_and_the_endpoint_tell_the_same_story():
round_ = open_round()
c, _ = logged_in()
post_bet(c, round_)
body, page = c.get("/app/stato/").json(), text(c.get("/app/"))
assert body["me"]["participation"]["label"] in page and body["me"]["spendable_text"] in page
def test_the_play_page_polls_the_players_endpoint():
open_round()
c, _ = logged_in()
html = c.get("/app/").content.decode()
assert 'data-poll-url="/app/stato/"' in html and "home.js" in html
# --- how a round ends for the player ----------------------------------------------------------
def test_the_player_is_told_how_their_round_ended():
"""The winner reads «hai vinto», the others «non hai vinto»; the round then belongs to the past."""
t0 = timezone.now()
round_ = lifecycle.open_new_round_if_needed(t0)
clients = {}
for name in ("a", "b", "c"):
c, _ = logged_in(name)
post_bet(c, round_)
clients[name] = c
for bet in Participation.objects.all():
ledger.confirm_bet(bet)
from tests.django.test_lifecycle import FakeChain
chain, end = FakeChain(1000), round_.opened_at + timedelta(seconds=round_.duration_seconds)
lifecycle.tick(now=end, chain=chain)
chain.tip = 1003
lifecycle.tick(now=end, chain=chain)
done = end + timedelta(minutes=5)
simulation.settle(done)
lifecycle.tick(now=done, chain=chain)
round_.refresh_from_db()
winner = round_.winner.username
for name, c in clients.items():
line = c.get("/app/stato/").json()["me"]["last_result"]
if name == winner:
assert line == f"Round {round_.pk}: hai vinto 21 PLM." # 70% of 3 x 10
else:
assert line == f"Round {round_.pk}: non hai vinto questa volta."
# --- the wallet (WEB-21) ----------------------------------------------------------------------
def test_the_wallet_separates_spendable_funds_from_funds_in_confirmation():
user = make_user(funds=BET)
ledger.deposit(user, 5 * PLM, confirmed=False)
c = Client()
c.force_login(user)
html = c.get("/app/portafoglio/").content.decode()
page = text(c.get("/app/portafoglio/"))
assert re.search(r"Spendibile</dt><dd>10 PLM", html) and re.search(r"In conferma</dt><dd>5 PLM", html)
assert "Depositi in conferma" in page and "5 PLM" in page
def test_the_wallet_shows_network_address_qr_and_a_copy_control():
c, user = logged_in()
html = c.get("/app/portafoglio/").content.decode()
assert "PLM regtest" in html and participant_address(user) in html
assert 'src="/app/portafoglio/qr.svg"' in html and 'alt="QR code' in html
assert 'data-copy-target="deposit-address"' in html and "readonly" in html # still copyable without JavaScript
assert "wallet.js" in html
def test_the_qr_is_an_svg_of_the_players_own_address():
c, user = logged_in()
response = c.get("/app/portafoglio/qr.svg")
body = response.content.decode()
assert response.status_code == 200 and response["Content-Type"] == "image/svg+xml" and "<svg" in body
other, other_user = logged_in("luigi")
assert other.get("/app/portafoglio/qr.svg").content != response.content # a different address, a different code
assert "no-store" in response["Cache-Control"] or "no-cache" in response["Cache-Control"]
def test_the_qr_takes_no_address_from_the_request():
c, user = logged_in()
plain = c.get("/app/portafoglio/qr.svg").content
assert c.get("/app/portafoglio/qr.svg?address=rplm1evil&data=evil").content == plain
# --- test deposits (WEB-26) -------------------------------------------------------------------
def test_a_test_deposit_arrives_in_confirmation_and_becomes_spendable():
c, user = logged_in(funds=0)
key = uuid4()
response = c.post("/app/portafoglio/deposito-prova/", {"amount": 50, "request_id": key})
assert response["Location"] == "/app/portafoglio/"
page = c.get("/app/portafoglio/")
assert "Deposito di prova di 50 PLM in conferma" in text(page) and "Depositi in conferma" in text(page)
assert (balance_of(user).spendable_sats, balance_of(user).incoming_sats) == (0, 50 * PLM)
simulation.settle(timezone.now() + timedelta(seconds=30))
assert (balance_of(user).spendable_sats, balance_of(user).incoming_sats) == (50 * PLM, 0)
def test_a_test_deposit_sent_twice_is_one_deposit():
c, user = logged_in(funds=0)
key = uuid4()
c.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": key})
c.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": key})
assert Movement.objects.filter(user=user, kind="deposit").count() == 1
assert "già stato registrato" in " ".join(messages_of(c.get("/app/portafoglio/")))
@pytest.mark.parametrize("amount", ["1", "1000000", "-10", "10.5", "abc", "", "9999999999999999"])
def test_only_the_offered_amounts_are_accepted(amount):
"""A tampered form gets nothing."""
c, user = logged_in(funds=0)
c.post("/app/portafoglio/deposito-prova/", {"amount": amount, "request_id": uuid4()})
assert Movement.objects.filter(user=user).count() == 0
assert "non è valida" in " ".join(messages_of(c.get("/app/portafoglio/")))
def test_test_deposits_exist_only_on_the_simulated_ledger(settings, monkeypatch):
"""WEB-26: with a real ledger the endpoint does not exist and the form is not offered."""
c, user = logged_in(funds=0)
assert "Fondi di prova" in c.get("/app/portafoglio/").content.decode()
settings.LEDGER_BACKEND = "chain"
monkeypatch.setattr("apps.web.player_views.participant_address", lambda u: "rplm1realaddress") # HD addresses: phase B
assert c.post("/app/portafoglio/deposito-prova/", {"amount": 10, "request_id": uuid4()}).status_code == 404
assert "Fondi di prova" not in c.get("/app/portafoglio/").content.decode()
assert Movement.objects.filter(user=user).count() == 0
def test_the_test_deposit_is_get_only_safe():
c, _ = logged_in()
assert c.get("/app/portafoglio/deposito-prova/").status_code == 405
# --- movements (WEB-25) -----------------------------------------------------------------------
def test_the_movements_are_listed_newest_first_with_sign_and_status():
round_ = open_round()
c, user = logged_in(funds=2 * BET)
post_bet(c, round_)
ledger.deposit(user, PLM, confirmed=False)
html = c.get("/app/movimenti/").content.decode()
rows = re.findall(r"<tr>(.*?)</tr>", html, re.S)[1:] # without the header row
assert len(rows) == 3
assert "Deposito" in rows[0] and "In conferma" in rows[0] and "+1 PLM" in rows[0] # the newest
assert "Puntata" in rows[1] and "-10 PLM" in rows[1] and "round" in rows[1]
assert "Deposito" in rows[2] and "Confermato" in rows[2] and "+20 PLM" in rows[2]
def test_a_transaction_shows_its_txid_and_says_when_it_is_simulated():
round_ = open_round()
c, user = logged_in()
post_bet(c, round_)
txid = Participation.objects.get().bet_txid
html = c.get("/app/movimenti/").content.decode()
assert f'title="{txid}"' in html and f"{txid[:10]}…{txid[-6:]}" in html and "(simulata)" in html
def test_the_txid_links_to_the_explorer_when_one_is_configured(settings):
settings.EXPLORER_TX_URL = "https://explorer.example/tx/{txid}"
round_ = open_round()
c, user = logged_in()
post_bet(c, round_)
txid = Participation.objects.get().bet_txid
assert f'href="https://explorer.example/tx/{txid}"' in c.get("/app/movimenti/").content.decode()
def test_movements_are_paged():
c, user = logged_in(funds=0)
for _ in range(30):
ledger.deposit(user, PLM)
first = c.get("/app/movimenti/")
assert len(re.findall(r"<tr>", first.content.decode())) == 1 + 25 # header row + 25
assert "Pagina 1 di 2" in text(first) and "Meno recenti" in text(first)
second = c.get("/app/movimenti/?pagina=2")
assert len(re.findall(r"<tr>", second.content.decode())) == 1 + 5 and "Più recenti" in text(second)
assert c.get("/app/movimenti/?pagina=999").status_code == 200 # a page out of range is the last one, not an error
def test_an_empty_history_points_to_the_wallet():
c, _ = logged_in(funds=0)
assert "Non ci sono ancora movimenti" in text(c.get("/app/movimenti/"))
# --- markup, accessibility, scripts -----------------------------------------------------------
@pytest.mark.parametrize("url", ["/app/", "/app/punta/", "/app/portafoglio/", "/app/movimenti/"])
def test_player_pages_use_no_inline_scripts_or_styles(url):
open_round()
c, _ = logged_in()
html = c.get(url, follow=True).content.decode()
inline = [m for m in re.findall(r"<script\b[^>]*>", html) if "src=" not in m]
assert not inline and " style=" not in html and not re.search(r"\son[a-z]+=", html)
def test_the_current_section_is_marked_in_the_navigation():
c, _ = logged_in()
assert re.search(r'<a href="/app/portafoglio/" aria-current="page">Portafoglio</a>', c.get("/app/portafoglio/").content.decode())
assert re.search(r'<a href="/app/movimenti/" aria-current="page">Movimenti</a>', c.get("/app/movimenti/").content.decode())
assert "aria-current" not in c.get("/app/movimenti/").content.decode().split("Movimenti</a>")[0].split("Portafoglio")[0]
def test_the_movements_table_is_accessible_and_stacks_on_a_phone():
c, user = logged_in()
html = c.get("/app/movimenti/").content.decode()
assert "<caption" in html and html.count('scope="col"') == 5
# every cell names itself, so the stacked layout of a phone (site.css) still reads as a list of labelled facts
assert html.count('data-label="Importo"') == 1 and html.count('data-label="Stato"') == 1
css = (ROOT / "apps/web/static/web/site.css").read_text()
assert "@media (max-width: 40rem)" in css and "attr(data-label)" in css
def test_the_wallet_controls_have_labels():
c, _ = logged_in()
html = c.get("/app/portafoglio/").content.decode()
assert 'aria-label="Il tuo indirizzo di deposito"' in html and '<label for="test-amount">' in html
NODE = shutil.which("node")
@pytest.mark.skipif(NODE is None, reason="node is not installed")
def test_the_wallet_script_is_valid_and_copies_through_the_clipboard_api():
script = ROOT / "apps/web/static/web/wallet.js"
subprocess.run([NODE, "--check", str(script)], check=True)
code = f"""
const {{ copyText }} = require('{script}');
(async () => {{
const copied = [];
await copyText('rplm1abc', {{ writeText: async (t) => copied.push(t) }});
let refused = false;
try {{ await copyText('x', undefined); }} catch (e) {{ refused = true; }}
console.log(JSON.stringify({{ copied, refused }}));
}})();
"""
out = subprocess.run([NODE, "-e", code], capture_output=True, text=True, check=True)
assert json.loads(out.stdout) == {"copied": ["rplm1abc"], "refused": True}
def test_every_ledger_error_has_an_italian_text():
from apps.lottery.messages import ledger_error_text
for code in ("no_round_open", "round_closing", "already_betting", "bets_suspended", "missing_request_id",
"idempotency_conflict", "invalid_amount", "round_full"):
assert ledger_error_text(code, {}) and not re.search(r"[a-z]+_[a-z]+", ledger_error_text(code, {}))
assert "10 PLM" in ledger_error_text("insufficient_balance", {"required_sats": BET})
assert "5 PLM" in ledger_error_text("balance_pending_confirmation", {"pending_sats": 5 * PLM})
assert ledger_error_text("something_new", {})
def test_the_audit_records_what_the_player_did():
round_ = open_round()
c, user = logged_in()
post_bet(c, round_)
actions = list(AuditEntry.objects.order_by("id").values_list("action", flat=True))
assert actions == ["deposit_credited", "bet_placed"]