diff --git a/CLAUDE.md b/CLAUDE.md index 49b7ef5..9ce343a 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 — 992 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 — 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. 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 992 tests +python -m pytest # all 1041 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 96ce0f9..a3c4f0c 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 ``` -992 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +1041 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/format.py b/apps/lottery/format.py new file mode 100644 index 0000000..39613fa --- /dev/null +++ b/apps/lottery/format.py @@ -0,0 +1,13 @@ +"""Amounts for people: integer satoshi in, Italian text out (1 PLM = 100,000,000 sat).""" + +from .models import SATS_PER_PLM + + +def plm_text(sats: int) -> str: + """`1000000000` -> `10 PLM`, `70000000` -> `0,7 PLM`, `123450000000` -> `1.234,5 PLM`. Never rounds: the decimals shown + are exactly the satoshi that exist.""" + whole, fraction = divmod(abs(int(sats)), SATS_PER_PLM) + text = f"{whole:,}".replace(",", ".") + if fraction: + text += "," + f"{fraction:08d}".rstrip("0") + return f"{'-' if sats < 0 else ''}{text} PLM" diff --git a/apps/lottery/status.py b/apps/lottery/status.py new file mode 100644 index 0000000..2c39cdc --- /dev/null +++ b/apps/lottery/status.py @@ -0,0 +1,103 @@ +"""What a visitor sees of the lottery right now (WEB-10): one of six states, the quota, the confirmed prize +and the closing time. The same function feeds the page when it is rendered and the endpoint the page polls, +so the two can never tell different stories (WEB-05).""" + +from datetime import datetime, timedelta, timezone as dt_timezone +from typing import Any + +from django.db.models import Count, Sum +from django.utils import timezone + +from .format import plm_text +from .lifecycle import get_active_round +from .models import LotteryConfig, Participation, Round +from .rules import round_deadline, winner_share + +NONE, OPEN, CLOSING, DRAWING, PAYING, MAINTENANCE = "none", "open", "closing", "drawing", "paying", "maintenance" + +LABELS = { + NONE: "Nessun round in corso", + OPEN: "Puntate aperte", + CLOSING: "In chiusura", + DRAWING: "Estrazione in corso", + PAYING: "Pagamento in attesa", + MAINTENANCE: "Manutenzione", +} + + +def iso(moment: datetime) -> str: + return moment.astimezone(dt_timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def clock_text(moment: datetime) -> str: + return moment.astimezone(dt_timezone.utc).strftime("%H:%M:%S") + " UTC" + + +def countdown_text(total_seconds: float) -> str: + """`mm:ss`, or `h:mm:ss` from one hour up — the same text `home.js` writes, so the page reads the same with and + without JavaScript.""" + seconds = max(0, int(total_seconds)) + hours, minutes, secs = seconds // 3600, seconds % 3600 // 60, seconds % 60 + return f"{hours}:{minutes:02d}:{secs:02d}" if hours else f"{minutes:02d}:{secs:02d}" + + +def public_state(now: datetime | None = None) -> dict[str, Any]: + now = now or timezone.now() + config = LotteryConfig.get() + round_ = get_active_round() + + data: dict[str, Any] = { + "server_now": iso(now), "round_id": None, "closes_at": None, "closes_at_text": "", "seconds_left": None, "countdown_text": "", + "bet_amount_sats": config.bet_amount_sats, "bet_amount_text": plm_text(config.bet_amount_sats), + "jackpot_sats": 0, "jackpot_text": plm_text(0), "confirmed_players": 0, "pending_players": 0, + "paused_after_round": config.pause_after_round, "next_round_at": None, "next_round_at_text": "", + } + + if round_ is None: + return _without_round(data, config, now) + + totals = Participation.objects.filter(round=round_, status=Participation.Status.CONFIRMED).aggregate( + players=Count("id"), pool=Sum("bet_amount_sats")) + confirmed_pool = totals["pool"] or 0 + deadline = round_deadline(round_) + data.update( + round_id=round_.pk, + bet_amount_sats=round_.bet_amount_sats, bet_amount_text=plm_text(round_.bet_amount_sats), # the round's own quota + confirmed_players=totals["players"] or 0, + pending_players=Participation.objects.filter(round=round_, status=Participation.Status.PENDING).count(), + # "Confirmed prize": the winner's share of what is already confirmed — never more than will be paid (B-11, B-65). + jackpot_sats=winner_share(confirmed_pool), jackpot_text=plm_text(winner_share(confirmed_pool)), + ) + + if round_.status == Round.Status.OPEN and now < deadline: + if config.new_bets_suspended: # ADR-57: «Sospendi nuove puntate» + return _finish(data, MAINTENANCE, "Le nuove puntate sono sospese. Le puntate già inviate restano valide.") + data.update(closes_at=iso(deadline), closes_at_text=clock_text(deadline), + seconds_left=max(0, int((deadline - now).total_seconds())), + countdown_text=countdown_text((deadline - now).total_seconds())) + message = f"Quota {data['bet_amount_text']}. Il round chiude alle {data['closes_at_text']}." + if config.pause_after_round: + message += " Dopo questo round la lotteria si ferma per manutenzione." + return _finish(data, OPEN, message) + if round_.status in (Round.Status.OPEN, Round.Status.CLOSING): # past the deadline, even if the scheduler lags + return _finish(data, CLOSING, "Le puntate sono chiuse: attendiamo la conferma di quelle già inviate.") + if round_.status == Round.Status.DRAWING: + return _finish(data, DRAWING, "Il vincitore sarà scelto con un blocco della catena che ancora non esisteva alla chiusura.") + return _finish(data, PAYING, "Il vincitore è stato estratto: il pagamento è in attesa di conferma.") + + +def _without_round(data: dict[str, Any], config: LotteryConfig, now: datetime) -> dict[str, Any]: + if config.pause_after_round: + return _finish(data, MAINTENANCE, "La lotteria è ferma per manutenzione. Il prossimo round non è ancora fissato.") + last = Round.objects.filter(status=Round.Status.CLOSED).order_by("-id").first() + if last is not None and last.closed_at is not None: + opens = last.closed_at + timedelta(seconds=last.cooldown_seconds) + if opens > now: + data.update(next_round_at=iso(opens), next_round_at_text=clock_text(opens)) + return _finish(data, NONE, f"Il prossimo round apre alle {data['next_round_at_text']}.") + return _finish(data, NONE, "Il prossimo round sta per aprirsi.") + + +def _finish(data: dict[str, Any], state: str, message: str) -> dict[str, Any]: + data.update(state=state, label=LABELS[state], message=message, can_participate=state == OPEN) + return data diff --git a/apps/web/static/web/home.js b/apps/web/static/web/home.js new file mode 100644 index 0000000..2880e5c --- /dev/null +++ b/apps/web/static/web/home.js @@ -0,0 +1,93 @@ +/* The public home keeps itself current (WEB-05, WEB-10): the server already rendered the state, so this only + (1) runs the countdown against the *server's* clock, never the visitor's, and (2) polls /stato/ — every 5 s while + the page is visible, at once when it becomes visible again or when the countdown ends, slower after errors. + No dependencies, no inline code. */ + +function formatCountdown(totalSeconds) { + const s = Math.max(0, Math.floor(totalSeconds)); + const hours = Math.floor(s / 3600), minutes = Math.floor((s % 3600) / 60), seconds = s % 60; + const two = (n) => String(n).padStart(2, "0"); + return hours > 0 ? `${hours}:${two(minutes)}:${two(seconds)}` : `${two(minutes)}:${two(seconds)}`; +} + +/* How far the visitor's clock is from the server's: add it to Date.now() to get the server's time. */ +function serverOffsetMs(serverNowIso, clientNowMs) { + return Date.parse(serverNowIso) - clientNowMs; +} + +function secondsLeft(closesAtIso, offsetMs, clientNowMs) { + return (Date.parse(closesAtIso) - (clientNowMs + offsetMs)) / 1000; +} + +function pollDelayMs(failures) { + return Math.min(30000, 5000 * Math.pow(2, Math.max(0, failures))); +} + +if (typeof module !== "undefined") { + module.exports = { formatCountdown, serverOffsetMs, secondsLeft, pollDelayMs }; +} + +if (typeof document !== "undefined") { + const card = document.getElementById("round-card"); + if (card) { + const field = (name) => card.querySelector(`[data-field="${name}"]`); + let offsetMs = 0, closesAt = "", failures = 0, timer = null, polling = false; + + 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; }; + + function render(s) { + card.dataset.state = s.state; + offsetMs = serverOffsetMs(s.server_now, Date.now()); + closesAt = s.closes_at || ""; + setText("label", s.label); + setText("message", s.message); + setText("bet_amount_text", s.bet_amount_text); + setText("jackpot_text", s.jackpot_text); + setText("confirmed_players", s.confirmed_players); + setText("pending_players", s.pending_players); + setHidden("pending", !s.pending_players); + setHidden("participate-line", !s.can_participate); + setHidden("countdown-line", !closesAt); + tickClock(); + } + + function tickClock() { + if (!closesAt) return; + const left = secondsLeft(closesAt, offsetMs, Date.now()); + setText("countdown", formatCountdown(left)); + if (left <= 0 && !polling) poll(); // the round has just closed: ask the server what happens next + } + + async function poll() { + if (polling) return; + polling = true; + clearTimeout(timer); + try { + const response = await fetch(card.dataset.pollUrl, { headers: { Accept: "application/json" }, cache: "no-store" }); + if (!response.ok) throw new Error(String(response.status)); + render(await response.json()); + failures = 0; + setHidden("connection", true); + } catch (error) { + failures += 1; + setHidden("connection", false); + } finally { + polling = false; + schedule(); + } + } + + function schedule() { + clearTimeout(timer); + if (!document.hidden) timer = setTimeout(poll, pollDelayMs(failures)); + } + + document.addEventListener("visibilitychange", () => { if (document.hidden) clearTimeout(timer); else poll(); }); + setInterval(tickClock, 1000); + offsetMs = serverOffsetMs(card.dataset.serverNow, Date.now()); + closesAt = card.dataset.closesAt || ""; + tickClock(); + schedule(); + } +} diff --git a/apps/web/static/web/site.css b/apps/web/static/web/site.css index c0058bb..283aae2 100644 --- a/apps/web/static/web/site.css +++ b/apps/web/static/web/site.css @@ -68,3 +68,22 @@ input[type=text], input[type=password] { width: 100%; min-height: 2.75rem; paddi @media (min-width: 40rem) { h1 { font-size: 2rem; } .card { padding: 1.6rem; } } @media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } } + +/* `hidden` must win over any `display` set above. */ +[hidden] { display: none !important; } + +/* Public home: the state of the round (WEB-10). The colour is a cue, never the only one — the label says it too. */ +.lead { color: var(--muted); max-width: 40rem; } +.round-card { --state: var(--muted); border-left: .4rem solid var(--state); } +.round-card[data-state="open"] { --state: var(--ok); } +.round-card[data-state="closing"], .round-card[data-state="drawing"], .round-card[data-state="paying"] { --state: var(--accent); } +.round-card[data-state="maintenance"] { --state: var(--error); } +.state-label { font-size: 1.35rem; font-weight: 700; margin: 0 0 .3rem; color: var(--state); } +.state-message { margin: 0 0 1rem; } +.countdown { font-size: 1.1rem; margin: 0 0 1rem; } +.clock { font-size: 1.8rem; font-variant-numeric: tabular-nums; } +.stats { display: grid; gap: .8rem 1.5rem; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); margin: 0 0 1.2rem; } +.stats dt { color: var(--muted); font-size: .9rem; } .stats dd { margin: 0; font-size: 1.25rem; font-weight: 600; } +.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; } diff --git a/apps/web/templates/web/base.html b/apps/web/templates/web/base.html index 5a091ec..800e461 100644 --- a/apps/web/templates/web/base.html +++ b/apps/web/templates/web/base.html @@ -6,6 +6,7 @@
Il sito è in costruzione.
+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.
+ +{{ s.label }}
+ + ++ Chiude fra {{ s.countdown_text|default:'00:00' }} + (ora del server) +
+ ++ Partecipa +
+Connessione persa: i dati potrebbero non essere aggiornati. Riprovo…
+ +