diff --git a/CLAUDE.md b/CLAUDE.md
index 9ce343a..e06245c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
## Project status
-All 10 stages of the original build order are code-complete and unit-tested — 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
```
diff --git a/README.md b/README.md
index a3c4f0c..a6d8230 100644
--- a/README.md
+++ b/README.md
@@ -62,7 +62,7 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file
```
-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
diff --git a/apps/lottery/messages.py b/apps/lottery/messages.py
new file mode 100644
index 0000000..ec707aa
--- /dev/null
+++ b/apps/lottery/messages.py
@@ -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.")
diff --git a/apps/lottery/player.py b/apps/lottery/player.py
new file mode 100644
index 0000000..acb807f
--- /dev/null
+++ b/apps/lottery/player.py
@@ -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)}
diff --git a/apps/web/player_views.py b/apps/web/player_views.py
new file mode 100644
index 0000000..2fc11bb
--- /dev/null
+++ b/apps/web/player_views.py
@@ -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})
diff --git a/apps/web/static/web/home.js b/apps/web/static/web/home.js
index 2880e5c..07202f2 100644
--- a/apps/web/static/web/home.js
+++ b/apps/web/static/web/home.js
@@ -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 || "";
diff --git a/apps/web/static/web/site.css b/apps/web/static/web/site.css
index 283aae2..6f947fa 100644
--- a/apps/web/static/web/site.css
+++ b/apps/web/static/web/site.css
@@ -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; }
+}
diff --git a/apps/web/static/web/wallet.js b/apps/web/static/web/wallet.js
new file mode 100644
index 0000000..6f4e83b
--- /dev/null
+++ b/apps/web/static/web/wallet.js
@@ -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; }
+ });
+ });
+}
diff --git a/apps/web/templates/web/_round_card.html b/apps/web/templates/web/_round_card.html
new file mode 100644
index 0000000..e4e39cd
--- /dev/null
+++ b/apps/web/templates/web/_round_card.html
@@ -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. #}
+ {{ s.label }}
+ Chiude fra {{ s.countdown_text|default:'00:00' }}
+ (ora del server)
+
+ Partecipa
+ Connessione persa: i dati potrebbero non essere aggiornati. Riprovo…
+
+
+ {% if show_participate %}
+
Ciao {{ user.get_username }}. La schermata di gioco è in costruzione.
+{{ me.participation.label }}
+{{ me.participation.message }}
++ Punta {{ s.bet_amount_text }} +
+{{ me.bet_blocker }}
+ {% if not me.can_bet and not me.participation and not me.bet_blocker %}{% endif %} + +{{ me.last_result }}
+