Restructures app/static/index.html's visual design without touching any JS
logic or element IDs:
- Typography switched to IBM Plex Sans (financial/trustworthy pairing),
Fira Code kept for addresses and numeric mono values.
- Design tokens extended with elevation shadows, an inset-surface color,
and a scaled border-radius system; cards/buttons get subtle depth instead
of flat borders.
- Navigation goes adaptive: a native-app-style fixed bottom tab bar on
mobile (thumb-reachable), promoted back to an inline tab strip once the
viewport is wide enough (>=720px) to fit one comfortably under the header.
- Top bar decluttered: balance shown as a highlighted pill (icon + value),
Guida/Segnala un bug/Esci condensed into icon buttons with tooltips and
aria-labels instead of full-text links.
- Round-status card gets a subtle gradient "hero" treatment to read as the
central live widget of the dashboard.
- Content width now adapts from 480px (mobile) to 620px (>=720px) instead
of staying phone-narrow on desktop; safe-area insets reserved for the
fixed bottom bar and toast stack.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Adds a navbar-balance span next to the username, kept in sync by the
existing refreshMe() calls (login, after a bet, after a withdrawal, manual
refresh) — no new endpoint needed, /users/me already returns balance_sats.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Serves docs/guida-utente.md as plain text at GET /guida (no markdown
rendering, kept simple) and links it from the navbar next to a "Segnala un
bug" button. The bug-report link is a placeholder GitHub issues URL
(REPLACE_ME) until a real repo exists.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
embit's address_to_scriptpubkey only knows Bitcoin's network prefixes, not
PLM's — so a legacy P2PKH address (prefix 55, "P...") silently produces a
None scriptpubkey instead of a clear rejection, and P2SH only works by
coincidence. Until the address decoding is fixed to use PLM's own network
prefixes, surface the current limitation to users in the withdrawal form
and the user guide instead of letting them lose funds to a broken address.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
CLAUDE.md and the user/admin guides only mentioned "a confirmed block" for
the draw, leaving the actual end-to-end timing (why it can take several
minutes after the countdown hits zero) unclear. Spell out the three distinct
confirmations in sequence — last pending bet, draw block, payout tx — and
the resulting best/worst-case wall-clock estimates.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The round timer relied on each client's own wall clock, so two browsers with
skewed local clocks showed different countdowns for the same round; the
server now also returns server_time so the frontend can correct for clock
skew. Also drop out-of-order /rounds/current responses (multiple independent
triggers could resolve late and revert the UI to a stale drawing/result
state) and prune per-round bookkeeping maps on round transitions.
Separately, place_bet only checked status == "open", leaving a window (up to
the scheduler's 5s tick interval) after a round's timer hit zero where a new
bet could still be accepted. place_bet now checks the round's own deadline
directly (round_accepts_bets), acting as an immediate "yellow light" for new
entries while still letting already-broadcast bets confirm before the round
closes.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Session hardening: / and /admin now respond with Cache-Control: no-store, and
both pages re-derive their auth state on pageshow (event.persisted) as a
safety net against bfcache showing a stale logged-in/out view across
back/forward navigation. The user page also syncs logout across tabs via the
storage event, since localStorage is shared but in-memory JS state isn't.
Password recovery: admin gets a "Reset" button per user (POST
/admin/users/{id}/reset-password) that generates and sets a new password,
shown once — passwords are Argon2-hashed and can never be recovered, only
replaced. Users get self-service password change (POST
/users/me/change-password, requires the current password) under a new
Profilo tab, alongside read-only account info (username, address, balance,
join date).
Round display robustness: the user dashboard now refreshes immediately on
tab visibility change (background tabs get their timers throttled hard),
shows an explicit "connessione persa" state after repeated failed polls
instead of silently freezing on stale data, and polls faster both right when
the countdown hits zero and through the gap where the round is past its
deadline but still waiting for in-flight bets to confirm before the server
actually closes it.
RoundConfig gets a paused flag toggled via new POST /admin/pause and
/admin/resume endpoints (audit-logged, surfaced as a "Manutenzione" card in
the admin Parametri view). Pausing only stops the *next* round from opening
once the current one closes — rounds/service.py:open_new_round_if_needed
still lets an in-progress round finish, draw, and pay out its winner
normally. GET /rounds/current exposes lottery_paused so the user page shows
a maintenance banner (even while logged out) instead of silently going idle.
Also replaces the user dashboard's stacked account-bar card + bento-grid
menu with a single sticky navbar (identity row + Deposito/Bet/Prelievo
tabs), and moves the page content into a dedicated .app-shell container so
the navbar itself can span full width.
The user page's login screen was a bare test dashboard with no explanation
of how the lottery works; it now leads with a hero (3-step explainer, trust
pills) shown only while logged out, plus a bento-style nav and a glowing
round card during the draw.
Both the user and admin pages now show the current chain tip height and
lottery status (open / drawing / waiting for next round) via a small status
strip, polled from /rounds/current (extended with chain_tip_height sourced
from ElectrumListener.tip_height).
_close_and_draw set round_.status = "closing" but then immediately
overwrote it in memory with "closed" (no participants) or "drawing"
(with participants) before the first session.commit() — so "closing"
was never actually written to the database, only ever visible in the
ORM object's transient in-memory state. GET /rounds/current (and the
frontend's "in chiusura" label) could never observe it.
Committing right after setting "closing"/closed_at, before querying
participants, makes it a real, briefly-observable state like the
others in the round lifecycle.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
CLAUDE.md's DRAW architecture bullet now explains draw_animation_seconds
and its decoupling from the real block-wait timing. guida-utente.md
gets a new "Estrazione del vincitore" section describing what a player
sees and when. guida-admin.md's Parametri table and hardcoded-defaults
note include the new field.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
When the round leaves "open" (closing/drawing/paying_out), the round
card swaps its timer for a spinning "Estrazione del vincitore in
corso…" state instead — bets are already rejected server-side once the
round isn't open, this just reflects that visually. Once winner_user_id
is set AND at least draw_animation_seconds has elapsed since the round
started closing (client-tracked per round_id), it reveals "🎉 Hai
vinto! +N PLM" (compared against the user's own id from /users/me) or
"Non hai vinto questa volta.", with a success toast on a win. The
result stays on screen through the cooldown gap and only clears once a
genuinely new round opens (tracked via activeResultRoundId), not the
instant the old round has no active status.
Polling is now dynamic (setTimeout-chained, not setInterval): 3s while
the round is closing/drawing/paying_out for a responsive reveal, 15s
while open.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
RoundConfig gains draw_animation_seconds (default 20) — the minimum
time the frontend's "estrazione in corso" animation plays before
revealing a winner. It's purely a UI cue: the real draw still waits for
a confirmed block for its entropy (rounds/scheduler.py), which usually
takes much longer than this value, so it only ever extends the
animation, never truncates the real wait.
GET /rounds/current now also returns draw_animation_seconds,
winner_user_id and winner_amount_sats (all populated once the
scheduler sets them on the round, i.e. from "paying_out" onward) so a
client can determine and reveal the outcome. GET /users/me now returns
the user's own id, needed client-side to compare against winner_user_id.
Admin config CRUD refactored to a shared field tuple (_CONFIG_FIELDS)
instead of repeating the same 7-then-8 field list three times.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Project overview, quick start (local venv and Docker+Caddy), and a
documentation index pointing to CLAUDE.md, flowchart.mmd and docs/ —
none of that existed as an entry point before this.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
guida-admin.md now covers all five dashboard sections instead of just
Parametri/Utenti, plus an explanation of who actually pays an RBF fee
bump (the transaction's own sender/pool, never the fixed recipient
amount) placed right next to the timeout field it governs.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Ran through the init skill's checklist against the current codebase:
test count (49 -> 54), a new "Admin dashboard and test UI" architecture
section (the two static SPAs, their endpoints, and the deliberate
non-linking between them), two new non-obvious domain decisions (admin
privkey export is intentional not a bug; who pays an RBF fee bump), a
pointer to docs/ for the human-facing guides, and updated Known gaps
(deployment gap resolved and removed; admin-token blast radius and the
Docker auto-restart risk called out; user-facing history gap reworded
now that the admin side has one). MVP business parameters reworded to
distinguish what's admin-configurable (bet amount, min amount) from
what's genuinely hardcoded (70/30 split, 1-conf threshold).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
CLAUDE.md and docs/guida-admin.md now describe RoundConfig as the sole
source of truth for business parameters, with no env var counterpart —
defaults live as hardcoded model column defaults, not app/config.py.
guida-admin.md documents the four new dashboard sections (Round,
Transazioni pendenti, Audit log alongside Parametri/Utenti). setup.md
points readers to the admin panel instead of .env for those values.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Replaces the single scrolling page with a sticky top navbar and five
sections: Parametri (all seven RoundConfig fields, now including round
duration/cooldown/min amount/fee rate/RBF timeout alongside fee address
and bet amount), Utenti (unchanged), Round (history: status, winner,
pool/winner/fee amounts, payout txid), Transazioni pendenti (in-flight
bet/payout/withdrawal txs), and Audit log (recent system events with
parsed payload). Everything loads on login; switching a nav tab
refreshes that section's data.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
GET /admin/rounds: recent rounds with status, winner (joined username),
pool/winner/fee amounts, payout txid. GET /admin/pending-transactions:
in-flight bet/payout/withdrawal txs (RBF candidates). GET /admin/audit-log:
recent audit_log entries with parsed payload. All gated by the existing
require_admin dependency, feeding the new dashboard sections.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
RoundConfig gains round_duration_seconds, round_cooldown_seconds,
min_amount_sats, fee_rate_sat_vb and rbf_timeout_seconds (plus a
hardcoded default for the pre-existing bet_amount_sats) as column
defaults on the model itself — get_round_config no longer seeds from
Settings at all. Every call site that read these from settings
(scheduler, bets, withdrawals, rounds service/route, RBF bumper) now
reads the DB-backed RoundConfig instead.
app/config.py now holds only true env-driven infra/secrets (database
URL, Electrum connection, master key, JWT, admin token) — no business
parameter has an env var anymore, matching an explicit decision to drop
the "seed from settings" indirection entirely rather than keep a env
fallback nobody should rely on.
Migration backfills the existing round_config row via server_default
(matching the old settings defaults) then drops the default, so future
rows go through the ORM/model defaults instead of a stale constant.
Tests updated: should_bump's timeout_seconds is now required (no
settings fallback); test_scheduler.py seeds a RoundConfig row directly
instead of monkeypatching settings; test_withdrawals.py and
test_rounds_service.py use local constants mirroring the model
defaults instead of reading them off settings.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
/admin now shows only a token field + "Accedi" button on first load —
config and users are structurally in the page but empty/hidden, no data
requested until the token is verified. On successful login (a GET
/admin/config that doesn't 403) it reveals the dashboard and loads
config + users automatically; no more separate "Carica configurazione"/
"Carica utenti" buttons. Token is kept in sessionStorage (cleared on
tab close) so a reload during the same session skips straight back to
the dashboard. Added a Logout button and Enter-to-submit on the token
field.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Registration now requires the password twice, rejected client-side on
mismatch before hitting the API. The admin page gets a Utenti card:
loads the user list (id, username, address, balance in PLM) and a
per-row "Mostra" button that reveals the private key after an explicit
confirm() — click again to hide it. A persistent warning banner notes
that every reveal is audit-logged.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
GET /admin/users lists id/username/address/balance_sats/created_at.
GET /admin/users/{id}/privkey derives and returns that user's raw WIF
private key, for manual intervention (e.g. sweeping funds back if
something's stuck) — this is already a custodial system, the server
holds the master key everything is derived from, so this doesn't grant
a new capability, just exposes an existing one through the API. Every
access is audit-logged (admin_privkey_accessed).
Also fixes a pre-existing test-isolation bug in test_admin.py's client
fixture: app.db.session.get_session had `from app.db.base import
AsyncSessionLocal`, a one-time reference copy at first import — later
tests reassigning db_base.AsyncSessionLocal never reached it, so any
test mixing direct DB writes with router calls silently read/wrote
against a stale, possibly-disposed engine from whichever test ran
first. Fixed by also rebinding app.db.session.AsyncSessionLocal in the
fixture on every run.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
open_new_round_if_needed now withholds opening the next round until
ROUND_COOLDOWN_SECONDS (default 30) have passed since the previous
round's closed_at, returning None in that window instead of a Round.
Without this, the next round opened within one scheduler tick (~5s) of
the previous payout confirming — not enough time for a player to
notice the round they were in actually resolved.
Callers updated: the scheduler treats None as "nothing to do this
tick", and place_bet raises a "try again shortly" BetError instead of
crashing on a None round.
Not in the original flowchart — a deliberate UX addition on top of it,
documented as such in CLAUDE.md.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Used to generate the color palette/typography/UX guidelines behind the
test and admin UI redesign. Checked in so the plugin is enabled for
anyone else working on this repo with Claude Code, not just this
session.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Four standalone Markdown docs instead of growing CLAUDE.md further:
setup.md (one-time secrets/master-key/migrations), running-the-server.md
(local venv vs Docker+Caddy, dev self-signed vs production domain),
guida-utente.md (dashboard: deposit+QR, bet, withdrawal, round timer/
jackpot) and guida-admin.md (the /admin panel and its API equivalent).
Written in Italian per explicit request, unlike the rest of the
repository's English-only docs.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Records the docker compose commands (master key bootstrap, up/down,
log tailing) and the SITE_ADDRESS dev-vs-production behavior, plus an
explicit warning: app's restart:unless-stopped means a crash mid-round
auto-restarts into the still-open scheduler-resume gap, so this isn't
unattended-safe yet.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Caddy's site address comes from SITE_ADDRESS (defaults to "localhost").
Left at that default, Caddy detects it isn't a public hostname and
issues a self-signed cert from its own internal CA — no domain needed
for local/dev testing. Set to a real domain, it gets a genuine Let's
Encrypt certificate automatically instead.
DB, encrypted master key and logs are bind-mounted from ./data/ on the
host (not opaque Docker-managed volumes), so they survive container
restarts/rebuilds and stay reachable for manual inspection/backup
directly from the repo root. ./data/ is gitignored.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
python:3.12-slim, installs the package (pip install .), runs pending
Alembic migrations before starting uvicorn. Migrations/alembic.ini/
scripts are copied in as-is (not part of the installed package) since
alembic and generate_master_key.py run directly against the source
tree.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
A card above the section menu polls GET /rounds/current every 15s and
ticks a mm:ss countdown to closes_at every second locally, showing
status (aperto/in chiusura/estrazione/pagamento), participant count
and jackpot in PLM. Refreshed immediately after placing a bet, and
timers are cleared on logout.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
GET /rounds/current returns the active round's id/status, opened_at/
closes_at (derived from ROUND_DURATION_SECONDS), participant count and
jackpot (participant_count * bet_amount_sats). No active round still
returns bet_amount_sats so clients can render a fixed-entry hint either
way.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Deposito/Bet/Prelievo are now separate panels behind a top nav instead
of one long scroll of cards, and the Deposito panel renders the
deposit address as a QR code (via GET /qr/{address}) alongside the
existing copy-to-clipboard address box.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
GET /qr/{address} renders the address as a PNG QR code (qrcode[pil]),
gated by a bech32-shaped regex since it's otherwise unauthenticated —
the address itself isn't sensitive, but this keeps it from being used
as an arbitrary text-to-QR service.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
New visual system from the ui-ux-pro-max skill (gold/purple accents,
Fira Sans + Fira Code, light mode, WCAG AA contrast): card layout,
tabbed login/register, loading states on every button, and toast
feedback instead of a raw request/response JSON dump. The dump is gone
from both pages — diagnosing an error now means reading logs/app.log,
not staring at the page.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
All app and uvicorn logging now goes to logs/app.log (rotating,
10MB x5), and a catch-all exception handler logs full tracebacks there
before returning a generic 500 — so an error is traceable to its cause
without depending on how the process was launched. logs/ is gitignored,
like the other runtime artifacts.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Balance, withdrawal amount and bet_amount_sats are entered/displayed in
PLM in both static pages; conversion to sats happens client-side right
before the API call, since the backend contract stays sats-based.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Moves the fee_address/bet_amount_sats config form out of the main test
UI into a dedicated admin.html, served by a GET /admin route
(registered ahead of the StaticFiles mount so it doesn't shadow the
existing GET/PUT /admin/config API). Deliberately not linked from the
test UI in either direction: reachable only by knowing the URL.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Lets an operator load and update fee_address/bet_amount_sats from a
form (using the X-Admin-Token header) instead of curl/Swagger, with
inline status feedback and the same request/response log as the rest
of the page.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Records the MVP build as code-complete and unit-tested, documents the
real install/run/test commands now that the project is scaffolded, and
lists known gaps (scheduler restart resume, payout retry, RBF fallback,
missing history endpoints, deployment, admin auth, rate limiting) to
address before treating this as production-ready.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Single-page vanilla HTML/JS frontend (register/login, balance,
place bet, withdraw) served by FastAPI at the same origin so it can
exercise the live API without CORS setup. Manual-testing aid only,
not part of the MVP spec.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
app/main.py assembles the lifespan-managed background tasks (Electrum
listener, round scheduler, confirmation poller, RBF bumper) and mounts
all routers behind a /health check. generate_master_key.py is the
one-time ops script that creates and Fernet-encrypts the server's
master xprv before first launch.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Bearer-token-gated admin endpoints to read/update the DB-backed
operational config (fee_address, bet_amount_sats) without a redeploy,
plus a lightweight audit log writer for round/payout/config events.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Builds and broadcasts a user->external-address PSBT with change back to
the user's own address, fee deducted from the withdrawn amount, and
registers the confirmation handler that marks the withdrawal confirmed.
Shares the per-user lock with bets so a build never races a spend from
the same UTXO set.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Periodic scheduler (configurable round duration) that closes a round
only once all broadcast bets confirm, waits for the next block after
closing, draws a winner via block-hash-seeded modulo over participants
ordered by broadcast time, triggers the 70/30 payout, and only opens the
next round once that payout confirms. Draw logic is isolated in
draw.py as a deliberately simple, replaceable component.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Places the fixed-cost bet into the current round: builds and broadcasts
the user->pool PSBT with change back to the user's own address, enforces
at most one active bet per user, and registers the confirmation handler
that marks a bet confirmed and adds the participant to the round.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Credits a user's internal balance once a UTXO on their deposit address
reaches 1 confirmation, keeping utxo_events as the source of truth and
cached_balance_sats as a derived read cache.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Shared per-user locking to serialize bet/withdrawal PSBT builds
(tx/locks.py), a confirmation poller for pending outgoing transactions,
and the timeout->fee-bump->rebroadcast loop used by bets, payouts and
withdrawals alike (tx/broadcast.py).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Argon2 password hashing, JWT session issuing/verification
(auth/security.py), register/login routes, the bearer-token
get_current_user dependency, and GET /users/me for address + balance.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Minimal Electrum protocol client (client.py) plus a scripthash
subscription listener (listener.py) that watches user deposit addresses
for confirmed UTXOs, with the address->scripthash conversion helper and
a manual smoke-test script against the dev bootstrap server.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>