6 Commits
Author SHA1 Message Date
davideandClaude Sonnet 5 bae08f2759 Extract inline JS from index.html/admin.html into app.js/admin.js
Mirrors the earlier CSS extraction (style.css/admin.css) — app/static/ is
now split cleanly by file type (markup, styles, script) instead of mixing
JS inline in the HTML. No behavior change: the script content moved
verbatim, referenced via <script src>. FastAPI's existing StaticFiles mount
serves the new files automatically, same as the CSS files already do.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 11:05:38 +02:00
davideandClaude Sonnet 5 aae0961c94 Bring docs in sync with recent features (pending balance, SSE, per-player reveal)
CLAUDE.md: bumped the stale test count (54 -> 76), added "Balance display"
and "Real-time updates (SSE)" sections, and rewrote the DRAW section's
frontend-reveal paragraph to describe the actual current behavior (dual
status/result boxes gated by user_played, closes_at-anchored reveal delay,
localStorage persistence, the last-round-result backstop) instead of the
older single-box design. Refined the "no history endpoints" known gap now
that GET /users/me/last-round-result exists (still not general history).

README.md: same test count fix, expanded coverage list.

docs/: fixed a pre-existing broken link in setup.md (admin-guide.md ->
guida-admin.md), added a note in running-the-server.md that editing the
bind-mounted Caddyfile needs an explicit `docker compose restart caddy`
(discovered while adding the SSE Caddy config in a prior change), and
rewrote guida-utente.md's draw/reveal section plus the balance/withdrawal
sections to match what the UI actually does now. guida-admin.md was
reviewed but needed no changes.

app/static/style.css: dropped `.toast.info`, dead since the toast-based
loss notification it styled was replaced by the persistent result box.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 11:05:27 +02:00
davideandClaude Sonnet 5 dda5bd14e1 Wire up the SSE push channel in both frontend dashboards
app/static/index.html: opens an EventSource against /rounds/stream (no auth
needed, see the previous commit) alongside the existing polling loops. On an
"update" notification, immediately re-runs the same refreshes polling would
eventually do (refreshRound/refreshMe/checkLastRoundResult when logged in,
refreshChainStatusOnly when logged out). Also reacts to the browser's "open"
event, which fires on the initial connection and on every automatic
reconnect — this re-syncs right away instead of leaving the page on stale
state until the next event or poll tick, which matters most right after a
dropped connection comes back.

app/static/admin.html: same channel, refreshing the chain-status bar and
whichever admin section is currently open (Utenti/Round/Transazioni
pendenti/Audit log) instead of requiring a manual tab switch to see new data.

Polling intervals are untouched in both pages — this is purely additive, so
a blocked/dropped SSE connection just degrades to the pre-existing behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 10:52:50 +02:00
davideandClaude Sonnet 5 f229f91632 Add server-push (SSE) notifications for round/bet/balance state changes
Frontend dashboards previously found out about state changes only on their
next poll tick (up to 15s, or 3s during a draw) — this adds a push channel
so updates land as soon as they happen instead.

- app/rounds/events.py: a small in-process pub/sub (RoundEventBroadcaster).
  The message carries no payload — it's just a "something changed, go
  refetch" signal, so it needs no auth and no knowledge of who's allowed to
  see what; personalization stays entirely in the existing REST endpoints.
- GET /rounds/stream: an SSE endpoint exposing that channel, with keep-alive
  comments so it survives idle periods behind a reverse proxy, and a
  defensive MAX_SUBSCRIBERS cap (well above the ~100 concurrent users
  expected) — past it, the endpoint returns 503 instead of opening a stream,
  and callers just keep working off polling.
- publish() calls added at every point that actually changes what a
  dashboard would want to know: new round opened, round status transitions
  (closing/drawing/paying_out/closed), a bet or withdrawal broadcast, any
  pending tx confirming (bet/withdrawal/payout), a deposit credited, and a
  new block tip arriving (the exact moment the "drawing" phase is waiting on).
- Caddyfile: excludes /rounds/stream from gzip encoding, since compression
  would buffer output and defeat the point of a live stream.

Single-process only by design for now (no cross-worker fan-out) and the
notification is a generic broadcast rather than a per-user channel — both
are deliberate scope decisions for the current ~100-user, single-container
deployment, not oversights. Polling is left fully in place as a fallback;
this is purely additive.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 10:52:07 +02:00
davideandClaude Sonnet 5 6a857f0e07 Show pending-inclusive balance and per-player round outcome reliably
Balance display: place_bet/request_withdrawal spend whole UTXOs and mark
them spent at broadcast time, well before confirmation, so the confirmed-only
balance could drop by far more than the amount actually moving. Add
compute_pending_balance() (app/wallet/balance.py) to fold the unconfirmed
change from in-flight bet/withdrawal PendingTransactions back in; GET
/users/me now returns pending_balance_sats + has_pending, and the frontend
shows it colored green (settled) or amber (still pending) instead of the
confirmed-only figure.

Round outcome display: the win/lose reveal and the "pagamento al vincitore
in corso" status were fighting over the same UI slot, and the reveal broke
across a page refresh. Now:
- The round-status box (generic phase progress) and the personal win/lose
  box are independent and can both be visible at once.
- The win/lose box only renders for users who actually played in that round
  (new user_played field on GET /rounds/current, via a new optional-auth
  dependency so the endpoint stays usable logged-out).
- The reveal delay is anchored to the round's server-provided closes_at
  instead of a client-side "first seen" timestamp, so repeated reloads can't
  reset it, and the revealed result is persisted in localStorage so it
  survives a refresh even after the round has fully closed.
- GET /users/me/last-round-result is a durable DB-backed backstop for
  players who miss the live window entirely (backgrounded tab, offline).

Also hardens the frontend polling loop: call() now times out instead of
hanging forever, and a session-epoch counter stops an in-flight request from
a previous login from resurrecting a duplicate poll loop after logout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 10:09:12 +02:00
davide f822911128 Fix frontend/server round-state desync bugs
- Add a request timeout (AbortController) to the frontend's call() helper, so a
  hung server request no longer freezes the entire polling chain silently.
- Add GET /users/me/last-round-result: a durable, DB-backed fallback for the
  round outcome, since /rounds/current drops winner_user_id the instant a
  round flips from "paying_out" to "closed" — a backgrounded tab or a missed
  poll could otherwise mean a player never learns whether they won.
- Refresh the balance display when a win is revealed (live or via the new
  backstop), instead of leaving the pre-payout balance on screen.
- Guard refreshRound() with a session-epoch counter so an in-flight request
  from a previous login can't re-arm the poll loop after logout, which
  previously produced a duplicate "zombie" polling chain.
2026-07-23 08:53:23 +02:00
26 changed files with 1738 additions and 926 deletions

No files matched your search

+23 -4
View File
@@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
## Project status
All 10 build-order stages from `/home/davide/.claude/plans/scalable-mixing-sloth.md` are code-complete and unit-tested (54 tests green): project skeleton, DB schema + Alembic migrations, auth, HD wallet derivation, Electrum client, deposit detection, bet flow, round/draw engine, payout, withdrawal, RBF fee-bump, admin config + audit log. Beyond the original 10 stages: a Docker + Caddy deployment (see below), a full admin dashboard (`/admin`), and a static test UI for the user-facing flow (`/`).
All 10 build-order stages from `/home/davide/.claude/plans/scalable-mixing-sloth.md` are code-complete and unit-tested (76 tests green): project skeleton, DB schema + Alembic migrations, auth, HD wallet derivation, Electrum client, deposit detection, bet flow, round/draw engine, payout, withdrawal, RBF fee-bump, admin config + audit log. Beyond the original 10 stages: a Docker + Caddy deployment (see below), a full admin dashboard (`/admin`), a static test UI for the user-facing flow (`/`), a pending-inclusive balance display (see "Balance display" below), and a Server-Sent Events push channel layered on top of the original polling (see "Real-time updates" below).
Real-money verification on mainnet, done so far: registration + address derivation, deposit crediting (1-conf), a real 10 PLM bet (broadcast, confirmed, change credited back), and a full round cycle — close → draw (real block hash) → payout (70/30 split, exact sat math verified against the broadcast tx) → confirmation → round closed → next round auto-opened. Withdrawal and the RBF bump path are unit-tested but have never been exercised against a live broadcast. See "Known gaps" below before treating this as production-ready.
@@ -81,6 +81,25 @@ Mainnet:
- Block time: 120s
- BIP32 extended key headers (Legacy/native-segwit `zprv`/`zpub` etc.): see `ExtKeyHeaders` in `ChainProfiles.cs`
## Balance display
`place_bet`/`request_withdrawal` (`app/bets/service.py`, `app/withdrawals/service.py`) select whole UTXOs to cover the amount (`select_utxos`, largest-first) and mark every selected UTXO `spent_txid` immediately at broadcast time — well before the tx has any confirmations. `User.cached_balance_sats` (`recompute_balance`, `app/wallet/balance.py`) only sums confirmed, unspent UTXOs, so right after a bet/withdrawal it understates the user's real balance by the entire unconfirmed change amount, which is often far larger than the amount actually moving.
`compute_pending_balance` (`app/wallet/balance.py`) fixes the *displayed* number without touching what's actually spendable: it decodes the raw tx of every in-flight (`status="pending"`) bet/withdrawal `PendingTransaction` belonging to the user and sums whichever outputs pay back to the user's own address, adding that to `cached_balance_sats`. `GET /users/me` returns both `balance_sats` (confirmed-only — still what withdrawal-max and internal spend logic use, since only confirmed UTXOs are actually spendable) and `pending_balance_sats` + `has_pending` (what the frontend displays, colored green when settled and amber while `has_pending` is true).
## Real-time updates (SSE)
`GET /rounds/stream` (`app/api/routes/rounds.py`) is a Server-Sent Events channel layered *on top of* the original polling loops in `app/static/index.html`/`admin.html` — polling is the fallback, not replaced, so a blocked/dropped SSE connection just degrades to the pre-existing behavior. The channel carries no payload and needs no auth: it's purely a "something changed, go refetch" ping; personalization (e.g. `user_played` below) still lives entirely in the normal per-user REST endpoints.
`app/rounds/events.py`'s `RoundEventBroadcaster` (module-level singleton `broadcaster`) is a simple in-process pub/sub — one `asyncio.Queue` (maxsize 1, so redundant notifications coalesce) per connected SSE client. `broadcaster.publish()` is called from every point that changes something a dashboard would want to know about: a new round opening (`rounds/service.py`), every round status transition (`rounds/scheduler.py`: closing/drawing/paying_out/closed), a bet or withdrawal broadcast (`bets/service.py`, `withdrawals/service.py`), any pending tx confirming — bet/withdrawal/payout (`tx/confirmation.py`), a deposit credited (`deposits/service.py`), and a new block tip arriving (`electrum/listener.py` — the exact moment the "drawing" phase is waiting on).
Deliberate scope decisions, not oversights:
- **Single-process only, no cross-worker fan-out.** Fine for the current deployment (one uvicorn process, see `docker-compose.yml`). A multi-worker/multi-container deployment would need a shared channel (e.g. Redis pub/sub) instead — don't add that speculatively before it's actually needed.
- **Generic broadcast, not a per-user channel.** Every connected client refetches on every event, even ones irrelevant to them. Acceptable at the expected scale (~100 concurrent users); a targeted per-user channel would need auth on the SSE endpoint and server-side knowledge of who's affected by each event — real engineering work, only worth it well past current expected concurrency.
- `MAX_SUBSCRIBERS` (default 500, `app/rounds/events.py`) is a defensive cap only — past it, `GET /rounds/stream` returns 503 instead of opening a stream, and the client's `EventSource` just falls back to polling. Not a substitute for the app-wide "no rate limiting anywhere" gap (see Known gaps).
Frontend: both `index.html` and `admin.html` open an `EventSource('/rounds/stream')` and, on an `update` message *or* on `open` (which fires on the initial connection and every automatic reconnect), immediately re-run the same refresh calls polling would eventually do — this matters most right after a dropped connection reconnects, closing most of the "missed while disconnected" gap.
## MVP business parameters
- Bet cost per round: **10 PLM** by default, admin-configurable (`RoundConfig.bet_amount_sats`) — not a fixed constant.
@@ -99,7 +118,7 @@ The flow is organized into 5 phases, each a subgraph in [flowchart.mmd](flowchar
- **REG (Registration)**: on signup the server derives a new P2WPKH address via BIP84 (`m/84'/coin'/0'/0/index`, one index per user) from a master xprv **encrypted at rest**. This address is permanent and serves as both the deposit address and the address that receives winnings and withdrawals.
- **DEP (Balance top-up)**: an ElectrumClient/SPV subscribes to the user's address scripthash. Internal balance (DB) is credited after **1 confirmation only** — the reorg risk at 1-conf is knowingly accepted in v1, with no rollback logic.
- **PLAY (Bet)**: fixed cost per round, **at most one active bet per user at a time** in v1. The server builds a PSBT user-address → pool-address for the fixed amount, with a **change output back to the same user address** (the user's balance must never exactly equal the bet amount). Fee minimized (~1 sat/vB), **deducted from the bet amount**. If the tx doesn't confirm within a timeout, fee-bump (RBF) and rebroadcast.
- **DRAW (Periodic draw)**: configurable timer (default 10 minutes). The round's own deadline (`opened_at + round_duration_seconds`) is the authoritative "yellow light" cutoff for new bets — **not** the DB status transition. `place_bet` (`app/bets/service.py`) calls `rounds/service.round_accepts_bets(round_, round_duration_seconds)`, which rejects the bet once the deadline has passed even if `status` is still `"open"` in the DB (the `RoundScheduler` tick that flips it to `"closing"` runs every `_TICK_INTERVAL_SECONDS` = 5s and can lag a few seconds behind the deadline). This closes the race where a bet placed in that lag window would otherwise still be accepted. Once a round leaves `open` (closing/drawing/paying_out), **no new bets are accepted** for it either, and a new round can't open until the current one is fully `closed` (see round cooldown below). Round closing **waits for all already-broadcast bets to confirm** before proceeding (avoids losing bets at the round boundary) — this is the "yellow light" behavior: no new entries once the timer hits zero, but bets already in flight are still given time to confirm before the round actually closes and draws. The **next round only opens once the previous round's payout tx is confirmed** — rounds never overlap in v1. v1 draw algorithm (deliberately simple, meant to be replaced later): wait for the first block confirmed after round closing, use its hash as seed, `index = seed mod participant_count` over the participant list ordered by **broadcast timestamp** (this is also the tie-break when two bets confirm in the same block). Every participant has **equal probability regardless of bet amount** (consistent with the fixed bet amount). The payout (70% winner / 30% fees) is signed with the pool address key; the **payout fee is deducted from the winner's 70%**, the 30% fee share stays intact. Same timeout → RBF → rebroadcast pattern here too. The frontend shows a "drawing" animation on every user's dashboard for at least `draw_animation_seconds` (admin-configurable, default 20s) once the round starts closing — purely cosmetic, decoupled from the real (and much longer, ~block-time) wait for `winner_user_id` to actually be set; see `GET /rounds/current`'s `winner_user_id`/`winner_amount_sats` and `app/static/index.html`'s reveal logic.
- **DRAW (Periodic draw)**: configurable timer (default 10 minutes). The round's own deadline (`opened_at + round_duration_seconds`) is the authoritative "yellow light" cutoff for new bets — **not** the DB status transition. `place_bet` (`app/bets/service.py`) calls `rounds/service.round_accepts_bets(round_, round_duration_seconds)`, which rejects the bet once the deadline has passed even if `status` is still `"open"` in the DB (the `RoundScheduler` tick that flips it to `"closing"` runs every `_TICK_INTERVAL_SECONDS` = 5s and can lag a few seconds behind the deadline). This closes the race where a bet placed in that lag window would otherwise still be accepted. Once a round leaves `open` (closing/drawing/paying_out), **no new bets are accepted** for it either, and a new round can't open until the current one is fully `closed` (see round cooldown below). Round closing **waits for all already-broadcast bets to confirm** before proceeding (avoids losing bets at the round boundary) — this is the "yellow light" behavior: no new entries once the timer hits zero, but bets already in flight are still given time to confirm before the round actually closes and draws. The **next round only opens once the previous round's payout tx is confirmed** — rounds never overlap in v1. v1 draw algorithm (deliberately simple, meant to be replaced later): wait for the first block confirmed after round closing, use its hash as seed, `index = seed mod participant_count` over the participant list ordered by **broadcast timestamp** (this is also the tie-break when two bets confirm in the same block). Every participant has **equal probability regardless of bet amount** (consistent with the fixed bet amount). The payout (70% winner / 30% fees) is signed with the pool address key; the **payout fee is deducted from the winner's 70%**, the 30% fee share stays intact. Same timeout → RBF → rebroadcast pattern here too. The frontend shows a generic "drawing" status box (phase label, e.g. "Pagamento al vincitore in corso…") to **every** viewer on every dashboard for the whole closing/drawing/paying_out phase — this one is purely cosmetic status text, driven directly by `status`, no gating. Independently and *additively* (not instead of it), a personalized "Hai vinto!/Non hai vinto" box appears only for users where `GET /rounds/current`'s `user_played` field is true (computed via `app/auth/dependencies.py:get_optional_user`, since this endpoint is reachable logged-out too) — everyone else has nothing to reveal and never sees it. That reveal is additionally delayed by at least `draw_animation_seconds` (admin-configurable, default 20s) for cosmetic suspense, anchored to the round's server-provided `closes_at` timestamp rather than a client-side "first seen" time (so reloading the page can't reset the countdown), and decoupled from the real (and much longer, ~block-time) wait for `winner_user_id` to actually be set. Once revealed, the result is persisted in the browser's `localStorage` (`plm_persisted_result`) so it survives a page refresh even after the round moves past `paying_out` into `closed` — at which point `get_active_round` stops returning that round at all and `winner_user_id` disappears from `GET /rounds/current` entirely. `GET /users/me/last-round-result` (`app/api/routes/users.py`) is a durable, DB-backed backstop for a user who reloads on a browser/device that missed the live reveal window completely: it looks up the most recent *closed* round the user has a `RoundParticipant` row in. See `app/static/index.html`'s `refreshRound`/`checkLastRoundResult` for the full reveal logic.
- **WITHDRAW (Withdrawal)**: the only way to move funds out of the platform to an external address. PSBT user-address → external-address + change back to the user address, fee deducted from the withdrawn amount, same RBF retry pattern.
PLAY and WITHDRAW share a **per-user DB lock**: a user can never have a bet-build and a withdrawal-build in flight at the same time, since both would otherwise spend from the same UTXO set on the user's dedicated address.
@@ -113,7 +132,7 @@ So worst case (last bet confirms right at the deadline) is ~3 block times end-to
## Admin dashboard and test UI
Two static single-page apps, served directly by FastAPI (`app/main.py` mounts `app/static/` and adds a dedicated `GET /admin` route) — no build step, no framework:
Two static single-page apps, served directly by FastAPI (`app/main.py` mounts `app/static/` and adds a dedicated `GET /admin` route) — no build step, no framework. Each page's HTML/CSS/JS are separate files (`index.html`/`style.css`/`app.js`, `admin.html`/`admin.css`/`admin.js`), served as plain static files (no bundler):
- **`/` (`app/static/index.html`)**: the end-user test UI. Register/login, then a menu-driven dashboard (Deposito with a QR code of the address via `GET /qr/{address}`, Bet, Prelievo) with a persistent round-status card (`GET /rounds/current`: id/status/timer/participant count/jackpot) above the menu.
- **`/admin` (`app/static/admin.html`)**: gated by a token screen (not a real login — just checks `X-Admin-Token` against `ADMIN_TOKEN` from `.env`), then a navbar-driven dashboard with five sections, each backed by its own `/admin/*` endpoint (`app/api/routes/admin.py`): Parametri (`RoundConfig` CRUD), Utenti (list + per-user WIF privkey export, audit-logged), Round (history), Transazioni pendenti (in-flight RBF candidates), Audit log. **`/admin` is deliberately not linked from `/`** in either direction — reachable only by knowing the URL.
@@ -139,7 +158,7 @@ Not blockers for reading the code, but must be addressed before this is producti
- **RBF bump only handles one case**: a single change output, paying back to the tx's own sender address, large enough to absorb the fee increase. No additional-input selection fallback — an exact-amount tx (no change) or a change output too small to absorb the bump raises `RbfError` and needs manual operator intervention. Documented in `tx/broadcast.py`.
- **Payout retry**: if `_trigger_payout` fails (e.g. insufficient pool UTXOs, Electrum disconnected), it just logs and returns — the round stays stuck in `paying_out` with no automatic retry.
- **Withdrawal and RBF bump have never been exercised against a live broadcast** — only deposit and bet flow are verified end-to-end with real PLM as of this commit.
- **No user-facing history endpoints** (list my own bets / withdrawals / past rounds) — a user still only has `/users/me` (balance). The admin side now has this (`/admin/rounds`, `/admin/pending-transactions`, `/admin/audit-log`), but there's no equivalent scoped to "my own history" for a logged-in user.
- **No general user-facing history endpoints** (list my own bets / withdrawals / past rounds) — `GET /users/me/last-round-result` covers exactly one case (the outcome of the most recent *closed* round the user played in, as a reveal-persistence backstop; see DRAW above), not a real history. The admin side has more (`/admin/rounds`, `/admin/pending-transactions`, `/admin/audit-log`), but there's still no "my own full history" equivalent for a logged-in user.
- **Admin auth is a single shared bearer token** (`ADMIN_TOKEN`, `X-Admin-Token` header) — no per-admin identity or audit trail of *who* changed config (the `audit_log` table records *what* changed, not which operator did it). This token now gates a lot more than config (user list, private key export, round/audit history), so its blast radius if leaked is correspondingly larger.
- **No rate limiting / abuse protection** on any endpoint (register, bet, withdrawal, admin).
- No automated integration tests against a live Electrum connection — all live-network verification so far has been manual (ad hoc scripts + real mainnet transactions), not part of the `pytest` suite.
+7 -1
View File
@@ -6,6 +6,12 @@
# instead, via its internal CA. Browsers will still warn on first visit
# unless that CA is explicitly trusted — expected for local/dev use.
{$SITE_ADDRESS:localhost} {
encode gzip
# gzip buffers output, which would delay delivery on the SSE stream
# (/rounds/stream, app/api/routes/rounds.py) — it needs each event flushed
# to the client immediately, not batched. Everything else still compresses.
@not_sse {
not path /rounds/stream
}
encode @not_sse gzip
reverse_proxy app:8123
}
+5 -5
View File
@@ -62,8 +62,8 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file
```
54 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
deposits, withdrawals, the round/draw engine, RBF fee-bumping, and admin
config. No automated integration tests against a live Electrum connection —
mainnet verification so far has been manual (see CLAUDE.md's "Project
status").
76 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
verification so far has been manual (see CLAUDE.md's "Project status").
+86 -2
View File
@@ -1,17 +1,80 @@
import asyncio
import json
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import RoundParticipant
from app.auth.dependencies import get_optional_user
from app.db.models import RoundParticipant, User
from app.db.session import get_session
from app.rounds.config import get_round_config
from app.rounds.events import RoundEventCapacityError, broadcaster
from app.rounds.service import get_active_round
router = APIRouter(prefix="/rounds", tags=["rounds"])
# How often request.is_disconnected() gets (re-)checked while idle — bounds
# how long a subscriber slot lingers after a client goes away without a clean
# TCP close (e.g. the network just vanishes). Kept short since the check
# itself is cheap; it does NOT control how often anything is sent on the wire.
_SSE_DISCONNECT_CHECK_SECONDS = 5
# How often to send an SSE keep-alive comment on an otherwise-idle connection —
# well under any reasonable reverse-proxy/load-balancer idle-connection timeout
# (Caddy's default is 5 minutes) so the stream isn't silently dropped. Expressed
# as a multiple of the disconnect-check interval above.
_SSE_KEEPALIVE_TICKS = 4 # 4 * 5s = 20s between keep-alive comments
@router.get("/stream")
async def round_stream(request: Request) -> Response:
"""Server-Sent Events channel: pushes a content-free "update" notification
the instant round/bet/balance state changes anywhere (see app/rounds/events.py
for the publish() call sites), instead of clients only finding out on their
next poll. No payload and no auth: it's a public "go refetch" signal, and
the actual data still comes from the normal per-user REST endpoints, which
is where authorization and personalization (e.g. user_played) already live.
Frontend polling (app/static/index.html) is left in place as a fallback —
this is purely additive, so a dropped/blocked SSE connection degrades to
the pre-existing polling behavior rather than losing updates outright.
That's also what happens past MAX_SUBSCRIBERS (app/rounds/events.py): this
returns 503 rather than opening a stream, and the browser's EventSource
just retries later while the frontend keeps working off polling meanwhile.
"""
try:
queue = broadcaster.subscribe()
except RoundEventCapacityError:
return JSONResponse(status_code=503, content={"detail": "too many concurrent update streams"})
async def event_generator():
ticks_since_keepalive = 0
try:
while True:
if await request.is_disconnected():
break
try:
await asyncio.wait_for(queue.get(), timeout=_SSE_DISCONNECT_CHECK_SECONDS)
yield "event: update\ndata: {}\n\n".format(json.dumps({}))
ticks_since_keepalive = 0
except asyncio.TimeoutError:
ticks_since_keepalive += 1
if ticks_since_keepalive >= _SSE_KEEPALIVE_TICKS:
yield ": keep-alive\n\n"
ticks_since_keepalive = 0
finally:
broadcaster.unsubscribe(queue)
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
)
class CurrentRoundResponse(BaseModel):
server_time: str
@@ -29,10 +92,15 @@ class CurrentRoundResponse(BaseModel):
draw_block_hash: str | None = None
chain_tip_height: int | None = None
lottery_paused: bool = False
user_played: bool = False
@router.get("/current", response_model=CurrentRoundResponse)
async def current_round(request: Request, session: AsyncSession = Depends(get_session)) -> CurrentRoundResponse:
async def current_round(
request: Request,
session: AsyncSession = Depends(get_session),
user: User | None = Depends(get_optional_user),
) -> CurrentRoundResponse:
config = await get_round_config(session)
round_ = await get_active_round(session)
listener = request.app.state.electrum_listener
@@ -52,6 +120,21 @@ async def current_round(request: Request, session: AsyncSession = Depends(get_se
) or 0
opened_at = round_.opened_at.replace(tzinfo=timezone.utc)
closes_at = opened_at + timedelta(seconds=config.round_duration_seconds)
# Lets the frontend show the personalized win/lose reveal only to players in
# this round — everyone else (not logged in, or logged in but didn't bet)
# just sees the generic phase progress instead of a "non hai vinto" that
# wouldn't mean anything to them.
user_played = False
if user is not None:
user_played = (
await session.scalar(
select(RoundParticipant).where(
RoundParticipant.round_id == round_.id, RoundParticipant.user_id == user.id
)
)
) is not None
await session.commit()
# Shown to players as "jackpot": the winner's 70% share of the pool (same
@@ -76,4 +159,5 @@ async def current_round(request: Request, session: AsyncSession = Depends(get_se
draw_block_hash=round_.draw_block_hash,
chain_tip_height=chain_tip_height,
lottery_paused=config.paused,
user_played=user_played,
)
+51 -2
View File
@@ -1,11 +1,13 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import get_current_user
from app.auth.security import hash_password, verify_password
from app.db.models import User
from app.db.models import Round, RoundParticipant, User
from app.db.session import get_session
from app.wallet.balance import compute_pending_balance
router = APIRouter(prefix="/users", tags=["users"])
@@ -17,16 +19,24 @@ class MeResponse(BaseModel):
username: str
address: str
balance_sats: int
pending_balance_sats: int
has_pending: bool
created_at: str
@router.get("/me", response_model=MeResponse)
async def me(user: User = Depends(get_current_user)) -> MeResponse:
async def me(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
) -> MeResponse:
pending_balance_sats, has_pending = await compute_pending_balance(session, user)
return MeResponse(
id=user.id,
username=user.username,
address=user.address,
balance_sats=user.cached_balance_sats,
pending_balance_sats=pending_balance_sats,
has_pending=has_pending,
created_at=user.created_at.isoformat(),
)
@@ -52,3 +62,42 @@ async def change_password(
user.password_hash = hash_password(body.new_password)
await session.commit()
class LastRoundResultResponse(BaseModel):
round_id: int | None = None
won: bool = False
amount_sats: int | None = None
@router.get("/me/last-round-result", response_model=LastRoundResultResponse)
async def last_round_result(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
) -> LastRoundResultResponse:
"""The most recent *closed* round this user participated in, with its outcome.
Deliberately independent of /rounds/current: that endpoint only exposes
winner_user_id while the round is "paying_out", and drops it entirely once
the round flips to "closed" (see rounds/service.get_active_round). A client
that misses that narrow window (backgrounded tab, missed poll, page loaded
late) would otherwise never learn the outcome of a round it bet in. This
endpoint reads the durable DB record instead, so the frontend can always
catch up regardless of polling timing."""
row = await session.execute(
select(Round)
.join(RoundParticipant, RoundParticipant.round_id == Round.id)
.where(RoundParticipant.user_id == user.id, Round.status == "closed")
.order_by(Round.id.desc())
.limit(1)
)
round_ = row.scalar_one_or_none()
if round_ is None:
return LastRoundResultResponse()
won = round_.winner_user_id == user.id
return LastRoundResultResponse(
round_id=round_.id,
won=won,
amount_sats=round_.winner_amount_sats if won else None,
)
+18 -1
View File
@@ -1,4 +1,4 @@
from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -23,3 +23,20 @@ async def get_current_user(
if user is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "user not found")
return user
async def get_optional_user(
request: Request,
session: AsyncSession = Depends(get_session),
) -> User | None:
"""Like get_current_user, but for endpoints reachable both logged-out and
logged-in (e.g. /rounds/current) that need to personalize their response
*if* the caller happens to be authenticated, without requiring it."""
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return None
try:
user_id = decode_access_token(auth_header.removeprefix("Bearer "))
except Exception:
return None
return await session.scalar(select(User).where(User.id == user_id))
+2
View File
@@ -8,6 +8,7 @@ from app.audit.log import write_audit_log
from app.db.models import PendingTransaction, RoundParticipant, User, UtxoEvent
from app.electrum.client import ElectrumClient
from app.rounds.config import get_round_config
from app.rounds.events import broadcaster
from app.rounds.service import open_new_round_if_needed, round_accepts_bets
from app.wallet.balance import recompute_balance
from app.wallet.hd import derive_pool_address, derive_user_key
@@ -91,6 +92,7 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
await session.commit()
await session.refresh(participant)
broadcaster.publish() # participant_count/jackpot changed — nudge every dashboard to refetch
return participant
+2
View File
@@ -3,6 +3,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.log import write_audit_log
from app.db.models import UtxoEvent
from app.rounds.events import broadcaster
from app.wallet.balance import recompute_balance
@@ -50,5 +51,6 @@ async def credit_confirmed_utxos(session: AsyncSession, user_id: int, entries: l
await session.flush()
await recompute_balance(session, user_id)
await session.commit()
broadcaster.publish() # nudges this user's dashboard to refetch its balance instantly
return newly_credited
+5
View File
@@ -9,6 +9,7 @@ from app.db.models import User
from app.deposits.service import credit_confirmed_utxos
from app.electrum.client import ElectrumClient
from app.electrum.scripthash import address_to_scripthash
from app.rounds.events import broadcaster
logger = logging.getLogger(__name__)
@@ -94,6 +95,10 @@ class ElectrumListener:
for header in params:
self.tip_height = header["height"]
self.tip_header_hex = header.get("hex")
# A new block is exactly what the "drawing" phase is waiting on
# (rounds/scheduler.py:_wait_for_next_block) — nudge dashboards to
# refetch instead of waiting for their next poll.
broadcaster.publish()
async def _consume_scripthash(self, queue: asyncio.Queue) -> None:
while True:
+50
View File
@@ -0,0 +1,50 @@
import asyncio
# Defensive cap on concurrent SSE subscribers. Expected load is on the order of
# ~100 concurrent users; this is set well above that so it never engages under
# normal use — it exists purely so a runaway/DoS-y number of open connections
# degrades (new connections fall back to polling, see round_stream()) instead
# of growing the in-memory subscriber set without bound. Revisit this number if
# expected concurrency grows well past it.
MAX_SUBSCRIBERS = 500
class RoundEventCapacityError(Exception):
"""Raised by subscribe() when MAX_SUBSCRIBERS is already reached."""
class RoundEventBroadcaster:
"""In-process pub/sub so SSE clients (GET /rounds/stream) get pushed a
notification the instant round/bet/balance state changes, instead of only
finding out on their next poll. The message carries no payload — it's just
a "something changed, go refetch" signal; the client re-hits the existing
per-user REST endpoints (/rounds/current, /users/me, ...) for the actual
data, so this never needs to know what changed or who's allowed to see it.
Single-process only (no cross-worker fan-out) — fine for this deployment
(one uvicorn process, see docker-compose.yml). A multi-worker deployment
would need a shared channel (e.g. Redis pub/sub) instead.
"""
def __init__(self, max_subscribers: int = MAX_SUBSCRIBERS):
self._subscribers: set[asyncio.Queue] = set()
self.max_subscribers = max_subscribers
def subscribe(self) -> asyncio.Queue:
if len(self._subscribers) >= self.max_subscribers:
raise RoundEventCapacityError(f"already at the {self.max_subscribers}-subscriber cap")
queue: asyncio.Queue = asyncio.Queue(maxsize=1)
self._subscribers.add(queue)
return queue
def unsubscribe(self, queue: asyncio.Queue) -> None:
self._subscribers.discard(queue)
def publish(self) -> None:
for queue in self._subscribers:
if queue.full():
continue # a not-yet-delivered notification already covers this one
queue.put_nowait(None)
broadcaster = RoundEventBroadcaster()
+5
View File
@@ -12,6 +12,7 @@ from app.electrum.listener import ElectrumListener
from app.electrum.scripthash import address_to_scripthash
from app.rounds.config import get_round_config
from app.rounds.draw import draw_winner, header_hex_to_block_hash
from app.rounds.events import broadcaster
from app.rounds.service import open_new_round_if_needed
from app.wallet.hd import derive_pool_key
from app.wallet.plm_network import PLM_MAINNET
@@ -71,6 +72,7 @@ class RoundScheduler:
round_.status = "closing"
round_.closed_at = datetime.now(timezone.utc)
await session.commit()
broadcaster.publish()
async with self._session_factory() as session:
pending_count = await session.scalar(
@@ -99,6 +101,7 @@ class RoundScheduler:
round_.status = "closed"
await write_audit_log(session, "round_closed", {"participants": 0}, round_id=round_id)
await session.commit()
broadcaster.publish()
logger.info("round %s closed with no participants", round_id)
return
@@ -112,6 +115,7 @@ class RoundScheduler:
round_.status = "drawing"
await session.commit()
broadcaster.publish()
tip_at_close = self._listener.tip_height
block_height, block_hash = await self._wait_for_next_block(tip_at_close)
@@ -139,6 +143,7 @@ class RoundScheduler:
round_id=round_id,
)
await session.commit()
broadcaster.publish()
logger.info("round %s: winner=%s pool=%s", round_id, winner_address, pool_amount)
await self._trigger_payout(round_id)
+6
View File
@@ -5,6 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import Round
from app.rounds.config import get_round_config
from app.rounds.events import broadcaster
_ACTIVE_STATUSES = ("open", "closing", "drawing", "paying_out")
@@ -57,4 +58,9 @@ async def open_new_round_if_needed(session: AsyncSession) -> Round | None:
round_ = Round(status="open")
session.add(round_)
await session.flush()
# Published pre-commit (the caller commits right after) — acceptable: this
# only tells subscribers "go refetch", and by the time an SSE client's
# refetch request actually lands, this in-process commit (microseconds
# away) has essentially always already happened.
broadcaster.publish()
return round_
+1 -365
View File
@@ -158,371 +158,7 @@
<div id="toast-container" aria-live="polite"></div>
<script>
const SATS_PER_PLM = 100000000;
let adminToken = sessionStorage.getItem('plm_admin_token');
function toast(message, type) {
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = 'toast ' + type;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), 4000);
}
async function withLoading(button, label, fn) {
const original = button.textContent;
button.disabled = true;
button.textContent = label;
try {
await fn();
} finally {
button.disabled = false;
button.textContent = original;
}
}
async function callAdmin(method, path, body) {
const headers = { 'Content-Type': 'application/json', 'X-Admin-Token': adminToken };
const res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || res.statusText);
return data;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function badge(status) {
return `<span class="badge status-${escapeHtml(status)}">${escapeHtml(status)}</span>`;
}
function fmtDate(iso) {
if (!iso) return '—';
return new Date(iso).toLocaleString('it-IT');
}
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
const CHAIN_STATUS_LABELS = {
waiting: 'In attesa del prossimo round',
open: 'Round aperto',
drawing: 'Estrazione in corso',
};
let chainStatusInterval = null;
async function refreshChainStatus() {
try {
const res = await fetch('/rounds/current');
const data = await res.json();
let statusKey;
if (!data.round_id) statusKey = 'waiting';
else if (DRAWING_STATUSES.includes(data.status)) statusKey = 'drawing';
else statusKey = 'open';
document.getElementById('chain-status-dot').className = 'status-dot status-' + statusKey;
document.getElementById('chain-status-label').textContent = CHAIN_STATUS_LABELS[statusKey];
document.getElementById('chain-block').textContent =
'Blocco ' + (data.chain_tip_height != null ? '#' + data.chain_tip_height : '—');
} catch (e) {
// leave the last-known status on screen rather than blanking it out
}
}
function startChainStatusPolling() {
refreshChainStatus();
clearInterval(chainStatusInterval);
chainStatusInterval = setInterval(refreshChainStatus, 15000);
}
function stopChainStatusPolling() {
clearInterval(chainStatusInterval);
chainStatusInterval = null;
}
const VIEWS = ['parametri', 'utenti', 'round', 'pending', 'audit'];
function switchView(name) {
for (const key of VIEWS) {
document.getElementById('nav-' + key).classList.toggle('active', key === name);
document.getElementById('view-' + key).classList.toggle('active', key === name);
}
const loaders = { utenti: loadUsers, round: loadRounds, pending: loadPending, audit: loadAuditLog };
if (loaders[name]) loaders[name]();
}
function showDashboard() {
document.getElementById('login-section').classList.add('hidden');
document.getElementById('dashboard-section').classList.remove('hidden');
startChainStatusPolling();
}
async function loadDashboard() {
await Promise.all([adminLoadConfig(), loadUsers(), loadRounds(), loadPending(), loadAuditLog()]);
}
async function adminLogin() {
const btn = document.getElementById('login-btn');
adminToken = document.getElementById('admin-token').value;
await withLoading(btn, 'Verifica…', async () => {
try {
await callAdmin('GET', '/admin/config');
sessionStorage.setItem('plm_admin_token', adminToken);
showDashboard();
await loadDashboard();
} catch (e) {
adminToken = null;
toast('Token non valido.', 'error');
}
});
}
function adminLogout() {
stopChainStatusPolling();
sessionStorage.removeItem('plm_admin_token');
adminToken = null;
document.getElementById('admin-token').value = '';
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('login-section').classList.remove('hidden');
}
async function adminLoadConfig() {
try {
const data = await callAdmin('GET', '/admin/config');
document.getElementById('admin-fee-address').value = data.fee_address;
document.getElementById('admin-bet-amount').value = data.bet_amount_sats / SATS_PER_PLM;
document.getElementById('admin-round-duration').value = data.round_duration_seconds;
document.getElementById('admin-round-cooldown').value = data.round_cooldown_seconds;
document.getElementById('admin-draw-animation').value = data.draw_animation_seconds;
document.getElementById('admin-fee-rate').value = data.fee_rate_sat_vb;
document.getElementById('admin-rbf-timeout').value = data.rbf_timeout_seconds;
renderMaintenanceState(data.paused);
} catch (e) {
toast('Errore nel caricamento configurazione: ' + e.message, 'error');
}
}
function renderMaintenanceState(paused) {
const dot = document.getElementById('maintenance-dot');
const label = document.getElementById('maintenance-status-label');
const btn = document.getElementById('maintenance-btn');
btn.dataset.paused = paused ? '1' : '0';
if (paused) {
dot.className = 'status-dot status-paused';
label.textContent = 'In pausa: nessun nuovo round verrà aperto';
btn.textContent = 'Riprendi lotteria';
btn.classList.remove('btn-stop');
} else {
dot.className = 'status-dot status-open';
label.textContent = 'Attiva: i round si susseguono normalmente';
btn.textContent = 'Interrompi dopo questo round';
btn.classList.add('btn-stop');
}
}
async function toggleMaintenance() {
const btn = document.getElementById('maintenance-btn');
const isPaused = btn.dataset.paused === '1';
const path = isPaused ? '/admin/resume' : '/admin/pause';
if (!isPaused && !window.confirm(
"Nessun nuovo round verrà aperto dopo quello in corso, fino a quando non riprendi la lotteria. " +
"Il round attuale (se presente) verrà comunque completato e il vincitore pagato. Continuare?"
)) {
return;
}
btn.disabled = true;
try {
const data = await callAdmin('POST', path, {});
renderMaintenanceState(data.paused);
toast(data.paused ? 'Lotteria in pausa.' : 'Lotteria ripresa.', 'success');
refreshChainStatus();
} catch (e) {
toast('Errore: ' + e.message, 'error');
} finally {
btn.disabled = false;
}
}
async function adminSave() {
const btn = document.getElementById('save-btn');
const feeAddress = document.getElementById('admin-fee-address').value;
const betAmountPlm = parseFloat(document.getElementById('admin-bet-amount').value);
const body = {
fee_address: feeAddress,
bet_amount_sats: Math.round(betAmountPlm * SATS_PER_PLM),
round_duration_seconds: parseInt(document.getElementById('admin-round-duration').value, 10),
round_cooldown_seconds: parseInt(document.getElementById('admin-round-cooldown').value, 10),
draw_animation_seconds: parseInt(document.getElementById('admin-draw-animation').value, 10),
fee_rate_sat_vb: parseInt(document.getElementById('admin-fee-rate').value, 10),
rbf_timeout_seconds: parseInt(document.getElementById('admin-rbf-timeout').value, 10),
};
await withLoading(btn, 'Salvataggio…', async () => {
try {
await callAdmin('PUT', '/admin/config', body);
toast('Configurazione salvata.', 'success');
} catch (e) {
toast('Errore nel salvataggio: ' + e.message, 'error');
}
});
}
async function loadUsers() {
try {
const users = await callAdmin('GET', '/admin/users');
const tbody = document.getElementById('users-tbody');
tbody.innerHTML = users.map((u) => `
<tr>
<td>${u.id}</td>
<td>${escapeHtml(u.username)}</td>
<td class="addr">${escapeHtml(u.address)}</td>
<td>${u.balance_sats / SATS_PER_PLM}</td>
<td>${fmtDate(u.created_at)}</td>
<td>
<button class="reveal" onclick="revealPrivkey(${u.id}, this)">Mostra</button>
<div class="privkey-box hidden" id="privkey-${u.id}"></div>
</td>
<td>
<button class="secondary" style="width:auto;margin-top:0;min-height:30px;padding:4px 10px;font-size:0.78rem" onclick="resetUserPassword(${u.id}, this)">Reset</button>
<div class="privkey-box hidden" id="newpass-${u.id}"></div>
</td>
</tr>
`).join('') || '<tr><td colspan="7" class="hint">Nessun utente registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento utenti: ' + e.message, 'error');
}
}
async function revealPrivkey(userId, button) {
const box = document.getElementById('privkey-' + userId);
if (!box.classList.contains('hidden')) {
box.classList.add('hidden');
box.textContent = '';
button.textContent = 'Mostra';
return;
}
if (!window.confirm('Stai per visualizzare la chiave privata di questo utente. L\'accesso verrà registrato nell\'audit log. Continuare?')) {
return;
}
await withLoading(button, '…', async () => {
try {
const data = await callAdmin('GET', '/admin/users/' + userId + '/privkey');
box.textContent = data.wif;
box.classList.remove('hidden');
button.textContent = 'Nascondi';
} catch (e) {
toast('Errore: ' + e.message, 'error');
}
});
}
async function resetUserPassword(userId, button) {
if (!window.confirm(
"Verrà generata una nuova password casuale per questo utente, che non potrà più accedere con quella vecchia. " +
"L'azione viene registrata nell'audit log. Continuare?"
)) {
return;
}
const box = document.getElementById('newpass-' + userId);
await withLoading(button, '…', async () => {
try {
const data = await callAdmin('POST', '/admin/users/' + userId + '/reset-password');
box.textContent = 'Nuova password per ' + data.username + ': ' + data.new_password;
box.classList.remove('hidden');
toast('Password reimpostata.', 'success');
} catch (e) {
toast('Errore: ' + e.message, 'error');
}
});
}
async function loadRounds() {
try {
const rounds = await callAdmin('GET', '/admin/rounds');
const tbody = document.getElementById('rounds-tbody');
tbody.innerHTML = rounds.map((r) => `
<tr>
<td>${r.id}</td>
<td>${badge(r.status)}</td>
<td>${fmtDate(r.opened_at)}</td>
<td>${r.winner_username ? escapeHtml(r.winner_username) : '—'}</td>
<td>${r.pool_amount_sats != null ? r.pool_amount_sats / SATS_PER_PLM : '—'}</td>
<td>${r.winner_amount_sats != null ? r.winner_amount_sats / SATS_PER_PLM : '—'}</td>
<td>${r.fee_amount_sats != null ? r.fee_amount_sats / SATS_PER_PLM : '—'}</td>
<td class="txid">${r.payout_txid ? escapeHtml(r.payout_txid) : '—'}</td>
</tr>
`).join('') || '<tr><td colspan="8" class="hint">Nessun round ancora.</td></tr>';
} catch (e) {
toast('Errore nel caricamento round: ' + e.message, 'error');
}
}
async function loadPending() {
try {
const items = await callAdmin('GET', '/admin/pending-transactions');
const tbody = document.getElementById('pending-tbody');
tbody.innerHTML = items.map((p) => `
<tr>
<td>${p.id}</td>
<td>${escapeHtml(p.kind)}</td>
<td>${badge(p.status)}</td>
<td class="txid">${escapeHtml(p.current_txid)}</td>
<td>${p.fee_rate_sat_vb} sat/vB</td>
<td>${p.attempt_count}</td>
<td>${fmtDate(p.broadcast_at)}</td>
</tr>
`).join('') || '<tr><td colspan="7" class="hint">Nessuna transazione pendente.</td></tr>';
} catch (e) {
toast('Errore nel caricamento transazioni pendenti: ' + e.message, 'error');
}
}
async function loadAuditLog() {
try {
const entries = await callAdmin('GET', '/admin/audit-log');
const tbody = document.getElementById('audit-tbody');
tbody.innerHTML = entries.map((e) => `
<tr>
<td>${e.id}</td>
<td>${escapeHtml(e.event_type)}</td>
<td><pre class="payload">${escapeHtml(JSON.stringify(e.payload))}</pre></td>
<td>${e.user_id ?? '—'}</td>
<td>${e.round_id ?? '—'}</td>
<td>${fmtDate(e.created_at)}</td>
</tr>
`).join('') || '<tr><td colspan="6" class="hint">Nessun evento registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento audit log: ' + e.message, 'error');
}
}
document.getElementById('admin-token').addEventListener('keydown', (e) => {
if (e.key === 'Enter') adminLogin();
});
function initAuthState() {
adminToken = sessionStorage.getItem('plm_admin_token');
if (!adminToken) {
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('login-section').classList.remove('hidden');
return;
}
callAdmin('GET', '/admin/config')
.then(() => { showDashboard(); return loadDashboard(); })
.catch(() => adminLogout());
}
// Bfcache can restore a frozen snapshot of this page (DOM/JS state as it was
// before navigating away) without re-running any of this script — so a stale
// view could survive across back/forward navigation, e.g. showing a dashboard
// for a token that's since been rotated or explicitly logged out of. Cache-
// Control: no-store on this response should already prevent that, but
// re-validate here too as a safety net for browsers that ignore it.
window.addEventListener('pageshow', (event) => {
if (event.persisted) initAuthState();
});
initAuthState();
</script>
<script src="/admin.js"></script>
</body>
</html>
+390
View File
@@ -0,0 +1,390 @@
const SATS_PER_PLM = 100000000;
let adminToken = sessionStorage.getItem('plm_admin_token');
function toast(message, type) {
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = 'toast ' + type;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), 4000);
}
async function withLoading(button, label, fn) {
const original = button.textContent;
button.disabled = true;
button.textContent = label;
try {
await fn();
} finally {
button.disabled = false;
button.textContent = original;
}
}
async function callAdmin(method, path, body) {
const headers = { 'Content-Type': 'application/json', 'X-Admin-Token': adminToken };
const res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || res.statusText);
return data;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function badge(status) {
return `<span class="badge status-${escapeHtml(status)}">${escapeHtml(status)}</span>`;
}
function fmtDate(iso) {
if (!iso) return '—';
return new Date(iso).toLocaleString('it-IT');
}
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
const CHAIN_STATUS_LABELS = {
waiting: 'In attesa del prossimo round',
open: 'Round aperto',
drawing: 'Estrazione in corso',
};
let chainStatusInterval = null;
async function refreshChainStatus() {
try {
const res = await fetch('/rounds/current');
const data = await res.json();
let statusKey;
if (!data.round_id) statusKey = 'waiting';
else if (DRAWING_STATUSES.includes(data.status)) statusKey = 'drawing';
else statusKey = 'open';
document.getElementById('chain-status-dot').className = 'status-dot status-' + statusKey;
document.getElementById('chain-status-label').textContent = CHAIN_STATUS_LABELS[statusKey];
document.getElementById('chain-block').textContent =
'Blocco ' + (data.chain_tip_height != null ? '#' + data.chain_tip_height : '—');
} catch (e) {
// leave the last-known status on screen rather than blanking it out
}
}
function startChainStatusPolling() {
refreshChainStatus();
clearInterval(chainStatusInterval);
chainStatusInterval = setInterval(refreshChainStatus, 15000);
}
function stopChainStatusPolling() {
clearInterval(chainStatusInterval);
chainStatusInterval = null;
}
const VIEWS = ['parametri', 'utenti', 'round', 'pending', 'audit'];
const VIEW_LOADERS = { utenti: loadUsers, round: loadRounds, pending: loadPending, audit: loadAuditLog };
let currentAdminView = 'parametri';
function switchView(name) {
currentAdminView = name;
for (const key of VIEWS) {
document.getElementById('nav-' + key).classList.toggle('active', key === name);
document.getElementById('view-' + key).classList.toggle('active', key === name);
}
if (VIEW_LOADERS[name]) VIEW_LOADERS[name]();
}
function showDashboard() {
document.getElementById('login-section').classList.add('hidden');
document.getElementById('dashboard-section').classList.remove('hidden');
startChainStatusPolling();
}
async function loadDashboard() {
await Promise.all([adminLoadConfig(), loadUsers(), loadRounds(), loadPending(), loadAuditLog()]);
}
async function adminLogin() {
const btn = document.getElementById('login-btn');
adminToken = document.getElementById('admin-token').value;
await withLoading(btn, 'Verifica…', async () => {
try {
await callAdmin('GET', '/admin/config');
sessionStorage.setItem('plm_admin_token', adminToken);
showDashboard();
await loadDashboard();
} catch (e) {
adminToken = null;
toast('Token non valido.', 'error');
}
});
}
function adminLogout() {
stopChainStatusPolling();
sessionStorage.removeItem('plm_admin_token');
adminToken = null;
document.getElementById('admin-token').value = '';
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('login-section').classList.remove('hidden');
}
async function adminLoadConfig() {
try {
const data = await callAdmin('GET', '/admin/config');
document.getElementById('admin-fee-address').value = data.fee_address;
document.getElementById('admin-bet-amount').value = data.bet_amount_sats / SATS_PER_PLM;
document.getElementById('admin-round-duration').value = data.round_duration_seconds;
document.getElementById('admin-round-cooldown').value = data.round_cooldown_seconds;
document.getElementById('admin-draw-animation').value = data.draw_animation_seconds;
document.getElementById('admin-fee-rate').value = data.fee_rate_sat_vb;
document.getElementById('admin-rbf-timeout').value = data.rbf_timeout_seconds;
renderMaintenanceState(data.paused);
} catch (e) {
toast('Errore nel caricamento configurazione: ' + e.message, 'error');
}
}
function renderMaintenanceState(paused) {
const dot = document.getElementById('maintenance-dot');
const label = document.getElementById('maintenance-status-label');
const btn = document.getElementById('maintenance-btn');
btn.dataset.paused = paused ? '1' : '0';
if (paused) {
dot.className = 'status-dot status-paused';
label.textContent = 'In pausa: nessun nuovo round verrà aperto';
btn.textContent = 'Riprendi lotteria';
btn.classList.remove('btn-stop');
} else {
dot.className = 'status-dot status-open';
label.textContent = 'Attiva: i round si susseguono normalmente';
btn.textContent = 'Interrompi dopo questo round';
btn.classList.add('btn-stop');
}
}
async function toggleMaintenance() {
const btn = document.getElementById('maintenance-btn');
const isPaused = btn.dataset.paused === '1';
const path = isPaused ? '/admin/resume' : '/admin/pause';
if (!isPaused && !window.confirm(
"Nessun nuovo round verrà aperto dopo quello in corso, fino a quando non riprendi la lotteria. " +
"Il round attuale (se presente) verrà comunque completato e il vincitore pagato. Continuare?"
)) {
return;
}
btn.disabled = true;
try {
const data = await callAdmin('POST', path, {});
renderMaintenanceState(data.paused);
toast(data.paused ? 'Lotteria in pausa.' : 'Lotteria ripresa.', 'success');
refreshChainStatus();
} catch (e) {
toast('Errore: ' + e.message, 'error');
} finally {
btn.disabled = false;
}
}
async function adminSave() {
const btn = document.getElementById('save-btn');
const feeAddress = document.getElementById('admin-fee-address').value;
const betAmountPlm = parseFloat(document.getElementById('admin-bet-amount').value);
const body = {
fee_address: feeAddress,
bet_amount_sats: Math.round(betAmountPlm * SATS_PER_PLM),
round_duration_seconds: parseInt(document.getElementById('admin-round-duration').value, 10),
round_cooldown_seconds: parseInt(document.getElementById('admin-round-cooldown').value, 10),
draw_animation_seconds: parseInt(document.getElementById('admin-draw-animation').value, 10),
fee_rate_sat_vb: parseInt(document.getElementById('admin-fee-rate').value, 10),
rbf_timeout_seconds: parseInt(document.getElementById('admin-rbf-timeout').value, 10),
};
await withLoading(btn, 'Salvataggio…', async () => {
try {
await callAdmin('PUT', '/admin/config', body);
toast('Configurazione salvata.', 'success');
} catch (e) {
toast('Errore nel salvataggio: ' + e.message, 'error');
}
});
}
async function loadUsers() {
try {
const users = await callAdmin('GET', '/admin/users');
const tbody = document.getElementById('users-tbody');
tbody.innerHTML = users.map((u) => `
<tr>
<td>${u.id}</td>
<td>${escapeHtml(u.username)}</td>
<td class="addr">${escapeHtml(u.address)}</td>
<td>${u.balance_sats / SATS_PER_PLM}</td>
<td>${fmtDate(u.created_at)}</td>
<td>
<button class="reveal" onclick="revealPrivkey(${u.id}, this)">Mostra</button>
<div class="privkey-box hidden" id="privkey-${u.id}"></div>
</td>
<td>
<button class="secondary" style="width:auto;margin-top:0;min-height:30px;padding:4px 10px;font-size:0.78rem" onclick="resetUserPassword(${u.id}, this)">Reset</button>
<div class="privkey-box hidden" id="newpass-${u.id}"></div>
</td>
</tr>
`).join('') || '<tr><td colspan="7" class="hint">Nessun utente registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento utenti: ' + e.message, 'error');
}
}
async function revealPrivkey(userId, button) {
const box = document.getElementById('privkey-' + userId);
if (!box.classList.contains('hidden')) {
box.classList.add('hidden');
box.textContent = '';
button.textContent = 'Mostra';
return;
}
if (!window.confirm('Stai per visualizzare la chiave privata di questo utente. L\'accesso verrà registrato nell\'audit log. Continuare?')) {
return;
}
await withLoading(button, '…', async () => {
try {
const data = await callAdmin('GET', '/admin/users/' + userId + '/privkey');
box.textContent = data.wif;
box.classList.remove('hidden');
button.textContent = 'Nascondi';
} catch (e) {
toast('Errore: ' + e.message, 'error');
}
});
}
async function resetUserPassword(userId, button) {
if (!window.confirm(
"Verrà generata una nuova password casuale per questo utente, che non potrà più accedere con quella vecchia. " +
"L'azione viene registrata nell'audit log. Continuare?"
)) {
return;
}
const box = document.getElementById('newpass-' + userId);
await withLoading(button, '…', async () => {
try {
const data = await callAdmin('POST', '/admin/users/' + userId + '/reset-password');
box.textContent = 'Nuova password per ' + data.username + ': ' + data.new_password;
box.classList.remove('hidden');
toast('Password reimpostata.', 'success');
} catch (e) {
toast('Errore: ' + e.message, 'error');
}
});
}
async function loadRounds() {
try {
const rounds = await callAdmin('GET', '/admin/rounds');
const tbody = document.getElementById('rounds-tbody');
tbody.innerHTML = rounds.map((r) => `
<tr>
<td>${r.id}</td>
<td>${badge(r.status)}</td>
<td>${fmtDate(r.opened_at)}</td>
<td>${r.winner_username ? escapeHtml(r.winner_username) : '—'}</td>
<td>${r.pool_amount_sats != null ? r.pool_amount_sats / SATS_PER_PLM : '—'}</td>
<td>${r.winner_amount_sats != null ? r.winner_amount_sats / SATS_PER_PLM : '—'}</td>
<td>${r.fee_amount_sats != null ? r.fee_amount_sats / SATS_PER_PLM : '—'}</td>
<td class="txid">${r.payout_txid ? escapeHtml(r.payout_txid) : '—'}</td>
</tr>
`).join('') || '<tr><td colspan="8" class="hint">Nessun round ancora.</td></tr>';
} catch (e) {
toast('Errore nel caricamento round: ' + e.message, 'error');
}
}
async function loadPending() {
try {
const items = await callAdmin('GET', '/admin/pending-transactions');
const tbody = document.getElementById('pending-tbody');
tbody.innerHTML = items.map((p) => `
<tr>
<td>${p.id}</td>
<td>${escapeHtml(p.kind)}</td>
<td>${badge(p.status)}</td>
<td class="txid">${escapeHtml(p.current_txid)}</td>
<td>${p.fee_rate_sat_vb} sat/vB</td>
<td>${p.attempt_count}</td>
<td>${fmtDate(p.broadcast_at)}</td>
</tr>
`).join('') || '<tr><td colspan="7" class="hint">Nessuna transazione pendente.</td></tr>';
} catch (e) {
toast('Errore nel caricamento transazioni pendenti: ' + e.message, 'error');
}
}
async function loadAuditLog() {
try {
const entries = await callAdmin('GET', '/admin/audit-log');
const tbody = document.getElementById('audit-tbody');
tbody.innerHTML = entries.map((e) => `
<tr>
<td>${e.id}</td>
<td>${escapeHtml(e.event_type)}</td>
<td><pre class="payload">${escapeHtml(JSON.stringify(e.payload))}</pre></td>
<td>${e.user_id ?? '—'}</td>
<td>${e.round_id ?? '—'}</td>
<td>${fmtDate(e.created_at)}</td>
</tr>
`).join('') || '<tr><td colspan="6" class="hint">Nessun evento registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento audit log: ' + e.message, 'error');
}
}
document.getElementById('admin-token').addEventListener('keydown', (e) => {
if (e.key === 'Enter') adminLogin();
});
function initAuthState() {
adminToken = sessionStorage.getItem('plm_admin_token');
if (!adminToken) {
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('login-section').classList.remove('hidden');
return;
}
callAdmin('GET', '/admin/config')
.then(() => { showDashboard(); return loadDashboard(); })
.catch(() => adminLogout());
}
// Bfcache can restore a frozen snapshot of this page (DOM/JS state as it was
// before navigating away) without re-running any of this script — so a stale
// view could survive across back/forward navigation, e.g. showing a dashboard
// for a token that's since been rotated or explicitly logged out of. Cache-
// Control: no-store on this response should already prevent that, but
// re-validate here too as a safety net for browsers that ignore it.
window.addEventListener('pageshow', (event) => {
if (event.persisted) initAuthState();
});
// Same server-push channel as app/static/index.html (see app/rounds/events.py):
// a content-free "something changed" ping. Here it refreshes the chain-status
// bar immediately, and reloads whichever admin section is currently open
// (Utenti/Round/Transazioni pendenti/Audit log) so it doesn't need a manual
// switch-away-and-back to pick up a new row. Polling stays in place as a
// fallback if this connection is ever blocked or drops.
let adminEventSource = null;
function onAdminServerEvent() {
if (!adminToken) return;
refreshChainStatus();
if (VIEW_LOADERS[currentAdminView]) VIEW_LOADERS[currentAdminView]();
}
function connectAdminEvents() {
if (adminEventSource) return;
adminEventSource = new EventSource('/rounds/stream');
adminEventSource.addEventListener('update', onAdminServerEvent);
// Fires on the initial connection AND every successful auto-reconnect —
// re-syncs immediately instead of waiting for the next event or poll tick
// to notice whatever changed while this connection was down.
adminEventSource.addEventListener('open', onAdminServerEvent);
}
connectAdminEvents();
initAuthState();
+710
View File
@@ -0,0 +1,710 @@
const SATS_PER_PLM = 100000000;
let token = localStorage.getItem('plm_token');
let username = localStorage.getItem('plm_username');
let address = localStorage.getItem('plm_address');
function toast(message, type) {
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = 'toast ' + type;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), 4000);
}
async function withLoading(button, label, fn) {
const original = button.textContent;
button.disabled = true;
button.textContent = label;
try {
await fn();
} finally {
button.disabled = false;
button.textContent = original;
}
}
const REQUEST_TIMEOUT_MS = 15000;
// Without a timeout, a single request that never resolves (server-side hang —
// stuck DB session, unresponsive Electrum connection...) would stall the whole
// sequential polling chain forever: the UI just freezes on whatever was last
// rendered, with no error and no "connessione persa" (that only fires on a
// rejected fetch, never on one that's merely stuck).
async function call(method, path, body) {
const headers = { 'Content-Type': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let res;
try {
res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: controller.signal });
} catch (e) {
throw new Error(e.name === 'AbortError' ? 'Richiesta al server scaduta.' : e.message);
} finally {
clearTimeout(timeoutId);
}
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || res.statusText);
return data;
}
function switchTab(name) {
document.getElementById('tab-login').classList.toggle('active', name === 'login');
document.getElementById('tab-register').classList.toggle('active', name === 'register');
document.getElementById('panel-login').classList.toggle('active', name === 'login');
document.getElementById('panel-register').classList.toggle('active', name === 'register');
}
function switchPanel(name) {
for (const key of ['deposit', 'bet', 'withdraw', 'profile']) {
document.getElementById('nav-' + key).classList.toggle('active', key === name);
document.getElementById('panel-' + key).classList.toggle('active', key === name);
}
}
// Bumped on every logout/login so an in-flight refreshRound() started under a
// previous session can detect it's now stale — a fetch can still be awaiting
// its response after logout() clears the timeout-based poll chain, and without
// this guard it would re-arm scheduleNextRoundPoll() and resurrect a "zombie"
// dashboard poll running in parallel with the logged-out chain-only poll.
let sessionEpoch = 0;
let roundCloseAt = null;
let serverTimeOffsetMs = 0; // serverNow - clientNow, so every client's countdown agrees regardless of local clock skew
function serverNow() { return new Date(Date.now() + serverTimeOffsetMs); }
// refreshRound() is triggered from several independent sources (poll timer, timer-hits-zero,
// visibilitychange, placeBet, showDashboard) whose requests can resolve out of order over the
// network. Track the latest applied response so a slow, stale one can never revert the UI to an
// older round's state after a newer response has already moved it forward.
let roundRequestSeq = 0;
let roundAppliedSeq = 0;
let roundTimerInterval = null;
let roundPollTimeout = null;
let lastResultInterval = null;
const ROUND_STATUS_LABELS = {
open: 'aperto',
closing: 'in chiusura',
drawing: 'estrazione in corso',
paying_out: 'pagamento al vincitore in corso',
};
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
// One distinct message per DRAW sub-phase (see CLAUDE.md's "three separate
// on-chain confirmations" note) instead of a single generic spinner label —
// takes the round data so the drawing phase can surface the draw block once known.
function drawingLabelFor(data) {
if (data.status === 'closing') {
return 'Round chiuso — in attesa di conferma dell\'ultima giocata prima di estrarre il vincitore…';
}
if (data.status === 'drawing') {
return 'In attesa del prossimo blocco per estrarre il vincitore…';
}
// paying_out
if (data.draw_block_height != null) {
return 'Vincitore estratto dal blocco #' + data.draw_block_height + ' — pagamento al vincitore in corso…';
}
return 'Vincitore estratto — pagamento al vincitore in corso…';
}
// One label per real round status, not just the coarse open/drawing/waiting
// grouping — the status bar should show the same phase distinction as the
// draw-state panel (drawingLabelFor above), just condensed to a short phrase.
const CHAIN_STATUS_LABELS = {
waiting: 'In attesa del prossimo round',
open: 'Round aperto',
closing: 'Round chiuso — attesa conferma puntate',
drawing: 'Estrazione in corso',
paying_out: 'Pagamento al vincitore in corso',
};
function updateChainStatusBar(data) {
const dot = document.getElementById('chain-status-dot');
const label = document.getElementById('chain-status-label');
const block = document.getElementById('chain-block');
// The dot's color/pulse only distinguishes waiting/open/drawing (that's all
// the CSS defines) — closing and paying_out both pulse like drawing, they
// just get their own text label below.
let dotKey;
if (!data.round_id) dotKey = 'waiting';
else if (DRAWING_STATUSES.includes(data.status)) dotKey = 'drawing';
else dotKey = 'open';
const labelKey = data.round_id && data.status in CHAIN_STATUS_LABELS ? data.status : 'waiting';
dot.className = 'status-dot status-' + dotKey;
label.textContent = CHAIN_STATUS_LABELS[labelKey];
block.textContent = 'Blocco ' + (data.chain_tip_height != null ? '#' + data.chain_tip_height : '—');
document.getElementById('maintenance-banner').classList.toggle('hidden', !data.lottery_paused);
}
// After a couple of consecutive failed polls (network blip, server restart,
// tab suspended too long...), say so explicitly instead of silently leaving
// whatever status happened to be on screen — a frozen "Round aperto" that's
// actually minutes stale is worse than an honest "connessione persa".
const STALE_AFTER_FAILURES = 2;
let consecutiveFetchFailures = 0;
function showConnectionLost() {
document.getElementById('chain-status-dot').className = 'status-dot status-offline';
document.getElementById('chain-status-label').textContent = 'Connessione al server persa — riprovo…';
}
function noteFetchOutcome(ok) {
if (ok) {
consecutiveFetchFailures = 0;
return;
}
consecutiveFetchFailures++;
if (consecutiveFetchFailures >= STALE_AFTER_FAILURES) showConnectionLost();
}
let chainOnlyInterval = null;
async function refreshChainStatusOnly() {
try {
const data = await call('GET', '/rounds/current');
updateChainStatusBar(data);
noteFetchOutcome(true);
} catch (e) {
noteFetchOutcome(false);
}
}
function startChainOnlyPolling() {
refreshChainStatusOnly();
clearInterval(chainOnlyInterval);
chainOnlyInterval = setInterval(refreshChainStatusOnly, 15000);
}
function stopChainOnlyPolling() {
clearInterval(chainOnlyInterval);
chainOnlyInterval = null;
}
// Background tabs get their timers throttled hard by the browser (sometimes to
// once a minute or less) — waiting for the next lazy tick after the user comes
// back could show a stale round state for a while. Refresh immediately instead
// as soon as the tab becomes visible again.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'visible') return;
if (chainOnlyInterval !== null) {
refreshChainStatusOnly();
} else if (token) {
refreshRound();
checkLastRoundResult();
}
});
// The win/lose box's content lives in localStorage, not just in-memory state —
// a page reload (or a completely fresh tab) must be able to redraw it exactly
// as it was, without waiting for a new poll or re-running the reveal
// animation. This is the single source of truth for "what result box (if any)
// is currently shown"; refreshRound() and checkLastRoundResult() below both
// read/write it instead of keeping their own separate notion of "revealed".
const PERSISTED_RESULT_KEY = 'plm_persisted_result';
function getPersistedResult() {
try {
return JSON.parse(localStorage.getItem(PERSISTED_RESULT_KEY));
} catch (e) {
return null;
}
}
function persistResult(roundId, won, amountSats) {
localStorage.setItem(PERSISTED_RESULT_KEY, JSON.stringify({ round_id: roundId, won, amount_sats: amountSats }));
}
function clearPersistedResult() {
localStorage.removeItem(PERSISTED_RESULT_KEY);
}
function renderPersistedResult(result) {
setRoundInfoVisible(false);
setResultBoxVisible(
true,
result.won ? '🎉 Hai vinto! +' + (result.amount_sats / SATS_PER_PLM) + ' PLM' : 'Non hai vinto questa volta.',
result.won ? 'win' : 'lose'
);
}
// The most recent round_id refreshRound() actually saw from the server (null
// meaning "confirmed no active round"; undefined meaning "haven't polled yet").
// Lets checkLastRoundResult() below avoid clobbering a round that's already
// known to be open/in-progress by the time its own (slower, DB-backed) request
// resolves.
let currentRoundIdSeen;
// Backstop for the live reveal in refreshRound(): that one only works if a poll
// happens to land while the round is still "paying_out" (winner_user_id is
// dropped from /rounds/current the instant the round flips to "closed" — see
// rounds/service.get_active_round). A backgrounded tab, a missed poll, or a
// late page load can miss that window entirely, in which case the live path
// never fires and the player would otherwise never learn the outcome. This
// reads GET /users/me/last-round-result, which reports the durable DB record
// instead of an ephemeral snapshot, so it always catches up eventually.
async function checkLastRoundResult() {
if (!token) return;
let data;
try {
data = await call('GET', '/users/me/last-round-result');
} catch (e) {
return; // silent — this is a backstop, refreshRound()'s own error handling already covers the primary path
}
if (data.round_id == null) return;
const persisted = getPersistedResult();
if (persisted && persisted.round_id === data.round_id) return; // already showing/known
if (currentRoundIdSeen != null && currentRoundIdSeen !== data.round_id) return; // a newer round is already in progress on screen
persistResult(data.round_id, data.won, data.amount_sats);
renderPersistedResult({ won: data.won, amount_sats: data.amount_sats });
if (data.won) {
const won = data.amount_sats / SATS_PER_PLM;
toast('Hai vinto il round #' + data.round_id + '! +' + won + ' PLM', 'success');
refreshMe();
}
}
let lastJackpotValue = null;
let timerHitZero = false;
function updateRoundTimer() {
const el = document.getElementById('round-timer');
if (!roundCloseAt) { el.textContent = '--:--'; timerHitZero = false; return; }
const rawSec = Math.floor((roundCloseAt - serverNow()) / 1000);
const totalSec = Math.max(0, rawSec);
const mm = String(Math.floor(totalSec / 60)).padStart(2, '0');
const ss = String(totalSec % 60).padStart(2, '0');
el.textContent = mm + ':' + ss;
// The countdown alone can't know the round actually closed server-side — poll
// right away instead of waiting up to 15s for the next scheduled tick, so the
// card doesn't sit on "00:00 · aperto" longer than necessary.
if (rawSec <= 0 && !timerHitZero) {
timerHitZero = true;
refreshRound();
} else if (rawSec > 0) {
timerHitZero = false;
}
}
// The round's normal info (title/timer/players/jackpot) vs. the drawing-phase
// spinner box vs. the personalized win/lose box are three independently
// toggled pieces, not three mutually-exclusive "screens" — during closing/
// drawing/paying_out, EVERY viewer sees the drawing box (generic phase
// progress), and a player who bet in that round ALSO sees the win/lose box at
// the same time once revealed, instead of the two fighting over one slot.
function setRoundInfoVisible(show) {
document.getElementById('round-normal-row').classList.toggle('hidden', !show);
document.getElementById('round-stats-row').classList.toggle('hidden', !show);
}
function setDrawingBoxVisible(show, label) {
document.getElementById('draw-state').classList.toggle('active', show);
if (show && label) document.getElementById('draw-label').textContent = label;
}
function setResultBoxVisible(show, html, cls) {
const el = document.getElementById('draw-result');
if (show) {
el.className = 'draw-result ' + cls;
el.innerHTML = html;
}
el.classList.toggle('hidden', !show);
}
function showNormalState() {
setRoundInfoVisible(true);
setDrawingBoxVisible(false);
setResultBoxVisible(false);
}
async function refreshRound() {
const seq = ++roundRequestSeq;
const epoch = sessionEpoch;
try {
const data = await call('GET', '/rounds/current');
if (epoch !== sessionEpoch) return; // session ended (or a new one started) while this was in flight
if (seq < roundAppliedSeq) return; // a newer refreshRound() call already applied its result
roundAppliedSeq = seq;
noteFetchOutcome(true);
updateChainStatusBar(data);
document.getElementById('round-title').textContent = data.round_id
? 'Round #' + data.round_id + ' — ' + (ROUND_STATUS_LABELS[data.status] || data.status)
: 'Nessun round attivo';
document.getElementById('round-players').textContent = data.participant_count;
const jackpotEl = document.getElementById('round-jackpot');
const jackpotValue = data.jackpot_sats / SATS_PER_PLM;
jackpotEl.textContent = jackpotValue;
if (lastJackpotValue !== null && jackpotValue !== lastJackpotValue) {
jackpotEl.classList.remove('jackpot-bump');
void jackpotEl.offsetWidth; // restart the animation
jackpotEl.classList.add('jackpot-bump');
}
lastJackpotValue = jackpotValue;
if (data.server_time) serverTimeOffsetMs = new Date(data.server_time) - new Date();
roundCloseAt = data.closes_at ? new Date(data.closes_at) : null;
updateRoundTimer();
currentRoundIdSeen = data.round_id || null;
const isDrawing = data.round_id && DRAWING_STATUSES.includes(data.status);
document.getElementById('round-card').classList.toggle('drawing-glow', !!isDrawing);
const persisted = getPersistedResult();
if (isDrawing) {
setRoundInfoVisible(false);
// The drawing-phase box (spinner + phase label) is generic status info —
// every viewer sees it for the whole closing/drawing/paying_out phase,
// regardless of whether they played in this round.
setDrawingBoxVisible(true, drawingLabelFor(data));
// The cosmetic reveal delay is anchored to the server's closes_at, not to
// any client-side "when did I first see this" timestamp — a page reload
// (or repeated reloads) can never reset it, since it's derived purely
// from server-provided values that don't change for this round.
const elapsedMs = serverNow() - new Date(data.closes_at);
const minMs = data.draw_animation_seconds * 1000;
const alreadyKnown = persisted && persisted.round_id === data.round_id;
// myUserId may not be loaded yet on the very first tick after a reload
// (refreshMe() and refreshRound() run concurrently) — fall back to the
// persisted result rather than risk showing nothing or the wrong side.
const canReveal =
data.user_played && data.winner_user_id != null && (alreadyKnown || elapsedMs >= minMs) && myUserId != null;
if (canReveal) {
const won = data.winner_user_id === myUserId;
if (!alreadyKnown) {
persistResult(data.round_id, won, data.winner_amount_sats);
if (won) {
const wonAmount = (data.winner_amount_sats / SATS_PER_PLM);
toast('Hai vinto il round #' + data.round_id + '! +' + wonAmount + ' PLM', 'success');
refreshMe(); // the win toast is useless if the balance card still shows the pre-payout amount
}
}
renderPersistedResult({ won, amount_sats: data.winner_amount_sats });
} else if (alreadyKnown) {
renderPersistedResult(persisted);
} else {
setResultBoxVisible(false);
}
} else {
setDrawingBoxVisible(false);
if (data.round_id && (!persisted || data.round_id !== persisted.round_id)) {
// a genuinely new round is open — clear any previous result and go back to normal
clearPersistedResult();
showNormalState();
} else if (!data.round_id && !persisted) {
// nothing has ever been revealed and there's no active round — plain empty state
showNormalState();
} else if (persisted) {
// no active round right now (cooldown, or a page reload after the round
// fully closed) — keep the persisted result on screen regardless, until
// a genuinely new round replaces it above.
renderPersistedResult(persisted);
}
}
scheduleNextRoundPoll(isDrawing);
} catch (e) {
if (epoch !== sessionEpoch) return; // session ended (or a new one started) while this was in flight
noteFetchOutcome(false);
scheduleNextRoundPoll(false);
}
}
function scheduleNextRoundPoll(fast) {
clearTimeout(roundPollTimeout);
roundPollTimeout = setTimeout(refreshRound, fast ? 3000 : 15000);
}
async function showDashboard() {
sessionEpoch++; // invalidate any dashboard poll chain left over from a previous login
stopChainOnlyPolling();
document.getElementById('landing-hero').classList.add('hidden');
document.getElementById('auth-section').classList.add('hidden');
document.getElementById('app-navbar').classList.remove('hidden');
document.getElementById('dashboard-section').classList.remove('hidden');
document.getElementById('dash-username').textContent = username;
document.getElementById('dash-address').textContent = address;
document.getElementById('dash-qr').src = '/qr/' + encodeURIComponent(address);
// Render instantly from localStorage, before the network round-trip below —
// otherwise a reload right after a win/lose flashes an empty round card for
// a moment. refreshRound()'s own response reconciles this shortly after
// (e.g. hides it again if a new round has since opened).
const persisted = getPersistedResult();
if (persisted) renderPersistedResult(persisted);
// Awaited so myUserId is populated before refreshRound() decides whether
// data.winner_user_id === myUserId — otherwise that comparison could race
// against an unset myUserId right after a reload.
await refreshMe();
// Awaited too, and before refreshRound(): on a brand-new browser/device that
// never saw this round live (nothing in localStorage), this is the only
// thing that knows the outcome once the round has fully closed. Resolving
// it first means refreshRound() finds the answer already in place instead
// of momentarily rendering "no result" and then flipping to the win/lose
// box a moment later once this backstop catches up.
await checkLastRoundResult();
refreshRound();
clearInterval(lastResultInterval);
lastResultInterval = setInterval(checkLastRoundResult, 20000);
clearInterval(roundTimerInterval);
roundTimerInterval = setInterval(updateRoundTimer, 1000);
}
function persistSession(data, u) {
token = data.access_token; username = u; address = data.address;
localStorage.setItem('plm_token', token);
localStorage.setItem('plm_username', username);
localStorage.setItem('plm_address', address);
}
async function register() {
const btn = document.getElementById('register-btn');
const u = document.getElementById('reg-username').value;
const p = document.getElementById('reg-password').value;
const pConfirm = document.getElementById('reg-password-confirm').value;
if (p !== pConfirm) {
toast('Le password non coincidono.', 'error');
return;
}
await withLoading(btn, 'Creazione…', async () => {
try {
const data = await call('POST', '/auth/register', { username: u, password: p });
persistSession(data, u);
toast('Account creato.', 'success');
showDashboard();
} catch (e) {
toast(e.message, 'error');
}
});
}
async function login() {
const btn = document.getElementById('login-btn');
const u = document.getElementById('login-username').value;
const p = document.getElementById('login-password').value;
await withLoading(btn, 'Accesso…', async () => {
try {
const data = await call('POST', '/auth/login', { username: u, password: p });
persistSession(data, u);
toast('Accesso riuscito.', 'success');
showDashboard();
} catch (e) {
toast(e.message, 'error');
}
});
}
function resetToLoggedOutUI() {
sessionEpoch++; // invalidate any refreshRound() still in flight from the dashboard we're leaving
token = username = address = null;
myUserId = null;
currentRoundIdSeen = undefined;
clearInterval(roundTimerInterval);
clearTimeout(roundPollTimeout);
clearInterval(lastResultInterval);
lastResultInterval = null;
document.getElementById('app-navbar').classList.add('hidden');
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('auth-section').classList.remove('hidden');
document.getElementById('landing-hero').classList.remove('hidden');
startChainOnlyPolling();
}
function logout() {
localStorage.clear();
resetToLoggedOutUI();
}
// Fires in every OTHER tab of this origin when one tab clears/changes plm_token
// (e.g. via logout()) — keeps all open tabs in sync instead of leaving stale
// ones showing a dashboard for a session that no longer exists anywhere else.
window.addEventListener('storage', (event) => {
if (event.key === 'plm_token' && !event.newValue) {
resetToLoggedOutUI();
}
});
// Bfcache restores a frozen snapshot of the DOM/JS state from before the user
// navigated away, without re-running this script — so a stale "logged in" (or
// stale "logged out") view could persist across back/forward navigation. Cache-
// Control: no-store on this response should already prevent that, but re-derive
// the UI from storage here too as a safety net for browsers that ignore it.
window.addEventListener('pageshow', (event) => {
if (event.persisted) initAuthState();
});
function initAuthState() {
token = localStorage.getItem('plm_token');
username = localStorage.getItem('plm_username');
address = localStorage.getItem('plm_address');
if (token) {
showDashboard();
} else {
resetToLoggedOutUI();
}
}
async function copyAddress() {
try {
await navigator.clipboard.writeText(address);
toast('Indirizzo copiato.', 'success');
} catch (e) {
toast('Impossibile copiare automaticamente.', 'error');
}
}
let myUserId = null;
let myBalanceSats = 0; // confirmed, spendable balance — what withdrawals/bets can actually draw from
// Shows the pending-inclusive balance (confirmed + own change still unconfirmed
// in a broadcast bet/withdrawal — see compute_pending_balance in
// app/wallet/balance.py) so the number doesn't drop by more than the amount
// actually spent while a tx is in flight. Green once settled, amber while
// has_pending is true so it's clear the figure isn't final yet.
function setBalanceDisplay(elementId, pendingBalanceSats, hasPending) {
const el = document.getElementById(elementId);
el.textContent = pendingBalanceSats / SATS_PER_PLM;
el.classList.toggle('balance-pending', hasPending);
el.classList.toggle('balance-confirmed', !hasPending);
}
async function refreshMe() {
const btn = document.getElementById('refresh-btn');
await withLoading(btn, '…', async () => {
try {
const data = await call('GET', '/users/me');
myUserId = data.id;
myBalanceSats = data.balance_sats;
setBalanceDisplay('dash-balance', data.pending_balance_sats, data.has_pending);
document.getElementById('navbar-balance').textContent = (data.pending_balance_sats / SATS_PER_PLM) + ' PLM';
document.getElementById('navbar-balance').classList.toggle('balance-pending', data.has_pending);
document.getElementById('navbar-balance').classList.toggle('balance-confirmed', !data.has_pending);
document.getElementById('profile-username').textContent = data.username;
document.getElementById('profile-address').textContent = data.address;
setBalanceDisplay('profile-balance', data.pending_balance_sats, data.has_pending);
document.getElementById('profile-created-at').textContent = new Date(data.created_at).toLocaleDateString('it-IT');
document.getElementById('wd-full-amount-value').textContent = data.balance_sats / SATS_PER_PLM;
if (document.getElementById('wd-full-amount').checked) {
document.getElementById('wd-amount').value = data.balance_sats / SATS_PER_PLM;
}
} catch (e) {
toast(e.message, 'error');
}
});
}
function toggleWithdrawFullAmount() {
const checked = document.getElementById('wd-full-amount').checked;
const amountInput = document.getElementById('wd-amount');
amountInput.disabled = checked;
if (checked) amountInput.value = myBalanceSats / SATS_PER_PLM;
}
async function changePassword() {
const btn = document.getElementById('change-password-btn');
const currentPassword = document.getElementById('settings-current-password').value;
const newPassword = document.getElementById('settings-new-password').value;
const newPasswordConfirm = document.getElementById('settings-new-password-confirm').value;
if (newPassword !== newPasswordConfirm) {
toast('Le nuove password non coincidono.', 'error');
return;
}
if (newPassword.length < 8) {
toast('La nuova password deve avere almeno 8 caratteri.', 'error');
return;
}
await withLoading(btn, 'Aggiornamento…', async () => {
try {
await call('POST', '/users/me/change-password', {
current_password: currentPassword,
new_password: newPassword,
});
document.getElementById('settings-current-password').value = '';
document.getElementById('settings-new-password').value = '';
document.getElementById('settings-new-password-confirm').value = '';
toast('Password aggiornata.', 'success');
} catch (e) {
toast(e.message, 'error');
}
});
}
async function placeBet() {
const btn = document.getElementById('bet-btn');
await withLoading(btn, 'Invio bet…', async () => {
try {
const data = await call('POST', '/bets', {});
toast('Bet piazzata sul round #' + data.round_id + '.', 'success');
} catch (e) {
toast(e.message, 'error');
}
});
refreshMe();
refreshRound();
}
async function withdraw() {
const btn = document.getElementById('withdraw-btn');
const ext = document.getElementById('wd-address').value;
const isFullAmount = document.getElementById('wd-full-amount').checked;
const amtSats = isFullAmount
? myBalanceSats
: Math.round(parseFloat(document.getElementById('wd-amount').value) * SATS_PER_PLM);
await withLoading(btn, 'Invio…', async () => {
try {
await call('POST', '/withdrawals', { external_address: ext, amount_sats: amtSats });
toast('Withdrawal inviato.', 'success');
document.getElementById('wd-full-amount').checked = false;
toggleWithdrawFullAmount();
document.getElementById('wd-amount').value = '';
} catch (e) {
toast(e.message, 'error');
}
});
refreshMe();
}
// Server push: an SSE channel that notifies the instant round/bet/balance
// state changes anywhere (see app/rounds/events.py), instead of everyone
// waiting for their next poll tick. The message carries no payload — it just
// means "something changed", so we react by immediately re-running the same
// refreshes the polling loop would eventually do on its own. Polling is left
// completely in place as a fallback: if this connection is blocked/dropped
// (proxy, browser setting, flaky network), the page keeps working exactly as
// before, just without the instant nudge.
let roundEventSource = null;
function onRoundServerEvent() {
if (token) {
refreshRound();
refreshMe();
checkLastRoundResult();
} else {
refreshChainStatusOnly();
}
}
function connectRoundEvents() {
if (roundEventSource) return;
roundEventSource = new EventSource('/rounds/stream');
roundEventSource.addEventListener('update', onRoundServerEvent);
// Fires on the initial connection AND every successful auto-reconnect (the
// browser retries this on its own after a drop) — re-syncs immediately
// instead of leaving the page on whatever it last knew until the next event
// or poll tick, which would otherwise widen the "missed while disconnected"
// window to the full reconnect gap.
roundEventSource.addEventListener('open', onRoundServerEvent);
}
connectRoundEvents();
initAuthState();
+1 -529
View File
@@ -235,535 +235,7 @@
<div id="toast-container" aria-live="polite"></div>
<script>
const SATS_PER_PLM = 100000000;
let token = localStorage.getItem('plm_token');
let username = localStorage.getItem('plm_username');
let address = localStorage.getItem('plm_address');
function toast(message, type) {
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = 'toast ' + type;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), 4000);
}
async function withLoading(button, label, fn) {
const original = button.textContent;
button.disabled = true;
button.textContent = label;
try {
await fn();
} finally {
button.disabled = false;
button.textContent = original;
}
}
async function call(method, path, body) {
const headers = { 'Content-Type': 'application/json' };
if (token) headers['Authorization'] = 'Bearer ' + token;
const res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || res.statusText);
return data;
}
function switchTab(name) {
document.getElementById('tab-login').classList.toggle('active', name === 'login');
document.getElementById('tab-register').classList.toggle('active', name === 'register');
document.getElementById('panel-login').classList.toggle('active', name === 'login');
document.getElementById('panel-register').classList.toggle('active', name === 'register');
}
function switchPanel(name) {
for (const key of ['deposit', 'bet', 'withdraw', 'profile']) {
document.getElementById('nav-' + key).classList.toggle('active', key === name);
document.getElementById('panel-' + key).classList.toggle('active', key === name);
}
}
let roundCloseAt = null;
let serverTimeOffsetMs = 0; // serverNow - clientNow, so every client's countdown agrees regardless of local clock skew
function serverNow() { return new Date(Date.now() + serverTimeOffsetMs); }
// refreshRound() is triggered from several independent sources (poll timer, timer-hits-zero,
// visibilitychange, placeBet, showDashboard) whose requests can resolve out of order over the
// network. Track the latest applied response so a slow, stale one can never revert the UI to an
// older round's state after a newer response has already moved it forward.
let roundRequestSeq = 0;
let roundAppliedSeq = 0;
let roundTimerInterval = null;
let roundPollTimeout = null;
const ROUND_STATUS_LABELS = {
open: 'aperto',
closing: 'in chiusura',
drawing: 'estrazione in corso',
paying_out: 'pagamento in corso',
};
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
// One distinct message per DRAW sub-phase (see CLAUDE.md's "three separate
// on-chain confirmations" note) instead of a single generic spinner label —
// takes the round data so the drawing phase can surface the draw block once known.
function drawingLabelFor(data) {
if (data.status === 'closing') {
return 'Round chiuso — in attesa di conferma dell\'ultima giocata prima di estrarre il vincitore…';
}
if (data.status === 'drawing') {
return 'In attesa del prossimo blocco per estrarre il vincitore…';
}
// paying_out
if (data.draw_block_height != null) {
return 'Vincitore estratto dal blocco #' + data.draw_block_height + ' — pagamento in corso…';
}
return 'Vincitore estratto — pagamento in corso…';
}
// One label per real round status, not just the coarse open/drawing/waiting
// grouping — the status bar should show the same phase distinction as the
// draw-state panel (drawingLabelFor above), just condensed to a short phrase.
const CHAIN_STATUS_LABELS = {
waiting: 'In attesa del prossimo round',
open: 'Round aperto',
closing: 'Round chiuso — attesa conferma puntate',
drawing: 'Estrazione in corso',
paying_out: 'Pagamento in corso',
};
function updateChainStatusBar(data) {
const dot = document.getElementById('chain-status-dot');
const label = document.getElementById('chain-status-label');
const block = document.getElementById('chain-block');
// The dot's color/pulse only distinguishes waiting/open/drawing (that's all
// the CSS defines) — closing and paying_out both pulse like drawing, they
// just get their own text label below.
let dotKey;
if (!data.round_id) dotKey = 'waiting';
else if (DRAWING_STATUSES.includes(data.status)) dotKey = 'drawing';
else dotKey = 'open';
const labelKey = data.round_id && data.status in CHAIN_STATUS_LABELS ? data.status : 'waiting';
dot.className = 'status-dot status-' + dotKey;
label.textContent = CHAIN_STATUS_LABELS[labelKey];
block.textContent = 'Blocco ' + (data.chain_tip_height != null ? '#' + data.chain_tip_height : '—');
document.getElementById('maintenance-banner').classList.toggle('hidden', !data.lottery_paused);
}
// After a couple of consecutive failed polls (network blip, server restart,
// tab suspended too long...), say so explicitly instead of silently leaving
// whatever status happened to be on screen — a frozen "Round aperto" that's
// actually minutes stale is worse than an honest "connessione persa".
const STALE_AFTER_FAILURES = 2;
let consecutiveFetchFailures = 0;
function showConnectionLost() {
document.getElementById('chain-status-dot').className = 'status-dot status-offline';
document.getElementById('chain-status-label').textContent = 'Connessione al server persa — riprovo…';
}
function noteFetchOutcome(ok) {
if (ok) {
consecutiveFetchFailures = 0;
return;
}
consecutiveFetchFailures++;
if (consecutiveFetchFailures >= STALE_AFTER_FAILURES) showConnectionLost();
}
let chainOnlyInterval = null;
async function refreshChainStatusOnly() {
try {
const data = await call('GET', '/rounds/current');
updateChainStatusBar(data);
noteFetchOutcome(true);
} catch (e) {
noteFetchOutcome(false);
}
}
function startChainOnlyPolling() {
refreshChainStatusOnly();
clearInterval(chainOnlyInterval);
chainOnlyInterval = setInterval(refreshChainStatusOnly, 15000);
}
function stopChainOnlyPolling() {
clearInterval(chainOnlyInterval);
chainOnlyInterval = null;
}
// Background tabs get their timers throttled hard by the browser (sometimes to
// once a minute or less) — waiting for the next lazy tick after the user comes
// back could show a stale round state for a while. Refresh immediately instead
// as soon as the tab becomes visible again.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'visible') return;
if (chainOnlyInterval !== null) {
refreshChainStatusOnly();
} else if (token) {
refreshRound();
}
});
// Per round_id: when we first saw it enter a drawing status (client clock), and
// whether the win/lose result has already been shown for it. Local-only state,
// not persisted — a page reload just re-derives it from the next poll.
const drawStartedAt = {};
const revealedRounds = new Set();
let activeResultRoundId = null; // round_id whose win/lose result is on screen, if any
let lastJackpotValue = null;
let timerHitZero = false;
function updateRoundTimer() {
const el = document.getElementById('round-timer');
if (!roundCloseAt) { el.textContent = '--:--'; timerHitZero = false; return; }
const rawSec = Math.floor((roundCloseAt - serverNow()) / 1000);
const totalSec = Math.max(0, rawSec);
const mm = String(Math.floor(totalSec / 60)).padStart(2, '0');
const ss = String(totalSec % 60).padStart(2, '0');
el.textContent = mm + ':' + ss;
// The countdown alone can't know the round actually closed server-side — poll
// right away instead of waiting up to 15s for the next scheduled tick, so the
// card doesn't sit on "00:00 · aperto" longer than necessary.
if (rawSec <= 0 && !timerHitZero) {
timerHitZero = true;
refreshRound();
} else if (rawSec > 0) {
timerHitZero = false;
}
}
function showDrawingState(label) {
document.getElementById('round-normal-row').classList.add('hidden');
document.getElementById('round-stats-row').classList.add('hidden');
document.getElementById('draw-state').classList.add('active');
document.getElementById('draw-result').classList.add('hidden');
if (label) document.getElementById('draw-label').textContent = label;
}
function showResultState(html, cls) {
document.getElementById('round-normal-row').classList.add('hidden');
document.getElementById('round-stats-row').classList.add('hidden');
document.getElementById('draw-state').classList.remove('active');
const el = document.getElementById('draw-result');
el.className = 'draw-result ' + cls;
el.innerHTML = html;
el.classList.remove('hidden');
}
function showNormalState() {
document.getElementById('round-normal-row').classList.remove('hidden');
document.getElementById('round-stats-row').classList.remove('hidden');
document.getElementById('draw-state').classList.remove('active');
document.getElementById('draw-result').classList.add('hidden');
}
async function refreshRound() {
const seq = ++roundRequestSeq;
try {
const data = await call('GET', '/rounds/current');
if (seq < roundAppliedSeq) return; // a newer refreshRound() call already applied its result
roundAppliedSeq = seq;
noteFetchOutcome(true);
updateChainStatusBar(data);
document.getElementById('round-title').textContent = data.round_id
? 'Round #' + data.round_id + ' — ' + (ROUND_STATUS_LABELS[data.status] || data.status)
: 'Nessun round attivo';
document.getElementById('round-players').textContent = data.participant_count;
const jackpotEl = document.getElementById('round-jackpot');
const jackpotValue = data.jackpot_sats / SATS_PER_PLM;
jackpotEl.textContent = jackpotValue;
if (lastJackpotValue !== null && jackpotValue !== lastJackpotValue) {
jackpotEl.classList.remove('jackpot-bump');
void jackpotEl.offsetWidth; // restart the animation
jackpotEl.classList.add('jackpot-bump');
}
lastJackpotValue = jackpotValue;
if (data.server_time) serverTimeOffsetMs = new Date(data.server_time) - new Date();
roundCloseAt = data.closes_at ? new Date(data.closes_at) : null;
updateRoundTimer();
const isDrawing = data.round_id && DRAWING_STATUSES.includes(data.status);
document.getElementById('round-card').classList.toggle('drawing-glow', !!isDrawing);
if (isDrawing) {
if (!(data.round_id in drawStartedAt)) drawStartedAt[data.round_id] = Date.now();
const elapsedMs = Date.now() - drawStartedAt[data.round_id];
const minMs = data.draw_animation_seconds * 1000;
if (data.winner_user_id != null && elapsedMs >= minMs && !revealedRounds.has(data.round_id)) {
revealedRounds.add(data.round_id);
activeResultRoundId = data.round_id;
if (myUserId != null && data.winner_user_id === myUserId) {
const won = (data.winner_amount_sats / SATS_PER_PLM);
showResultState('🎉 Hai vinto! +' + won + ' PLM', 'win');
toast('Hai vinto il round #' + data.round_id + '! +' + won + ' PLM', 'success');
} else {
showResultState('Non hai vinto questa volta.', 'lose');
}
} else if (!revealedRounds.has(data.round_id)) {
showDrawingState(drawingLabelFor(data));
}
} else if (data.round_id && data.round_id !== activeResultRoundId) {
// a genuinely new round is open — clear any previous result and go back to normal
activeResultRoundId = null;
// drop bookkeeping for old rounds so these maps don't grow for the life of the session
for (const key of Object.keys(drawStartedAt)) {
if (Number(key) !== data.round_id) delete drawStartedAt[key];
}
for (const id of revealedRounds) {
if (id !== data.round_id) revealedRounds.delete(id);
}
showNormalState();
} else if (!data.round_id && activeResultRoundId == null) {
// nothing has ever been revealed and there's no active round — plain empty state
showNormalState();
}
// else: no active round right now, but we just revealed a result for the last
// one — keep it on screen through the cooldown gap instead of flashing back to
// "Nessun round attivo".
scheduleNextRoundPoll(isDrawing);
} catch (e) {
noteFetchOutcome(false);
scheduleNextRoundPoll(false);
}
}
function scheduleNextRoundPoll(fast) {
clearTimeout(roundPollTimeout);
roundPollTimeout = setTimeout(refreshRound, fast ? 3000 : 15000);
}
function showDashboard() {
stopChainOnlyPolling();
document.getElementById('landing-hero').classList.add('hidden');
document.getElementById('auth-section').classList.add('hidden');
document.getElementById('app-navbar').classList.remove('hidden');
document.getElementById('dashboard-section').classList.remove('hidden');
document.getElementById('dash-username').textContent = username;
document.getElementById('dash-address').textContent = address;
document.getElementById('dash-qr').src = '/qr/' + encodeURIComponent(address);
refreshMe();
refreshRound();
clearInterval(roundTimerInterval);
roundTimerInterval = setInterval(updateRoundTimer, 1000);
}
function persistSession(data, u) {
token = data.access_token; username = u; address = data.address;
localStorage.setItem('plm_token', token);
localStorage.setItem('plm_username', username);
localStorage.setItem('plm_address', address);
}
async function register() {
const btn = document.getElementById('register-btn');
const u = document.getElementById('reg-username').value;
const p = document.getElementById('reg-password').value;
const pConfirm = document.getElementById('reg-password-confirm').value;
if (p !== pConfirm) {
toast('Le password non coincidono.', 'error');
return;
}
await withLoading(btn, 'Creazione…', async () => {
try {
const data = await call('POST', '/auth/register', { username: u, password: p });
persistSession(data, u);
toast('Account creato.', 'success');
showDashboard();
} catch (e) {
toast(e.message, 'error');
}
});
}
async function login() {
const btn = document.getElementById('login-btn');
const u = document.getElementById('login-username').value;
const p = document.getElementById('login-password').value;
await withLoading(btn, 'Accesso…', async () => {
try {
const data = await call('POST', '/auth/login', { username: u, password: p });
persistSession(data, u);
toast('Accesso riuscito.', 'success');
showDashboard();
} catch (e) {
toast(e.message, 'error');
}
});
}
function resetToLoggedOutUI() {
token = username = address = null;
myUserId = null;
activeResultRoundId = null;
revealedRounds.clear();
for (const key of Object.keys(drawStartedAt)) delete drawStartedAt[key];
clearInterval(roundTimerInterval);
clearTimeout(roundPollTimeout);
document.getElementById('app-navbar').classList.add('hidden');
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('auth-section').classList.remove('hidden');
document.getElementById('landing-hero').classList.remove('hidden');
startChainOnlyPolling();
}
function logout() {
localStorage.clear();
resetToLoggedOutUI();
}
// Fires in every OTHER tab of this origin when one tab clears/changes plm_token
// (e.g. via logout()) — keeps all open tabs in sync instead of leaving stale
// ones showing a dashboard for a session that no longer exists anywhere else.
window.addEventListener('storage', (event) => {
if (event.key === 'plm_token' && !event.newValue) {
resetToLoggedOutUI();
}
});
// Bfcache restores a frozen snapshot of the DOM/JS state from before the user
// navigated away, without re-running this script — so a stale "logged in" (or
// stale "logged out") view could persist across back/forward navigation. Cache-
// Control: no-store on this response should already prevent that, but re-derive
// the UI from storage here too as a safety net for browsers that ignore it.
window.addEventListener('pageshow', (event) => {
if (event.persisted) initAuthState();
});
function initAuthState() {
token = localStorage.getItem('plm_token');
username = localStorage.getItem('plm_username');
address = localStorage.getItem('plm_address');
if (token) {
showDashboard();
} else {
resetToLoggedOutUI();
}
}
async function copyAddress() {
try {
await navigator.clipboard.writeText(address);
toast('Indirizzo copiato.', 'success');
} catch (e) {
toast('Impossibile copiare automaticamente.', 'error');
}
}
let myUserId = null;
let myBalanceSats = 0;
async function refreshMe() {
const btn = document.getElementById('refresh-btn');
await withLoading(btn, '…', async () => {
try {
const data = await call('GET', '/users/me');
myUserId = data.id;
myBalanceSats = data.balance_sats;
document.getElementById('dash-balance').textContent = data.balance_sats / SATS_PER_PLM;
document.getElementById('navbar-balance').textContent = (data.balance_sats / SATS_PER_PLM) + ' PLM';
document.getElementById('profile-username').textContent = data.username;
document.getElementById('profile-address').textContent = data.address;
document.getElementById('profile-balance').textContent = data.balance_sats / SATS_PER_PLM;
document.getElementById('profile-created-at').textContent = new Date(data.created_at).toLocaleDateString('it-IT');
document.getElementById('wd-full-amount-value').textContent = data.balance_sats / SATS_PER_PLM;
if (document.getElementById('wd-full-amount').checked) {
document.getElementById('wd-amount').value = data.balance_sats / SATS_PER_PLM;
}
} catch (e) {
toast(e.message, 'error');
}
});
}
function toggleWithdrawFullAmount() {
const checked = document.getElementById('wd-full-amount').checked;
const amountInput = document.getElementById('wd-amount');
amountInput.disabled = checked;
if (checked) amountInput.value = myBalanceSats / SATS_PER_PLM;
}
async function changePassword() {
const btn = document.getElementById('change-password-btn');
const currentPassword = document.getElementById('settings-current-password').value;
const newPassword = document.getElementById('settings-new-password').value;
const newPasswordConfirm = document.getElementById('settings-new-password-confirm').value;
if (newPassword !== newPasswordConfirm) {
toast('Le nuove password non coincidono.', 'error');
return;
}
if (newPassword.length < 8) {
toast('La nuova password deve avere almeno 8 caratteri.', 'error');
return;
}
await withLoading(btn, 'Aggiornamento…', async () => {
try {
await call('POST', '/users/me/change-password', {
current_password: currentPassword,
new_password: newPassword,
});
document.getElementById('settings-current-password').value = '';
document.getElementById('settings-new-password').value = '';
document.getElementById('settings-new-password-confirm').value = '';
toast('Password aggiornata.', 'success');
} catch (e) {
toast(e.message, 'error');
}
});
}
async function placeBet() {
const btn = document.getElementById('bet-btn');
await withLoading(btn, 'Invio bet…', async () => {
try {
const data = await call('POST', '/bets', {});
toast('Bet piazzata sul round #' + data.round_id + '.', 'success');
} catch (e) {
toast(e.message, 'error');
}
});
refreshMe();
refreshRound();
}
async function withdraw() {
const btn = document.getElementById('withdraw-btn');
const ext = document.getElementById('wd-address').value;
const isFullAmount = document.getElementById('wd-full-amount').checked;
const amtSats = isFullAmount
? myBalanceSats
: Math.round(parseFloat(document.getElementById('wd-amount').value) * SATS_PER_PLM);
await withLoading(btn, 'Invio…', async () => {
try {
await call('POST', '/withdrawals', { external_address: ext, amount_sats: amtSats });
toast('Withdrawal inviato.', 'success');
document.getElementById('wd-full-amount').checked = false;
toggleWithdrawFullAmount();
document.getElementById('wd-amount').value = '';
} catch (e) {
toast(e.message, 'error');
}
});
refreshMe();
}
initAuthState();
</script>
<script src="/app.js"></script>
</body>
</html>
+5
View File
@@ -208,6 +208,11 @@ button.link:hover, a.link:hover { filter: none; color: var(--color-foreground);
.balance-value { font-size: 2rem; font-weight: 700; letter-spacing: -0.02em; }
.balance-unit { color: var(--color-muted-foreground); font-size: 1rem; font-weight: 500; }
/* Green once everything is confirmed; amber while a bet/withdrawal's change is
still unconfirmed — the displayed number already includes that change (see
compute_pending_balance), the color just flags that it isn't settled yet. */
.balance-confirmed { color: var(--color-success); }
.balance-pending { color: var(--color-primary); }
.icon { width: 16px; height: 16px; flex-shrink: 0; }
+2
View File
@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from app.db.models import PendingTransaction
from app.electrum.client import ElectrumClient
from app.rounds.events import broadcaster
logger = logging.getLogger(__name__)
@@ -44,6 +45,7 @@ async def poll_once(session_factory: async_sessionmaker, client: ElectrumClient)
if handler is not None:
await handler(session, row)
await session.commit()
broadcaster.publish() # a bet/withdrawal/payout just confirmed — balance and/or round state changed
confirmed += 1
return confirmed
+46 -1
View File
@@ -1,7 +1,9 @@
from embit.transaction import Transaction
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import User, UtxoEvent
from app.db.models import PendingTransaction, User, UtxoEvent
from app.wallet.plm_network import PLM_MAINNET
async def recompute_balance(session: AsyncSession, user_id: int) -> int:
@@ -14,3 +16,46 @@ async def recompute_balance(session: AsyncSession, user_id: int) -> int:
user = await session.get(User, user_id)
user.cached_balance_sats = balance or 0
return user.cached_balance_sats
async def compute_pending_balance(session: AsyncSession, user: User) -> tuple[int, bool]:
"""Balance including the user's own change still in flight.
Placing a bet or a withdrawal spends whatever UTXOs cover the amount — often
much larger than the amount actually moving, since select_utxos() picks
whole UTXOs — and recompute_balance() drops that entire input total from
cached_balance_sats the moment the tx is broadcast (spent_txid is set right
away, well before the tx has any confirmations). The change output that
returns the difference only becomes a UtxoEvent (and so counts toward the
confirmed balance again) once it gets its own 1st confirmation. In between,
User.cached_balance_sats alone understates the user's real balance by the
full unconfirmed change amount, which can look like a much bigger loss than
the tx actually represents.
This walks every in-flight (status="pending") bet/withdrawal PendingTransaction
of this user, decodes its current raw tx (kept up to date across RBF bumps —
see tx/broadcast.py:bump_fee), and sums whichever outputs pay back to the
user's own address. Adding that to cached_balance_sats gives the balance the
user will end up with once everything currently in flight confirms.
Returns (pending_inclusive_balance_sats, has_pending) — has_pending tells the
caller whether this differs from the confirmed-only balance at all.
"""
pending = (
await session.scalars(
select(PendingTransaction).where(
PendingTransaction.user_id == user.id,
PendingTransaction.kind.in_(("bet", "withdrawal")),
PendingTransaction.status == "pending",
)
)
).all()
pending_change_sats = 0
for row in pending:
tx = Transaction.parse(bytes.fromhex(row.raw_tx_hex))
for out in tx.vout:
if out.script_pubkey.address(network=PLM_MAINNET) == user.address:
pending_change_sats += out.value
return user.cached_balance_sats + pending_change_sats, bool(pending)
+2
View File
@@ -6,6 +6,7 @@ from app.audit.log import write_audit_log
from app.db.models import PendingTransaction, User, UtxoEvent, Withdrawal
from app.electrum.client import ElectrumClient
from app.rounds.config import get_round_config
from app.rounds.events import broadcaster
from app.wallet.balance import recompute_balance
from app.wallet.hd import derive_user_key
from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_signed_transaction
@@ -84,4 +85,5 @@ async def request_withdrawal(
await session.commit()
await session.refresh(withdrawal)
broadcaster.publish() # balance just went "pending" — nudge the dashboard to refetch
return withdrawal
+40 -15
View File
@@ -40,12 +40,13 @@ subito le nuove giocate, ma il round non chiude immediatamente. Se qualcuno
aveva già piazzato una bet negli ultimi istanti (transazione trasmessa ma
non ancora confermata), il round aspetta che anche quella si confermi prima
di procedere, così nessuna giocata già fatta viene persa al confine del
round. Solo a quel punto la card mostra un'animazione ("Estrazione del
vincitore in corso…") al posto del timer — la stessa cosa compare nella
dashboard di ogni giocatore, non solo la tua. L'animazione resta visibile
per almeno un tempo minimo configurabile dall'admin (default 20s), ma può
durare più a lungo, perché sotto la copertina servono **fino a tre
conferme sulla rete PLM in sequenza**, una diversa dall'altra:
round. Solo a quel punto la card mostra un messaggio di stato ("Round
chiuso — attesa conferma puntate…", poi "Estrazione in corso…", poi
"Pagamento al vincitore in corso…") al posto del timer — la stessa cosa
compare nella dashboard di **ogni** utente, anche di chi non ha giocato in
questo round. Questo messaggio resta visibile per l'intera durata della fase
(chiusura → estrazione → pagamento), perché sotto la copertina servono
**fino a tre conferme sulla rete PLM in sequenza**, una diversa dall'altra:
1. conferma dell'ultima giocata rimasta in sospeso (se ce n'era una proprio
allo scadere del timer — altrimenti questo passo è già superato);
@@ -59,14 +60,27 @@ c'era una giocata da confermare all'ultimo istante) o **2-4 minuti** (se
tutte le giocate erano già confermate prima dello zero) — non pochi
secondi, ed è normale.
Appena il vincitore è determinato, l'animazione lascia spazio a un
messaggio:
Se **hai giocato in questo round**, appena il vincitore è determinato compare
**in aggiunta** (non al posto del messaggio di stato sopra, che resta
visibile finché il pagamento non è confermato) un secondo riquadro solo per
te:
- **"🎉 Hai vinto! +N PLM"** se sei tu il vincitore — l'importo ti verrà
accreditato non appena la transazione di payout viene confermata (il
round successivo non si apre finché questo non accade)
- **"Non hai vinto questa volta."** altrimenti
Il messaggio resta visibile fino all'apertura del round successivo.
Chi non ha giocato in questo round non vede mai questo secondo riquadro,
solo il messaggio di stato generico. Il riquadro personale resta visibile
anche **dopo un refresh della pagina** (persiste nel browser), fino
all'apertura del round successivo — non serve restare sulla pagina per non
perderlo, e se hai perso completamente la finestra in tempo reale (es. tab in
background per diversi minuti), lo vedrai comunque comparire non appena
riapri la dashboard.
La dashboard si aggiorna anche **in tempo reale**, non solo a intervalli
fissi: appena qualcosa cambia sul server (una giocata, un cambio di fase del
round, un nuovo blocco confermato...) la pagina lo recepisce quasi subito,
senza bisogno di premere "Aggiorna" o ricaricare.
### Avviso di manutenzione
@@ -78,15 +92,22 @@ L'avviso sparisce da solo appena l'operatore riprende la lotteria.
### Deposito
- Il tuo **saldo interno** (accreditato dopo 1 conferma di rete) con bottone
"Aggiorna" per ricontrollarlo
- Il tuo **saldo interno**, con bottone "Aggiorna" per ricontrollarlo. Il
numero mostrato include anche il resto di una bet o un prelievo appena
inviati (non ancora confermato sulla rete) — non solo la parte già
confermata — così non sembra che il saldo sia crollato più del dovuto
subito dopo un'operazione. Il colore indica lo stato:
- **verde**: tutto confermato, il saldo mostrato è quello definitivo
- **arancione**: c'è una bet o un prelievo ancora in attesa di conferma —
il numero è corretto, ma non ancora "finale"
- Il tuo **indirizzo di deposito**, con bottone per copiarlo negli appunti
- Il **QR code** dello stesso indirizzo, comodo per inviare PLM da un altro
wallet scansionandolo invece di copiare l'indirizzo a mano
Per depositare, invia PLM (mainnet reale) a quell'indirizzo da un wallet
esterno. Il saldo si aggiorna da solo dopo la prima conferma; premi
"Aggiorna" per vederlo comparire.
esterno. Il saldo si aggiorna da solo dopo la prima conferma (e quasi subito,
grazie all'aggiornamento in tempo reale); premi "Aggiorna" se vuoi comunque
ricontrollarlo a mano.
### Bet
@@ -98,10 +119,14 @@ scalato dal tuo saldo interno.
Form con due campi:
- **Indirizzo esterno**: dove vuoi ricevere i PLM
- **Importo (PLM)**: quanto prelevare
- **Importo (PLM)**: quanto prelevare, oppure spunta **"Preleva l'intero
importo"** per prelevare tutto il saldo confermato senza doverlo
ricopiare a mano (il campo importo si disabilita e si aggiorna da solo)
Il prelievo viene costruito e trasmesso sulla rete; la fee di rete viene
scalata dall'importo richiesto (non si aggiunge separatamente).
scalata dall'importo richiesto (non si aggiunge separatamente). L'importo
minimo prelevabile è pari alla quota fissa di ingresso al round (mostrata
nella sezione Bet).
> **Nota**: attualmente è supportato solo l'indirizzo esterno in formato
> **P2WPKH bech32** (quelli che iniziano con `plm1q...`). Non inserire
+11
View File
@@ -60,6 +60,17 @@ docker compose stop # ferma senza rimuovere i container
docker compose down # ferma e rimuove i container (i dati in ./data/ restano)
```
> **Nota sul `Caddyfile`**: è montato in sola lettura nel container `caddy`
> (bind mount). Modificarlo non basta a farlo ripartire con la nuova
> configurazione — `docker compose up -d --build` non ricrea `caddy` solo
> perché il *contenuto* di un file montato è cambiato. Dopo una modifica al
> `Caddyfile` serve un passaggio in più:
> ```bash
> docker compose restart caddy
> ```
> (oppure, senza interrompere le connessioni esistenti: `docker compose exec
> caddy caddy reload --config /etc/caddy/Caddyfile`).
### ⚠️ Attenzione: riavvii automatici a metà round
`docker-compose.yml` imposta `restart: unless-stopped` sul container dell'app:
+1 -1
View File
@@ -93,7 +93,7 @@ pip install -e ".[dev]"
## 6. Impostare l'indirizzo delle fee
Prima che il primo round possa pagare, un admin deve impostare `fee_address`
tramite il pannello admin o l'API — vedi [admin-guide.md](admin-guide.md). I
tramite il pannello admin o l'API — vedi [guida-admin.md](guida-admin.md). I
payout si rifiutano di partire finché non è impostato.
A questo punto l'istanza è pronta per essere avviata — continua con
+111
View File
@@ -0,0 +1,111 @@
import pytest
from sqlalchemy import select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.bets.service import place_bet
from app.config import settings
from app.db.base import Base
from app.db.models import PendingTransaction, User, UtxoEvent
from app.wallet.balance import compute_pending_balance, recompute_balance
from app.wallet.hd import derive_user_address
class FakeElectrumClient:
async def broadcast(self, raw_tx_hex: str) -> str:
return "fake-network-txid"
@pytest.fixture
async def session_factory(tmp_path, monkeypatch):
monkeypatch.setattr(settings, "master_key_path", str(tmp_path / "master.xprv.enc"))
monkeypatch.setattr(
settings,
"xprv_encryption_key",
__import__("cryptography.fernet", fromlist=["Fernet"]).Fernet.generate_key().decode(),
)
from app.wallet import hd
hd._account_key = None
hd.generate_master_key()
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield async_sessionmaker(engine, expire_on_commit=False)
await engine.dispose()
hd._account_key = None
async def _make_funded_user(session_factory, index: int, funded_sats: int) -> int:
async with session_factory() as session:
address = derive_user_address(index)
user = User(username=f"user{index}", password_hash="x", derivation_index=index, address=address)
session.add(user)
await session.commit()
session.add(
UtxoEvent(
user_id=user.id,
txid=f"{index:02x}" * 32,
vout=0,
amount_sats=funded_sats,
confirmed_height=100,
)
)
await recompute_balance(session, user.id)
await session.commit()
return user.id
async def test_pending_balance_includes_unconfirmed_change(session_factory):
"""A bet spends a whole (much larger) UTXO and the change hasn't confirmed
yet, so cached_balance_sats alone understates the user's real balance by
the entire unconfirmed change amount — compute_pending_balance should add
it back."""
user_id = await _make_funded_user(session_factory, 0, 1_500_000_000)
client = FakeElectrumClient()
async with session_factory() as session:
user = await session.get(User, user_id)
await place_bet(session, client, user)
async with session_factory() as session:
user = await session.get(User, user_id)
assert user.cached_balance_sats == 0 # the whole funding UTXO was spent as input
pending_balance, has_pending = await compute_pending_balance(session, user)
assert has_pending is True
# confirmed (0) + unconfirmed change should be just under the original
# funding amount (minus the bet amount and the network fee)
assert 0 < pending_balance < 1_500_000_000
async def test_pending_balance_matches_confirmed_when_nothing_in_flight(session_factory):
user_id = await _make_funded_user(session_factory, 1, 2_000_000_000)
async with session_factory() as session:
user = await session.get(User, user_id)
pending_balance, has_pending = await compute_pending_balance(session, user)
assert has_pending is False
assert pending_balance == 2_000_000_000
async def test_pending_balance_ignores_other_users_pending_transactions(session_factory):
user_id = await _make_funded_user(session_factory, 2, 2_000_000_000)
other_user_id = await _make_funded_user(session_factory, 3, 1_500_000_000)
client = FakeElectrumClient()
async with session_factory() as session:
other_user = await session.get(User, other_user_id)
await place_bet(session, client, other_user)
async with session_factory() as session:
pending_rows = (await session.scalars(select(PendingTransaction))).all()
assert len(pending_rows) == 1 # sanity: only the other user has anything in flight
user = await session.get(User, user_id)
pending_balance, has_pending = await compute_pending_balance(session, user)
assert has_pending is False
assert pending_balance == 2_000_000_000
+62
View File
@@ -0,0 +1,62 @@
import asyncio
import pytest
from app.rounds.events import RoundEventBroadcaster, RoundEventCapacityError
async def test_publish_wakes_up_subscriber():
broadcaster = RoundEventBroadcaster()
queue = broadcaster.subscribe()
broadcaster.publish()
await asyncio.wait_for(queue.get(), timeout=1)
async def test_publish_with_no_subscribers_does_not_raise():
broadcaster = RoundEventBroadcaster()
broadcaster.publish() # no subscribers yet — must be a no-op, not an error
async def test_publish_coalesces_when_subscriber_has_not_drained():
"""The queue is maxsize=1: a second publish() before the subscriber reads
the first notification must not block or raise — it's fine to drop it,
since the subscriber will refetch full state anyway on the first one."""
broadcaster = RoundEventBroadcaster()
queue = broadcaster.subscribe()
broadcaster.publish()
broadcaster.publish() # would raise QueueFull if not guarded
assert queue.qsize() == 1
async def test_unsubscribe_stops_delivery():
broadcaster = RoundEventBroadcaster()
queue = broadcaster.subscribe()
broadcaster.unsubscribe(queue)
broadcaster.publish()
assert queue.empty()
async def test_subscribe_rejects_past_the_cap():
broadcaster = RoundEventBroadcaster(max_subscribers=3)
for _ in range(3):
broadcaster.subscribe()
with pytest.raises(RoundEventCapacityError):
broadcaster.subscribe()
async def test_unsubscribe_frees_a_capacity_slot():
broadcaster = RoundEventBroadcaster(max_subscribers=1)
queue = broadcaster.subscribe()
with pytest.raises(RoundEventCapacityError):
broadcaster.subscribe()
broadcaster.unsubscribe(queue)
broadcaster.subscribe() # no longer at capacity
+96
View File
@@ -0,0 +1,96 @@
import pytest
from cryptography.fernet import Fernet
from httpx import ASGITransport, AsyncClient
from app.config import settings
@pytest.fixture
async def client(monkeypatch, tmp_path):
monkeypatch.setattr(settings, "database_url", f"sqlite+aiosqlite:///{tmp_path}/test.db")
monkeypatch.setattr(settings, "jwt_secret", "test-jwt-secret")
monkeypatch.setattr(settings, "xprv_encryption_key", Fernet.generate_key().decode())
monkeypatch.setattr(settings, "master_key_path", str(tmp_path / "master.xprv.enc"))
import app.wallet.hd as hd
hd._account_key = None
hd.generate_master_key()
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.db import base as db_base
import app.db.models # noqa: F401
db_base.engine = create_async_engine(settings.database_url)
db_base.AsyncSessionLocal = async_sessionmaker(db_base.engine, expire_on_commit=False)
from app.db import session as db_session
db_session.AsyncSessionLocal = db_base.AsyncSessionLocal
async with db_base.engine.begin() as conn:
await conn.run_sync(db_base.Base.metadata.create_all)
from fastapi import FastAPI
from app.api.routes.rounds import router as rounds_router
from app.auth.routes import router as auth_router
from app.electrum.listener import ElectrumListener
app = FastAPI()
app.include_router(auth_router)
app.include_router(rounds_router)
app.state.electrum_listener = ElectrumListener(lambda: None, db_base.AsyncSessionLocal)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
yield ac, db_base.AsyncSessionLocal
await db_base.engine.dispose()
async def _register(ac, username):
resp = await ac.post("/auth/register", json={"username": username, "password": "hunter2hunter"})
assert resp.status_code == 201
data = resp.json()
return data["access_token"], data["user_id"] if "user_id" in data else None
async def test_user_played_true_only_for_participants(client):
ac, session_factory = client
from app.db.models import Round, RoundConfig, RoundParticipant, User
player_token, _ = await _register(ac, "player")
spectator_token, _ = await _register(ac, "spectator")
async with session_factory() as session:
from sqlalchemy import select
session.add(RoundConfig(fee_address="pool-fee-address"))
player = (await session.scalars(select(User).where(User.username == "player"))).one()
round_ = Round(status="paying_out", winner_user_id=player.id, winner_amount_sats=123)
session.add(round_)
await session.flush()
session.add(
RoundParticipant(
round_id=round_.id,
user_id=player.id,
bet_amount_sats=1_000_000_000,
bet_txid="a" * 64,
)
)
await session.commit()
resp = await ac.get("/rounds/current", headers={"Authorization": f"Bearer {player_token}"})
assert resp.status_code == 200
assert resp.json()["user_played"] is True
resp = await ac.get("/rounds/current", headers={"Authorization": f"Bearer {spectator_token}"})
assert resp.status_code == 200
assert resp.json()["user_played"] is False
resp = await ac.get("/rounds/current") # no auth at all — logged-out chain-only view
assert resp.status_code == 200
assert resp.json()["user_played"] is False