13 Commits
Author SHA1 Message Date
davideandClaude Sonnet 5 1941f30b10 Add ops scripts to decrypt/re-encrypt the master xprv, and document them
decrypt_master_key.py: prints the existing master xprv after an explicit
confirmation prompt, for disaster-recovery backups. Falls back to
./data/keys/master.xprv.enc (the docker-compose.yml bind-mount path) when
.env's configured MASTER_KEY_PATH doesn't exist locally.

encrypt_master_key.py: the reverse direction — takes an externally-generated
xprv (e.g. created offline/air-gapped) via a hidden getpass prompt, validates
it parses as a private extended key, and encrypts it with the same Fernet
scheme generate_master_key.py uses. Refuses to overwrite an existing key file
unless --overwrite is passed.

Neither script is reachable via any API endpoint or the admin panel, by
design — this is the one secret the entire custodial wallet derives from.
Documented in docs/setup.md (new "Recuperare o portare una xprv esistente"
section) and CLAUDE.md's Commands block.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 16:20:03 +02:00
davideandClaude Sonnet 5 9e7b726df7 Use the official PLM logo in the navbar and as favicon
Adds app/static/logo.svg — the official Palladium logo (fetched from the
palladium-coin/palladium-web-site repo), reprocessed for crisp display at
small sizes: the white/blue boundary is sharpened (steep contrast curve
instead of the soft anti-aliasing baked into the low-res source) and the
outer circle uses an analytically computed alpha edge instead of a
rasterized ellipse, so it stays perfectly round with no pixel staircase at
any size. Shape and colors are otherwise identical to the source artwork.

Wired up as the navbar brand mark (replacing the plain amber "P" square) in
index.html, and as the favicon for both index.html and admin.html.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 15:39:47 +02:00
davideandClaude Sonnet 5 5f62a8315e Add a "withdraw full balance" checkbox to the withdrawal form
Checking it disables the amount field, autofills it with the current
balance, and keeps it in sync if the balance changes while checked. The
actual withdrawal request uses the raw balance_sats value directly instead
of round-tripping through the PLM input field, avoiding float-rounding
drift when withdrawing the exact full balance.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 14:59:02 +02:00
davideandClaude Sonnet 5 80c413ad3d Show the net prize as the jackpot instead of the gross pool
GET /rounds/current's jackpot_sats was the full pool (participant_count *
bet_amount_sats), which overstates what the winner actually receives once
the 30% commission is taken out at payout time. Apply the same 70% split
rounds/scheduler.py uses so the number shown during the round already
matches the real payout, without surfacing the fee itself in the UI/docs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 14:53:09 +02:00
davideandClaude Sonnet 5 1acb6c3b16 Redesign the user dashboard with a modern fintech-style layout
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>
2026-07-22 14:50:17 +02:00
davideandClaude Sonnet 5 2b645f5e37 Show the user's balance in the navbar
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>
2026-07-22 14:36:30 +02:00
davideandClaude Sonnet 5 c4f6f2eed7 Add a help link and bug-report button to the user navbar
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>
2026-07-22 14:34:03 +02:00
davideandClaude Sonnet 5 67f70465e9 Warn users that withdrawals only support P2WPKH bech32 addresses
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>
2026-07-22 14:29:05 +02:00
davideandClaude Sonnet 5 9fa7eec378 Document the three sequential block confirmations behind the draw/payout timing
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>
2026-07-22 14:14:09 +02:00
davideandClaude Sonnet 5 7dcf6d2756 Sync round countdown across clients and enforce the bet cutoff on deadline, not scheduler tick
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>
2026-07-22 14:07:09 +02:00
davide f27fe6243c Harden session handling, add password reset/change, and firm up round polling
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.
2026-07-22 12:00:09 +02:00
davide 162a63d04a Add a maintenance pause/resume switch and a proper user navbar
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.
2026-07-22 10:36:36 +02:00
davide 78109aa4c4 Add a marketing landing hero and a live chain/round status strip
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).
2026-07-22 10:16:51 +02:00
21 changed files with 1476 additions and 130 deletions

No files matched your search

+11 -1
View File
@@ -26,6 +26,8 @@ alembic upgrade head # apply DB migrations
alembic revision --autogenerate -m "message" # generate a new migration after editing app/db/models.py
PYTHONPATH=. python scripts/generate_master_key.py # one-time: create+encrypt the server's master xprv (requires XPRV_ENCRYPTION_KEY in .env)
PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+print the existing master xprv (asks for confirmation first)
PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: bring your own externally-generated xprv instead of generating one (getpass prompt, --overwrite to replace)
uvicorn app.main:app --reload --port 8123 # run the dev server
@@ -64,6 +66,7 @@ Known risk: `docker-compose.yml` sets `restart: unless-stopped` on `app`, so a c
- **Secrets**: master xprv encrypted at rest with a symmetric scheme (AES-GCM/Fernet); the encryption key itself lives in an env var, never in the DB or in git.
- **Operational config**: every business/round parameter (fee address, bet amount, round duration, round cooldown, draw animation duration, minimum amount, network fee rate, RBF timeout) lives in the `round_config` DB table (single row, `app/rounds/config.py`) and is only editable live via the admin dashboard (`/admin`) or its API — no env var involved at all, no redeploy or restart needed. Defaults for a brand-new instance are hardcoded column defaults on the `RoundConfig` model (`app/db/models.py`), not `app/config.py`. Secrets and infra wiring (master key, JWT secret, Electrum host, admin token, database URL) stay env-var-driven in `.env` since those genuinely need a restart.
- **Round cooldown**: `round_cooldown_seconds` — gap after a round closes before the next one opens, so players have time to see the outcome (default 30s). Not in the original flowchart; added afterwards as an explicit design decision.
- **Maintenance pause**: `RoundConfig.paused` (default `false`), toggled via `POST /admin/pause` / `POST /admin/resume` (a dedicated "Manutenzione" card in `/admin`'s Parametri section, not a plain config field — it's a deliberate operator action, audit-logged as `lottery_paused`/`lottery_resumed`). When set, `rounds/service.py:open_new_round_if_needed` stops opening a *next* round once the current one closes — it never interrupts a round already in progress (that one still closes, draws, and pays out its winner normally). `GET /rounds/current` exposes it as `lottery_paused` so the user-facing page (`/`) shows a maintenance banner.
## PLM network parameters
@@ -96,11 +99,18 @@ 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). Once a round leaves `open` (closing/drawing/paying_out), **no new bets are accepted** for it — `place_bet` checks `status == "open"` 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). 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 "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.
- **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.
**Three separate on-chain confirmations, not one, between the timer hitting zero and the payout landing** — a common point of confusion, worth spelling out explicitly:
1. **Last bet's confirmation** (`scheduler.py`'s `_tick`, the `pending_count` check before `_close_and_draw`) — the round doesn't even flip to `"closing"` until every already-broadcast bet has its 1st confirmation. This can already have happened before the timer expired; it's the earliest of the three and not necessarily tied to the deadline at all.
2. **The draw block** (`_wait_for_next_block`, waits for `tip_height > tip_at_close`, where `tip_at_close` is recorded only once step 1 is done) — by construction this must be a **later, different block** than whichever one confirmed the last bet in step 1.
3. **Payout confirmation** — `_trigger_payout` broadcasts only after step 2's block is known, then registers a `PendingTransaction(kind="payout")` that the same generic `ConfirmationPoller` (`app/tx/confirmation.py`) waits on independently — this needs **yet another, later block** than step 2's, since the payout can't be built before the winner is known.
So worst case (last bet confirms right at the deadline) is ~3 block times end-to-end; best case (all bets already confirmed before the timer hit zero) is ~2 (draw block + payout block). At PLM's 120s block time that's roughly 4–6 minutes worst case, 2–4 minutes best case — independent of `draw_animation_seconds`, which only sets a cosmetic minimum for the frontend animation.
## 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:
+55
View File
@@ -1,4 +1,5 @@
import json
import secrets
from fastapi import APIRouter, Depends, Header, HTTPException, status
from pydantic import BaseModel
@@ -6,6 +7,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.log import write_audit_log
from app.auth.security import hash_password
from app.config import settings
from app.db.models import AuditLog, PendingTransaction, Round, User
from app.db.session import get_session
@@ -29,6 +31,7 @@ _CONFIG_FIELDS = (
"fee_rate_sat_vb",
"rbf_timeout_seconds",
"draw_animation_seconds",
"paused",
)
@@ -41,6 +44,7 @@ class RoundConfigResponse(BaseModel):
fee_rate_sat_vb: int
rbf_timeout_seconds: int
draw_animation_seconds: int
paused: bool
class RoundConfigUpdate(BaseModel):
@@ -52,6 +56,7 @@ class RoundConfigUpdate(BaseModel):
fee_rate_sat_vb: int | None = None
rbf_timeout_seconds: int | None = None
draw_animation_seconds: int | None = None
paused: bool | None = None
def _config_response(config) -> RoundConfigResponse:
@@ -78,6 +83,27 @@ async def update_config(
return _config_response(config)
@router.post("/pause", response_model=RoundConfigResponse, dependencies=[Depends(require_admin)])
async def pause_lottery(session: AsyncSession = Depends(get_session)) -> RoundConfigResponse:
"""Maintenance switch: the round in progress (if any) still closes, draws,
and pays out its winner normally — only opening the *next* round is
suppressed until /admin/resume is called (rounds/service.py)."""
config = await get_round_config(session)
config.paused = True
await write_audit_log(session, "lottery_paused", {})
await session.commit()
return _config_response(config)
@router.post("/resume", response_model=RoundConfigResponse, dependencies=[Depends(require_admin)])
async def resume_lottery(session: AsyncSession = Depends(get_session)) -> RoundConfigResponse:
config = await get_round_config(session)
config.paused = False
await write_audit_log(session, "lottery_resumed", {})
await session.commit()
return _config_response(config)
class AdminUserResponse(BaseModel):
id: int
username: str
@@ -123,6 +149,35 @@ async def user_privkey(user_id: int, session: AsyncSession = Depends(get_session
return AdminPrivkeyResponse(address=user.address, wif=wif)
class AdminPasswordResetResponse(BaseModel):
username: str
new_password: str
@router.post(
"/users/{user_id}/reset-password",
response_model=AdminPasswordResetResponse,
dependencies=[Depends(require_admin)],
)
async def reset_user_password(
user_id: int, session: AsyncSession = Depends(get_session)
) -> AdminPasswordResetResponse:
"""Admin-only password reset for a user who's locked out: passwords are
Argon2-hashed (one-way), so an existing password can never be recovered or
displayed — this generates and sets a brand new one instead, shown once so
the admin can relay it to the user. There is no user-facing self-service
reset; only an admin (via /admin, token-gated) can trigger this."""
user = await session.get(User, user_id)
if user is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "user not found")
new_password = secrets.token_urlsafe(12)
user.password_hash = hash_password(new_password)
await write_audit_log(session, "admin_password_reset", {"user_id": user_id}, user_id=user_id)
await session.commit()
return AdminPasswordResetResponse(username=user.username, new_password=new_password)
class AdminRoundResponse(BaseModel):
id: int
status: str
+23 -5
View File
@@ -1,6 +1,6 @@
from datetime import timedelta, timezone
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -14,6 +14,7 @@ router = APIRouter(prefix="/rounds", tags=["rounds"])
class CurrentRoundResponse(BaseModel):
server_time: str
round_id: int | None = None
status: str | None = None
opened_at: str | None = None
@@ -24,16 +25,24 @@ class CurrentRoundResponse(BaseModel):
draw_animation_seconds: int
winner_user_id: int | None = None
winner_amount_sats: int | None = None
chain_tip_height: int | None = None
lottery_paused: bool = False
@router.get("/current", response_model=CurrentRoundResponse)
async def current_round(session: AsyncSession = Depends(get_session)) -> CurrentRoundResponse:
async def current_round(request: Request, session: AsyncSession = Depends(get_session)) -> CurrentRoundResponse:
config = await get_round_config(session)
round_ = await get_active_round(session)
listener = request.app.state.electrum_listener
chain_tip_height = listener.tip_height or None
if round_ is None:
await session.commit()
return CurrentRoundResponse(
bet_amount_sats=config.bet_amount_sats, draw_animation_seconds=config.draw_animation_seconds
server_time=datetime.now(timezone.utc).isoformat(),
bet_amount_sats=config.bet_amount_sats,
draw_animation_seconds=config.draw_animation_seconds,
chain_tip_height=chain_tip_height,
lottery_paused=config.paused,
)
participant_count = await session.scalar(
@@ -43,15 +52,24 @@ async def current_round(session: AsyncSession = Depends(get_session)) -> Current
closes_at = opened_at + timedelta(seconds=config.round_duration_seconds)
await session.commit()
# Shown to players as "jackpot": the winner's 70% share of the pool (same
# split rounds/scheduler.py applies at payout time), not the full pool —
# what's displayed should match what the winner actually receives.
pool_amount_sats = participant_count * config.bet_amount_sats
jackpot_sats = pool_amount_sats * 70 // 100
return CurrentRoundResponse(
server_time=datetime.now(timezone.utc).isoformat(),
round_id=round_.id,
status=round_.status,
opened_at=opened_at.isoformat(),
closes_at=closes_at.isoformat(),
participant_count=participant_count,
bet_amount_sats=config.bet_amount_sats,
jackpot_sats=participant_count * config.bet_amount_sats,
jackpot_sats=jackpot_sats,
draw_animation_seconds=config.draw_animation_seconds,
winner_user_id=round_.winner_user_id,
winner_amount_sats=round_.winner_amount_sats,
chain_tip_height=chain_tip_height,
lottery_paused=config.paused,
)
+35 -2
View File
@@ -1,21 +1,54 @@
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
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.session import get_session
router = APIRouter(prefix="/users", tags=["users"])
_MIN_PASSWORD_LENGTH = 8
class MeResponse(BaseModel):
id: int
username: str
address: str
balance_sats: int
created_at: str
@router.get("/me", response_model=MeResponse)
async def me(user: User = Depends(get_current_user)) -> MeResponse:
return MeResponse(
id=user.id, username=user.username, address=user.address, balance_sats=user.cached_balance_sats
id=user.id,
username=user.username,
address=user.address,
balance_sats=user.cached_balance_sats,
created_at=user.created_at.isoformat(),
)
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str
@router.post("/me/change-password", status_code=status.HTTP_204_NO_CONTENT)
async def change_password(
body: ChangePasswordRequest,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
) -> None:
"""Self-service password change — requires the current password, unlike the
admin-only /admin/users/{id}/reset-password (which is for a user who's
actually locked out and can't provide it)."""
if not verify_password(body.current_password, user.password_hash):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "current password is incorrect")
if len(body.new_password) < _MIN_PASSWORD_LENGTH:
raise HTTPException(status.HTTP_400_BAD_REQUEST, f"new password must be at least {_MIN_PASSWORD_LENGTH} characters")
user.password_hash = hash_password(body.new_password)
await session.commit()
+4 -3
View File
@@ -8,7 +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.service import open_new_round_if_needed
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
from app.wallet.psbt_builder import BuiltTransaction, InsufficientFundsError, Utxo, build_signed_transaction
@@ -22,7 +22,9 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
round_ = await open_new_round_if_needed(session)
if round_ is None:
raise BetError("no round open right now, please try again shortly")
if round_.status != "open":
config = await get_round_config(session)
if not round_accepts_bets(round_, config.round_duration_seconds):
raise BetError("the current round is closing, please try again shortly")
already_playing = await session.scalar(
@@ -33,7 +35,6 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
if already_playing is not None:
raise BetError("you already have an active bet in the current round")
config = await get_round_config(session)
bet_amount = config.bet_amount_sats
unspent = (
+4
View File
@@ -95,6 +95,10 @@ class RoundConfig(Base):
min_amount_sats: Mapped[int] = mapped_column(BigInteger, default=100_000_000)
fee_rate_sat_vb: Mapped[int] = mapped_column(default=1)
rbf_timeout_seconds: Mapped[int] = mapped_column(default=900)
# Maintenance switch: when true, the round currently in progress still runs to
# completion (closes, draws, pays out the winner) but no new round is opened
# afterwards — see rounds/service.py:open_new_round_if_needed.
paused: Mapped[bool] = mapped_column(default=False)
updated_at: Mapped[datetime] = mapped_column(default=utcnow, onupdate=utcnow)
+17 -1
View File
@@ -82,9 +82,25 @@ async def health() -> dict[str, str]:
return {"status": "ok"}
_NO_STORE_HEADERS = {"Cache-Control": "no-store"}
@app.get("/", include_in_schema=False)
async def index_page() -> FileResponse:
return FileResponse("app/static/index.html", headers=_NO_STORE_HEADERS)
@app.get("/admin", include_in_schema=False)
async def admin_panel() -> FileResponse:
return FileResponse("app/static/admin.html")
return FileResponse("app/static/admin.html", headers=_NO_STORE_HEADERS)
@app.get("/guida", include_in_schema=False)
async def user_guide() -> FileResponse:
"""Serves docs/guida-utente.md as plain text so it opens inline in the
browser (no markdown rendering — keeps this simple), linked from the
navbar's help button in app/static/index.html."""
return FileResponse("docs/guida-utente.md", media_type="text/plain; charset=utf-8")
app.mount("/", StaticFiles(directory="app/static", html=True), name="static")
+26 -6
View File
@@ -16,22 +16,42 @@ async def get_active_round(session: AsyncSession) -> Round | None:
return await session.scalar(select(Round).where(Round.status.in_(_ACTIVE_STATUSES)).order_by(Round.id.desc()))
def round_accepts_bets(round_: Round, round_duration_seconds: int) -> bool:
"""The authoritative "yellow light" check: once a round's timer has expired,
no new bet may be accepted, even though its DB status is still "open" (the
scheduler only flips it to "closing" on its next tick, up to
_TICK_INTERVAL_SECONDS later — see rounds/scheduler.py). Bets already placed
before the deadline are unaffected: the round still waits for them to confirm
before actually closing."""
if round_.status != "open":
return False
opened_at = round_.opened_at.replace(tzinfo=timezone.utc)
return datetime.now(timezone.utc) < opened_at + timedelta(seconds=round_duration_seconds)
async def open_new_round_if_needed(session: AsyncSession) -> Round | None:
"""Returns the active round if one exists (whatever its status). Otherwise
opens a fresh one, unless the last closed round's cooldown (ROUND_COOLDOWN_SECONDS)
hasn't elapsed yet — in which case returns None. Callers that need to attach a
bet must additionally check the returned round's status == "open" — a round in
closing/drawing/paying_out isn't accepting new bets, but a new round can't open
until it's done."""
hasn't elapsed yet, or the lottery is paused for maintenance — in either case
returns None. Callers that need to attach a bet must additionally check the
returned round's status == "open" — a round in closing/drawing/paying_out
isn't accepting new bets, but a new round can't open until it's done.
Pausing never touches a round already in progress: it only suppresses opening
the *next* one, so the current round still closes, draws, and pays out the
winner normally (see admin.py's /admin/pause and /admin/resume)."""
active = await get_active_round(session)
if active is not None:
return active
config = await get_round_config(session)
if config.paused:
return None
last_closed = await session.scalar(select(Round).where(Round.status == "closed").order_by(Round.id.desc()))
if last_closed is not None and last_closed.closed_at is not None:
closed_at = last_closed.closed_at.replace(tzinfo=timezone.utc)
cooldown_seconds = (await get_round_config(session)).round_cooldown_seconds
if datetime.now(timezone.utc) < closed_at + timedelta(seconds=cooldown_seconds):
if datetime.now(timezone.utc) < closed_at + timedelta(seconds=config.round_cooldown_seconds):
return None
round_ = Round(status="open")
+176 -7
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PLM Lottery — Admin</title>
<link rel="icon" type="image/svg+xml" href="/logo.svg">
<style>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@500;600&family=Fira+Sans:wght@400;500;600;700&display=swap');
@@ -57,6 +58,32 @@
.navbar .nav-tab:hover { color: var(--color-foreground); }
.navbar .spacer { flex: 1; }
.chain-status-pill { display: inline-flex; align-items: center; gap: 7px; font-weight: 600; font-size: 0.82rem; white-space: nowrap; }
.status-dot {
width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0;
background: var(--color-muted-foreground);
}
.status-dot.status-open {
background: var(--color-success);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-success) 18%, transparent);
}
.status-dot.status-drawing {
background: var(--color-primary);
animation: status-dot-pulse 1400ms ease-in-out infinite;
}
.status-dot.status-waiting { background: var(--color-muted-foreground); }
@keyframes status-dot-pulse {
0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 45%, transparent); }
50% { box-shadow: 0 0 0 5px transparent; }
}
.chain-block { color: var(--color-muted-foreground); font-size: 0.82rem; white-space: nowrap; }
.row-between { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
#maintenance-btn.btn-stop {
background: var(--color-destructive-bg); color: var(--color-destructive); border-color: var(--color-destructive);
}
.status-dot.status-paused { background: var(--color-destructive); }
main { max-width: 960px; margin: 0 auto; padding: 24px 20px 80px; }
.view { display: none; }
@@ -187,7 +214,12 @@
<span class="nav-tab" id="nav-pending" onclick="switchView('pending')">Transazioni pendenti</span>
<span class="nav-tab" id="nav-audit" onclick="switchView('audit')">Audit log</span>
<span class="spacer"></span>
<button class="secondary" style="margin:8px 0" onclick="adminLogout()">Esci</button>
<span class="chain-status-pill">
<span class="status-dot" id="chain-status-dot"></span>
<span id="chain-status-label">Connessione…</span>
</span>
<span class="chain-block mono" id="chain-block">Blocco —</span>
<button class="secondary" style="margin:8px 0 8px 14px" onclick="adminLogout()">Esci</button>
</nav>
<main>
@@ -196,6 +228,21 @@
<h2 class="section-title">Parametri</h2>
<p class="hint">Configurazione operativa, salvata nel database — modificabile in qualsiasi momento senza riavviare il server.</p>
<div class="card" id="maintenance-card">
<h2>Manutenzione</h2>
<p class="hint" id="maintenance-hint">
Interrompe l'apertura di nuovi round dopo quello in corso, senza troncare il round attuale — chiusura,
estrazione e pagamento del vincitore avvengono normalmente. Gli utenti vedono un avviso di manutenzione.
</p>
<div class="row-between">
<span class="chain-status-pill">
<span class="status-dot" id="maintenance-dot"></span>
<span id="maintenance-status-label">—</span>
</span>
<button id="maintenance-btn" class="secondary" style="width:auto;margin-top:0" onclick="toggleMaintenance()">…</button>
</div>
</div>
<div class="card">
<div class="grid-2">
<div>
@@ -225,17 +272,17 @@
<div class="view" id="view-utenti">
<h2 class="section-title">Utenti</h2>
<p class="hint">Elenco utenti registrati, con saldo interno e accesso alla chiave privata per interventi manuali (es. restituire fondi bloccati).</p>
<p class="hint">Elenco utenti registrati, con saldo interno, accesso alla chiave privata per interventi manuali (es. restituire fondi bloccati) e reset password per chi resta bloccato fuori dall'account.</p>
<div class="warning-banner">
⚠ La chiave privata dà accesso completo ai fondi dell'utente. Ogni volta che la visualizzi viene registrata nell'audit log del server. Non condividerla, non salvarla altrove.
⚠ La chiave privata dà accesso completo ai fondi dell'utente: ogni visualizzazione viene registrata nell'audit log, non condividerla né salvarla altrove. La password esistente di un utente non è mai recuperabile (è salvata solo come hash Argon2) — "Reset" ne genera una nuova al posto della vecchia, anche questo audit-loggato.
</div>
<div class="card">
<div class="table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Username</th><th>Indirizzo</th><th>Saldo (PLM)</th><th>Registrato</th><th>Chiave</th></tr>
<tr><th>ID</th><th>Username</th><th>Indirizzo</th><th>Saldo (PLM)</th><th>Registrato</th><th>Chiave</th><th>Password</th></tr>
</thead>
<tbody id="users-tbody"></tbody>
</table>
@@ -342,6 +389,42 @@ function fmtDate(iso) {
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) {
@@ -356,6 +439,7 @@ function switchView(name) {
function showDashboard() {
document.getElementById('login-section').classList.add('hidden');
document.getElementById('dashboard-section').classList.remove('hidden');
startChainStatusPolling();
}
async function loadDashboard() {
@@ -379,6 +463,7 @@ async function adminLogin() {
}
function adminLogout() {
stopChainStatusPolling();
sessionStorage.removeItem('plm_admin_token');
adminToken = null;
document.getElementById('admin-token').value = '';
@@ -397,11 +482,53 @@ async function adminLoadConfig() {
document.getElementById('admin-min-amount').value = data.min_amount_sats / SATS_PER_PLM;
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;
@@ -442,8 +569,12 @@ async function loadUsers() {
<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="6" class="hint">Nessun utente registrato.</td></tr>';
`).join('') || '<tr><td colspan="7" class="hint">Nessun utente registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento utenti: ' + e.message, 'error');
}
@@ -472,6 +603,26 @@ async function revealPrivkey(userId, button) {
});
}
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');
@@ -536,11 +687,29 @@ document.getElementById('admin-token').addEventListener('keydown', (e) => {
if (e.key === 'Enter') adminLogin();
});
if (adminToken) {
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(() => { sessionStorage.removeItem('plm_admin_token'); adminToken = null; });
.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>
</body>
+611 -87
View File
@@ -3,55 +3,71 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PLM Lottery — Test</title>
<title>PLM Lottery</title>
<link rel="icon" type="image/svg+xml" href="/logo.svg">
<style>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@500;600&family=Fira+Sans:wght@400;500;600;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@500;600&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap');
:root {
--color-background: #F8FAFC;
--color-surface: #FFFFFF;
--color-surface-inset: #F1F5F9;
--color-foreground: #0F172A;
--color-muted-foreground: #64748B;
--color-border: #E2E8F0;
--color-primary: #F59E0B;
--color-on-primary: #0F172A;
--color-secondary: #FBBF24;
--color-accent: #7C3AED;
--color-destructive: #DC2626;
--color-destructive-bg: #FEF2F2;
--color-success: #16A34A;
--color-success-bg: #F0FDF4;
--color-ring: #F59E0B;
--radius: 12px;
--radius-sm: 8px;
--radius: 14px;
--radius-lg: 20px;
--shadow-sm: 0 1px 2px rgba(15, 23, 42, 0.05);
--shadow-md: 0 8px 24px -8px rgba(15, 23, 42, 0.14);
--content-width: 480px;
--nav-bottom-height: 68px;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
font-family: 'Fira Sans', system-ui, sans-serif;
font-family: 'IBM Plex Sans', system-ui, sans-serif;
background: var(--color-background);
color: var(--color-foreground);
max-width: 480px;
margin: 0 auto;
padding: 32px 20px 80px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
.mono { font-family: 'Fira Code', monospace; }
.app-shell { max-width: var(--content-width); margin: 0 auto; padding: 20px 20px 32px; }
header { margin-bottom: 24px; }
header h1 { font-size: 1.375rem; font-weight: 700; margin: 0; letter-spacing: -0.01em; }
header p { color: var(--color-muted-foreground); font-size: 0.9rem; margin: 4px 0 0; }
.mono { font-family: 'Fira Code', ui-monospace, monospace; }
h1, h2, h3 { font-family: inherit; letter-spacing: -0.01em; }
.section-label {
font-size: 0.72rem; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase;
color: var(--color-muted-foreground); margin: 0 2px 10px;
}
.card {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
box-shadow: var(--shadow-sm);
padding: 20px;
margin-bottom: 16px;
}
.card h2 { font-size: 1rem; font-weight: 600; margin: 0 0 4px; }
.card .hint { color: var(--color-muted-foreground); font-size: 0.85rem; margin: 0 0 14px; }
.card .hint { color: var(--color-muted-foreground); font-size: 0.85rem; margin: 0 0 14px; line-height: 1.45; }
.card .hint:last-child { margin-bottom: 0; }
.tabs { display: flex; gap: 4px; margin-bottom: 16px; border-bottom: 1px solid var(--color-border); }
.tab {
@@ -63,79 +79,150 @@
.tab-panel { display: none; }
.tab-panel.active { display: block; }
label { display: block; font-size: 0.85rem; font-weight: 500; color: var(--color-muted-foreground); margin-top: 12px; margin-bottom: 6px; }
label { display: block; font-size: 0.85rem; font-weight: 500; color: var(--color-muted-foreground); margin-top: 14px; margin-bottom: 6px; }
label:first-child { margin-top: 0; }
input {
width: 100%; padding: 10px 12px; font-size: 0.95rem; font-family: inherit;
border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-surface);
width: 100%; min-height: 44px; padding: 10px 12px; font-size: 0.95rem; font-family: inherit;
border: 1px solid var(--color-border); border-radius: var(--radius-sm); background: var(--color-surface);
color: var(--color-foreground); transition: border-color 150ms, box-shadow 150ms;
}
input:focus {
outline: none; border-color: var(--color-ring);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-ring) 25%, transparent);
}
input:disabled { background: var(--color-surface-inset); color: var(--color-muted-foreground); }
button {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
min-height: 44px; padding: 0 18px; margin-top: 16px; width: 100%;
font-family: inherit; font-size: 0.95rem; font-weight: 600;
background: var(--color-primary); color: var(--color-on-primary);
border: none; border-radius: 8px; cursor: pointer;
transition: filter 150ms, transform 150ms;
border: none; border-radius: var(--radius-sm); cursor: pointer;
box-shadow: var(--shadow-sm);
transition: filter 150ms, transform 150ms, box-shadow 150ms;
}
button:hover { filter: brightness(0.94); }
button:hover { filter: brightness(0.96); box-shadow: var(--shadow-md); }
button:active { transform: scale(0.98); }
button:disabled { opacity: 0.6; cursor: default; }
button:disabled { opacity: 0.6; cursor: default; box-shadow: none; }
button:focus-visible { outline: 2px solid var(--color-ring); outline-offset: 2px; }
button.secondary {
width: auto; margin-top: 0; padding: 0 12px; min-height: 36px;
background: var(--color-background); color: var(--color-foreground);
border: 1px solid var(--color-border);
width: auto; margin-top: 0; padding: 0 12px; min-height: 40px;
background: var(--color-surface-inset); color: var(--color-foreground);
border: 1px solid var(--color-border); box-shadow: none;
}
button.secondary:hover { filter: none; background: var(--color-border); box-shadow: none; }
button.link {
width: auto; margin-top: 0; padding: 0; min-height: auto;
button.link, a.link {
width: auto; min-height: 44px; margin-top: 0; padding: 0 2px;
display: inline-flex; align-items: center;
background: none; color: var(--color-muted-foreground); font-weight: 500;
font-size: 0.85rem; text-decoration: underline;
font-size: 0.82rem; box-shadow: none; text-decoration: none;
}
button.link:hover { filter: none; color: var(--color-foreground); }
.account-bar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; }
.account-bar .name { font-weight: 600; }
button.link:hover, a.link:hover { filter: none; color: var(--color-foreground); box-shadow: none; }
.row-between { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.address-box {
display: flex; align-items: center; justify-content: space-between; gap: 8px;
background: var(--color-background); border: 1px solid var(--color-border);
border-radius: 8px; padding: 10px 12px; font-size: 0.85rem; word-break: break-all;
.checkbox-row {
display: flex; align-items: center; gap: 8px;
font-size: 0.85rem; font-weight: 500; color: var(--color-foreground);
margin-top: 14px; cursor: pointer;
}
.checkbox-row input[type="checkbox"] {
width: 18px; height: 18px; min-height: auto; flex-shrink: 0; accent-color: var(--color-primary); cursor: pointer;
}
.balance-value { font-size: 2rem; font-weight: 700; }
/* --- app navbar: brand/balance row (sticky top) + section nav (bottom tab bar on
mobile, promoted back to an inline tab strip once there's room — see the
min-width breakpoint below), shown only when logged in --- */
.app-navbar-top {
position: sticky; top: 0; z-index: 20;
background: color-mix(in srgb, var(--color-surface) 90%, transparent);
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
border-bottom: 1px solid var(--color-border);
}
.app-navbar-top-inner {
max-width: var(--content-width); margin: 0 auto; padding: 12px 20px;
display: flex; align-items: center; justify-content: space-between; gap: 12px;
}
.app-navbar-top .brand { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 1rem; letter-spacing: -0.01em; }
.app-navbar-top .brand-mark { width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0; display: block; }
.app-navbar-account { display: flex; align-items: center; gap: 6px; }
.app-navbar-account .navbar-username { display: none; font-weight: 600; font-size: 0.85rem; margin-right: 2px; }
@media (min-width: 420px) { .app-navbar-account .navbar-username { display: inline; } }
.app-navbar-account .navbar-balance {
display: inline-flex; align-items: center; gap: 5px;
font-weight: 700; font-size: 0.85rem; white-space: nowrap;
background: color-mix(in srgb, var(--color-primary) 14%, transparent);
border: 1px solid color-mix(in srgb, var(--color-primary) 30%, transparent);
color: color-mix(in srgb, var(--color-primary) 70%, var(--color-foreground));
padding: 6px 10px; border-radius: 999px;
}
.app-navbar-account .icon-link {
width: 36px; height: 36px; min-height: 36px; padding: 0; margin: 0; border-radius: 999px;
justify-content: center;
}
.app-navbar-account .icon-link:hover { background: var(--color-surface-inset); }
.app-navbar-account .icon-link .icon { width: 18px; height: 18px; }
/* Bottom tab bar on narrow (mobile) viewports — thumb-reachable, app-like. */
.app-navbar-tabs {
position: fixed; left: 0; right: 0; bottom: 0; z-index: 20;
max-width: var(--content-width); margin: 0 auto;
background: color-mix(in srgb, var(--color-surface) 94%, transparent);
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
border-top: 1px solid var(--color-border);
box-shadow: 0 -8px 24px -12px rgba(15, 23, 42, 0.18);
display: flex; padding: 4px 8px calc(4px + env(safe-area-inset-bottom, 0px));
}
.app-navbar-tabs button.navbar-tab {
flex: 1; width: auto; min-height: 56px; margin-top: 0; padding: 8px 4px;
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
font-size: 0.68rem; font-weight: 600; font-family: inherit; cursor: pointer;
background: none; color: var(--color-muted-foreground); box-shadow: none;
border: none; border-radius: var(--radius-sm);
transition: color 150ms, background 150ms;
}
.app-navbar-tabs button.navbar-tab .icon { width: 20px; height: 20px; }
.app-navbar-tabs button.navbar-tab.active { color: var(--color-primary); }
.app-navbar-tabs button.navbar-tab.active .icon { color: var(--color-primary); }
.app-navbar-tabs button.navbar-tab:hover { filter: none; color: var(--color-foreground); background: var(--color-surface-inset); }
.app-navbar-tabs button.navbar-tab.active:hover { color: var(--color-primary); background: none; }
/* Reserve room so fixed content never sits under the bottom bar or the
iOS/Android home-indicator safe area. */
.app-shell { padding-bottom: calc(var(--nav-bottom-height) + env(safe-area-inset-bottom, 0px) + 20px); }
@media (min-width: 720px) {
:root { --content-width: 620px; }
/* Promote the bottom tab bar back to an ordinary inline strip once there's
enough width for it to sit comfortably under the top bar instead of
floating over thumb-reach real estate. */
.app-navbar-tabs {
position: static; box-shadow: none; border-top: none;
border-bottom: 1px solid var(--color-border);
padding: 4px 12px; gap: 4px;
}
.app-navbar-tabs button.navbar-tab { flex-direction: row; min-height: 44px; font-size: 0.85rem; }
.app-shell { padding-bottom: 40px; }
}
.address-box {
display: flex; align-items: center; justify-content: space-between; gap: 8px;
background: var(--color-surface-inset); border: 1px solid var(--color-border);
border-radius: var(--radius-sm); padding: 10px 12px; font-size: 0.85rem; word-break: break-all;
}
.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; }
.icon { width: 16px; height: 16px; flex-shrink: 0; }
nav.menu { display: flex; gap: 4px; margin-bottom: 16px; }
nav.menu button.nav-item {
flex: 1; width: auto; margin-top: 0; min-height: 56px; padding: 8px 4px;
flex-direction: column; gap: 4px; font-size: 0.8rem; font-weight: 600;
background: var(--color-surface); color: var(--color-muted-foreground);
border: 1px solid var(--color-border); border-radius: 10px;
}
nav.menu button.nav-item .icon { width: 20px; height: 20px; }
nav.menu button.nav-item.active {
background: var(--color-primary); color: var(--color-on-primary); border-color: var(--color-primary);
}
nav.menu button.nav-item:hover { filter: none; border-color: var(--color-ring); }
nav.menu button.nav-item.active:hover { filter: brightness(0.94); }
.dash-panel { display: none; }
.dash-panel.active { display: block; }
.qr-box { display: flex; justify-content: center; padding: 16px; background: #fff; border: 1px solid var(--color-border); border-radius: 10px; margin-top: 14px; }
.qr-box { display: flex; justify-content: center; padding: 16px; background: #fff; border: 1px solid var(--color-border); border-radius: var(--radius-sm); margin-top: 14px; }
.qr-box img { width: 200px; height: 200px; image-rendering: pixelated; }
.hidden { display: none !important; }
@@ -154,12 +241,14 @@
.draw-result.lose { color: var(--color-muted-foreground); }
#toast-container {
position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
position: fixed; left: 50%; transform: translateX(-50%);
bottom: calc(var(--nav-bottom-height) + env(safe-area-inset-bottom, 0px) + 12px);
display: flex; flex-direction: column; gap: 8px; z-index: 100; width: calc(100% - 40px); max-width: 440px;
}
@media (min-width: 720px) { #toast-container { bottom: 20px; } }
.toast {
display: flex; align-items: flex-start; gap: 8px;
padding: 12px 14px; border-radius: 8px; font-size: 0.85rem; font-weight: 500;
padding: 12px 14px; border-radius: var(--radius-sm); font-size: 0.85rem; font-weight: 500;
box-shadow: 0 4px 12px rgba(15, 23, 42, 0.12);
animation: toast-in 200ms ease-out;
}
@@ -167,6 +256,123 @@
.toast.error { background: var(--color-destructive-bg); color: var(--color-destructive); }
@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
/* --- landing hero (shown only when logged out) --- */
body {
position: relative;
isolation: isolate;
}
body::before {
content: '';
position: fixed;
inset: 0;
z-index: -1;
background:
radial-gradient(600px circle at 20% -10%, color-mix(in srgb, var(--color-primary) 16%, transparent), transparent 60%),
radial-gradient(500px circle at 90% 10%, color-mix(in srgb, var(--color-accent) 12%, transparent), transparent 60%);
}
.hero { text-align: center; padding: 8px 0 28px; }
.hero .eyebrow {
display: inline-flex; align-items: center; gap: 6px;
font-size: 0.75rem; font-weight: 600; letter-spacing: 0.02em;
color: var(--color-primary); background: color-mix(in srgb, var(--color-primary) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--color-primary) 30%, transparent);
padding: 4px 10px; border-radius: 999px; margin-bottom: 14px;
}
.hero h1 {
font-size: 1.85rem; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 8px;
background: linear-gradient(135deg, var(--color-foreground), var(--color-accent) 120%);
-webkit-background-clip: text; background-clip: text; color: transparent;
}
.hero p.lead { color: var(--color-muted-foreground); font-size: 0.95rem; margin: 0 auto; max-width: 360px; }
.hero-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 22px 0; }
.hero-step {
background: var(--color-surface); border: 1px solid var(--color-border); border-radius: var(--radius);
box-shadow: var(--shadow-sm);
padding: 14px 8px; transition: transform 150ms, border-color 150ms, box-shadow 150ms;
}
.hero-step:hover { transform: translateY(-2px); border-color: var(--color-ring); box-shadow: var(--shadow-md); }
.hero-step .step-icon {
width: 32px; height: 32px; margin: 0 auto 8px; border-radius: 999px;
background: color-mix(in srgb, var(--color-primary) 14%, transparent); color: var(--color-primary);
display: flex; align-items: center; justify-content: center;
}
.hero-step .step-icon .icon { width: 16px; height: 16px; }
.hero-step .step-title { font-size: 0.8rem; font-weight: 600; margin-bottom: 2px; }
.hero-step .step-hint { font-size: 0.72rem; color: var(--color-muted-foreground); line-height: 1.35; }
.trust-row { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-bottom: 24px; }
.trust-pill {
font-size: 0.72rem; font-weight: 500; color: var(--color-muted-foreground);
background: var(--color-surface); border: 1px solid var(--color-border);
padding: 5px 10px; border-radius: 999px; display: inline-flex; align-items: center; gap: 5px;
}
.trust-pill .icon { width: 13px; height: 13px; color: var(--color-success); flex-shrink: 0; }
/* --- round status: a "hero" ticket-style card, always visible above the panels --- */
.card.round-card {
background:
radial-gradient(320px circle at 100% 0%, color-mix(in srgb, var(--color-accent) 10%, transparent), transparent 70%),
var(--color-surface);
border-color: color-mix(in srgb, var(--color-primary) 25%, var(--color-border));
}
.round-card .hint { margin: 0; }
/* --- glowing card while a round is drawing --- */
.card.drawing-glow {
border-color: color-mix(in srgb, var(--color-primary) 55%, var(--color-border));
box-shadow: 0 0 0 1px color-mix(in srgb, var(--color-primary) 25%, transparent),
0 0 24px color-mix(in srgb, var(--color-primary) 22%, transparent);
animation: glow-pulse 2200ms ease-in-out infinite;
}
@keyframes glow-pulse {
0%, 100% { box-shadow: 0 0 0 1px color-mix(in srgb, var(--color-primary) 25%, transparent), 0 0 16px color-mix(in srgb, var(--color-primary) 16%, transparent); }
50% { box-shadow: 0 0 0 1px color-mix(in srgb, var(--color-primary) 45%, transparent), 0 0 28px color-mix(in srgb, var(--color-primary) 30%, transparent); }
}
.jackpot-bump { animation: jackpot-bump 420ms ease-out; }
@keyframes jackpot-bump {
0% { transform: scale(1); }
30% { transform: scale(1.12); color: var(--color-primary); }
100% { transform: scale(1); }
}
/* --- network / lottery status strip, shown on every screen --- */
.chain-bar {
display: flex; align-items: center; justify-content: space-between; gap: 10px;
font-size: 0.78rem; padding: 12px 2px 16px; margin-bottom: 4px;
border-bottom: 1px solid var(--color-border);
}
.chain-status-pill { display: inline-flex; align-items: center; gap: 7px; font-weight: 600; color: var(--color-foreground); }
.status-dot {
width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0;
background: var(--color-muted-foreground);
}
.status-dot.status-open {
background: var(--color-success);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-success) 18%, transparent);
}
.status-dot.status-drawing {
background: var(--color-primary);
animation: status-dot-pulse 1400ms ease-in-out infinite;
}
.status-dot.status-waiting { background: var(--color-muted-foreground); }
.status-dot.status-offline { background: var(--color-destructive); }
@keyframes status-dot-pulse {
0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-primary) 45%, transparent); }
50% { box-shadow: 0 0 0 5px transparent; }
}
.chain-block { color: var(--color-muted-foreground); white-space: nowrap; }
.maintenance-banner {
display: flex; align-items: flex-start; gap: 8px;
background: color-mix(in srgb, var(--color-primary) 12%, var(--color-surface));
border: 1px solid color-mix(in srgb, var(--color-primary) 40%, transparent);
color: var(--color-foreground); border-radius: var(--radius);
padding: 12px 14px; font-size: 0.82rem; line-height: 1.4; margin-bottom: 16px;
}
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}
@@ -174,10 +380,94 @@
</head>
<body>
<header>
<nav class="hidden" id="app-navbar" aria-label="Sezioni">
<div class="app-navbar-top">
<div class="app-navbar-top-inner">
<span class="brand">
<img class="brand-mark" src="/logo.svg" alt="">
PLM Lottery
</span>
<div class="app-navbar-account">
<span class="navbar-username" id="dash-username"></span>
<span class="navbar-balance mono">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v16"/></svg>
<span id="navbar-balance">— PLM</span>
</span>
<a class="link icon-link" href="/guida" target="_blank" rel="noopener" title="Guida" aria-label="Apri la guida utente">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 2-3 4"/><path d="M12 17h.01"/></svg>
</a>
<a class="link icon-link" href="https://github.com/REPLACE_ME/plm-lottery/issues/new" target="_blank" rel="noopener" title="Segnala un bug" aria-label="Segnala un bug su GitHub">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2v3M16 2v3M12 12v-2a2 2 0 1 1 2 2h-2Z"/><rect x="6" y="10" width="12" height="10" rx="4"/><path d="M6 15H3M21 15h-3M9 20v-3M15 20v-3"/></svg>
</a>
<button class="link icon-link" onclick="logout()" title="Esci" aria-label="Esci dall'account">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/></svg>
</button>
</div>
</div>
</div>
<div class="app-navbar-tabs">
<button class="navbar-tab active" id="nav-deposit" onclick="switchPanel('deposit')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v16"/></svg>
Deposito
</button>
<button class="navbar-tab" id="nav-bet" onclick="switchPanel('bet')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 12h.01M12 12h.01M18 12h.01"/></svg>
Bet
</button>
<button class="navbar-tab" id="nav-withdraw" onclick="switchPanel('withdraw')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
Prelievo
</button>
<button class="navbar-tab" id="nav-profile" onclick="switchPanel('profile')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
Profilo
</button>
</div>
</nav>
<div class="app-shell">
<div class="chain-bar" id="chain-bar">
<span class="chain-status-pill">
<span class="status-dot" id="chain-status-dot"></span>
<span id="chain-status-label">Connessione…</span>
</span>
<span class="chain-block mono" id="chain-block">Blocco —</span>
</div>
<div class="maintenance-banner hidden" id="maintenance-banner">
<span>⚠️</span>
<span>Manutenzione in programma: il round in corso viene completato regolarmente (vincitore incluso), ma il round successivo non si aprirà finché la manutenzione non sarà terminata.</span>
</div>
<section id="landing-hero" class="hero">
<h1>PLM Lottery</h1>
<p>Dashboard di test — mainnet reale</p>
</header>
<p class="lead">Deposita PLM, entra nel round con una quota fissa, e se viene estratto il tuo numero vinci il montepremi.</p>
<div class="hero-steps">
<div class="hero-step">
<div class="step-icon"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v16"/></svg></div>
<div class="step-title">1. Deposita</div>
<div class="step-hint">Ricevi un indirizzo PLM personale, tuo per sempre</div>
</div>
<div class="hero-step">
<div class="step-icon"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 12h.01M12 12h.01M18 12h.01"/></svg></div>
<div class="step-title">2. Gioca</div>
<div class="step-hint">Una bet a quota fissa per entrare nel round corrente</div>
</div>
<div class="hero-step">
<div class="step-icon"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 21h8M12 17v4M7 4h10v4a5 5 0 0 1-10 0V4Z"/><path d="M7 5H4a1 1 0 0 0-1 1v1a4 4 0 0 0 4 4M17 5h3a1 1 0 0 1 1 1v1a4 4 0 0 1-4 4"/></svg></div>
<div class="step-title">3. Vinci</div>
<div class="step-hint">Estrazione dal blocco, montepremi accreditato subito</div>
</div>
</div>
<div class="trust-row">
<span class="trust-pill"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>Quota fissa dichiarata</span>
<span class="trust-pill"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>Estrazione da hash di blocco</span>
<span class="trust-pill"><svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>Prelievo libero in ogni momento</span>
</div>
</section>
<section id="auth-section" class="card">
<div class="tabs">
@@ -206,14 +496,7 @@
<section id="dashboard-section" class="hidden">
<div class="card">
<div class="account-bar">
<span class="name" id="dash-username"></span>
<button class="link" onclick="logout()">Esci</button>
</div>
</div>
<div class="card">
<div class="card round-card" id="round-card">
<div class="row-between" id="round-normal-row">
<h2 id="round-title">Round —</h2>
<span class="mono" id="round-timer" style="font-size:1.1rem;font-weight:700">--:--</span>
@@ -237,21 +520,6 @@
<div class="hidden" id="draw-result"></div>
</div>
<nav class="menu" aria-label="Sezioni">
<button class="nav-item active" id="nav-deposit" onclick="switchPanel('deposit')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v16"/></svg>
Deposito
</button>
<button class="nav-item" id="nav-bet" onclick="switchPanel('bet')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 12h.01M12 12h.01M18 12h.01"/></svg>
Bet
</button>
<button class="nav-item" id="nav-withdraw" onclick="switchPanel('withdraw')">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
Prelievo
</button>
</nav>
<div class="dash-panel active" id="panel-deposit">
<div class="card">
<h2>Saldo interno</h2>
@@ -294,14 +562,48 @@
<p class="hint">Invia fondi a un indirizzo PLM esterno</p>
<label for="wd-address">Indirizzo esterno</label>
<input id="wd-address" class="mono" placeholder="plm1q...">
<p class="hint">Solo indirizzi P2WPKH bech32 (quelli che iniziano con <code>plm1q...</code>). Indirizzi legacy (<code>P...</code>) o P2SH non sono supportati.</p>
<label for="wd-amount">Importo (PLM)</label>
<input id="wd-amount" inputmode="decimal" placeholder="es. 2">
<label class="checkbox-row">
<input type="checkbox" id="wd-full-amount" onchange="toggleWithdrawFullAmount()">
Preleva l'intero importo (<span class="mono" id="wd-full-amount-value">—</span> PLM)
</label>
<button onclick="withdraw()" id="withdraw-btn">Preleva</button>
</div>
</div>
<div class="dash-panel" id="panel-profile">
<div class="card">
<h2>Profilo</h2>
<p class="hint">Le tue informazioni account</p>
<label>Username</label>
<div class="address-box"><span id="profile-username">—</span></div>
<label>Indirizzo di deposito</label>
<div class="address-box"><span class="mono" id="profile-address">—</span></div>
<label>Saldo interno</label>
<div class="address-box"><span class="mono" id="profile-balance">—</span> <span class="balance-unit">PLM</span></div>
<label>Utente dal</label>
<div class="address-box"><span id="profile-created-at">—</span></div>
</div>
<div class="card">
<h2>Impostazioni</h2>
<p class="hint">Cambia la password del tuo account</p>
<label for="settings-current-password">Password attuale</label>
<input id="settings-current-password" type="password" autocomplete="current-password">
<label for="settings-new-password">Nuova password</label>
<input id="settings-new-password" type="password" autocomplete="new-password">
<label for="settings-new-password-confirm">Conferma nuova password</label>
<input id="settings-new-password-confirm" type="password" autocomplete="new-password">
<button onclick="changePassword()" id="change-password-btn">Aggiorna password</button>
</div>
</div>
</section>
</div>
<div id="toast-container" aria-live="polite"></div>
<script>
@@ -349,13 +651,21 @@ function switchTab(name) {
}
function switchPanel(name) {
for (const key of ['deposit', 'bet', 'withdraw']) {
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;
@@ -368,20 +678,114 @@ const ROUND_STATUS_LABELS = {
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
const CHAIN_STATUS_LABELS = {
waiting: 'In attesa del prossimo round',
open: 'Round aperto',
drawing: 'Estrazione 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');
let statusKey;
if (!data.round_id) statusKey = 'waiting';
else if (DRAWING_STATUSES.includes(data.status)) statusKey = 'drawing';
else statusKey = 'open';
dot.className = 'status-dot status-' + statusKey;
label.textContent = CHAIN_STATUS_LABELS[statusKey];
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 = '--:--'; return; }
const totalSec = Math.max(0, Math.floor((roundCloseAt - new Date()) / 1000));
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() {
@@ -409,17 +813,32 @@ function showNormalState() {
}
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;
document.getElementById('round-jackpot').textContent = data.jackpot_sats / SATS_PER_PLM;
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();
@@ -442,6 +861,13 @@ async function refreshRound() {
} 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
@@ -451,8 +877,13 @@ async function refreshRound() {
// one — keep it on screen through the cooldown gap instead of flashing back to
// "Nessun round attivo".
scheduleNextRoundPoll(isDrawing);
// The countdown reaching zero doesn't mean the server has actually closed the
// round yet (it still waits for in-flight bets to confirm) — poll faster
// through that gap too, not just once status flips to closing/drawing/paying_out.
const pastDeadline = data.status === 'open' && roundCloseAt !== null && roundCloseAt - serverNow() <= 0;
scheduleNextRoundPoll(isDrawing || pastDeadline);
} catch (e) {
noteFetchOutcome(false);
scheduleNextRoundPoll(false);
}
}
@@ -463,7 +894,10 @@ function scheduleNextRoundPoll(fast) {
}
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;
@@ -518,8 +952,7 @@ async function login() {
});
}
function logout() {
localStorage.clear();
function resetToLoggedOutUI() {
token = username = address = null;
myUserId = null;
activeResultRoundId = null;
@@ -527,8 +960,45 @@ function logout() {
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() {
@@ -541,6 +1011,7 @@ async function copyAddress() {
}
let myUserId = null;
let myBalanceSats = 0;
async function refreshMe() {
const btn = document.getElementById('refresh-btn');
@@ -548,7 +1019,55 @@ async function refreshMe() {
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');
}
@@ -572,12 +1091,17 @@ async function placeBet() {
async function withdraw() {
const btn = document.getElementById('withdraw-btn');
const ext = document.getElementById('wd-address').value;
const amtPlm = parseFloat(document.getElementById('wd-amount').value);
const amtSats = Math.round(amtPlm * SATS_PER_PLM);
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');
}
@@ -585,7 +1109,7 @@ async function withdraw() {
refreshMe();
}
if (token) showDashboard();
initAuthState();
</script>
</body>
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
<image width="256" height="256" href="data:image/png;base64,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 truncated
</svg>

After

Width:  |  Height:  |  Size: 35 KiB

+36 -4
View File
@@ -20,7 +20,7 @@ sola schermata di login.
## Sezioni della dashboard
- **Parametri** — configurazione operativa (vedi tabella sotto)
- **Utenti** — elenco utenti, saldo, accesso alla chiave privata
- **Utenti** — elenco utenti, saldo, accesso alla chiave privata, reset password
- **Round** — storico round: stato, vincitore, importi, txid di payout
- **Transazioni pendenti** — bet/payout/prelievi non ancora confermati, candidati al fee-bump RBF
- **Audit log** — eventi registrati dal sistema (config cambiata, bet, payout, accessi a chiavi private, ecc.)
@@ -38,9 +38,9 @@ business — quelli si toccano solo da qui.
|---|---|
| **Fee address** | L'indirizzo PLM su cui finisce il 30% di ogni round (fee). Obbligatorio: i payout **non partono** se questo campo è vuoto. |
| **Bet amount (PLM)** | Il costo fisso d'ingresso per round. |
| **Durata round (secondi)** | Quanto resta aperto un round prima di chiudersi ed estrarre il vincitore. |
| **Durata round (secondi)** | Quanto resta aperto un round prima di chiudersi ed estrarre il vincitore. Il taglio per le nuove giocate scatta esattamente allo scadere di questo tempo (verificato ad ogni bet, non dipende dal ciclo dello scheduler) — è un "semaforo giallo": nessuna nuova entrata, ma le bet già trasmesse prima dello scadere hanno comunque tempo di confermarsi prima che il round chiuda ed estragga. |
| **Pausa tra un round e il successivo (secondi)** | Cooldown dopo la chiusura di un round, prima che il successivo si apra — dà tempo ai giocatori di vedere l'esito. |
| **Durata animazione estrazione (secondi)** | Tempo minimo per cui la dashboard di ogni utente mostra l'animazione "Estrazione in corso" dopo la chiusura del round, prima di rivelare il vincitore. È solo un minimo: l'estrazione reale aspetta un blocco confermato (~2 minuti in media), quindi l'animazione può durare più a lungo di questo valore, mai meno. |
| **Durata animazione estrazione (secondi)** | Tempo minimo per cui la dashboard di ogni utente mostra l'animazione "Estrazione in corso" dopo la chiusura del round, prima di rivelare il vincitore. È solo un minimo: il processo reale aspetta fino a 3 blocchi confermati in sequenza (ultima bet in sospeso, estrazione, payout — ~2 minuti l'uno), quindi l'animazione può durare più a lungo di questo valore, mai meno. |
| **Importo minimo deposito/prelievo (PLM)** | Soglia minima per un prelievo (i depositi non hanno un controllo minimo lato server, solo un floor consigliato). |
| **Fee rate di rete (sat/vB)** | Fee per byte usata per costruire bet, payout e prelievi. |
| **Timeout prima del fee-bump RBF (secondi)** | Dopo quanto tempo senza conferma una transazione viene ritrasmessa con fee più alta. |
@@ -54,6 +54,28 @@ hardcoded nel codice (`RoundConfig` in `app/db/models.py`: bet 10 PLM, round
sat/vB, RBF timeout 900s) — vanno
comunque rivisti e confermati dal pannello prima del primo utilizzo reale.
## Manutenzione (pausa/ripresa lotteria)
In cima alla sezione "Parametri" c'è una card "Manutenzione" con un pulsante
per fermare l'apertura di nuovi round — utile per intervenire sul server
(aggiornamenti, riavvii) senza lasciare gli utenti a metà di un round o
sorprenderli con un'interruzione improvvisa.
- **"Interrompi dopo questo round"**: il round eventualmente in corso viene
**completato normalmente** — chiude, estrae il vincitore da un blocco
confermato, e paga il 70/30 come sempre. Solo l'apertura del **round
successivo** viene sospesa. Gli utenti vedono un avviso di manutenzione
sulla loro dashboard (e sulla home, anche da sloggati) finché la lotteria
resta in pausa.
- **"Riprendi lotteria"**: annulla la pausa — al prossimo giro dello
scheduler (ogni 5 secondi) un nuovo round si apre normalmente (rispettando
comunque il cooldown se il precedente si è appena chiuso).
Ogni pausa/ripresa viene registrata nell'audit log (`lottery_paused` /
`lottery_resumed`), ma — come per il resto del pannello — non registra
*quale* operatore l'ha premuta (token condiviso, vedi limiti noti in
[CLAUDE.md](../CLAUDE.md)).
**Chi paga il fee-bump RBF?** Quando una bet, un payout o un prelievo resta
troppo a lungo senza conferma (oltre il "Timeout prima del fee-bump RBF"), il
sistema lo ritrasmette con una fee più alta. Il costo aggiuntivo lo assorbe
@@ -104,7 +126,7 @@ curl -X PUT https://<host>/admin/config \
-d '{"fee_address": "plm1q...", "bet_amount_sats": 1000000000, "round_duration_seconds": 600}'
```
## Utenti e chiave privata
## Utenti, chiave privata e reset password
La card "Utenti" elenca id, username, indirizzo e saldo di ogni utente
registrato. Il bottone "Mostra" su ogni riga rivela la chiave privata (WIF)
@@ -115,6 +137,16 @@ falla: il server è già custodial, la chiave master da cui derivano tutte le
chiavi utente vive sul server — questo pannello espone solo qualcosa che
l'operatore può già fare via script.
Il bottone "Reset" nella colonna "Password" genera una **nuova password
casuale** per l'utente e sovrascrive quella esistente — mostrata una sola
volta nel pannello, così puoi comunicarla a chi ti ha chiesto aiuto perché
l'ha dimenticata. Non è un "recupero": le password sono salvate solo come
hash Argon2 (`app/auth/security.py`), quindi quella vecchia **non è mai
recuperabile** né per l'admin né per il codice stesso — l'unica opzione è
sempre sostituirla con una nuova. Anche questa azione è audit-loggata
(`admin_password_reset`) e non esiste alcun flusso self-service equivalente
per l'utente: solo un admin col token può farlo.
## Limiti noti
- Il token è unico e condiviso: non c'è identità per singolo admin né audit
+57 -12
View File
@@ -20,7 +20,8 @@ login ogni volta che riapri la pagina.
Dopo l'accesso vedi, in ordine:
1. **Barra account** — il tuo username e il bottone "Esci" (logout)
1. **Barra di navigazione** (fissa in alto) — il tuo username e il bottone
"Esci" (logout) nella riga superiore, e i tab delle sezioni subito sotto
2. **Card del round corrente** — sempre visibile, indipendentemente dalla
sezione che stai guardando:
- numero del round e stato (*aperto*, *in chiusura*, *estrazione in
@@ -28,20 +29,35 @@ Dopo l'accesso vedi, in ordine:
- **timer** che conta alla rovescia il tempo rimanente prima della
chiusura del round
- **giocatori**: quanti hanno già piazzato una bet in questo round
- **jackpot**: il totale in PLM che verrà distribuito (70% al vincitore,
30% in fee)
3. **Menu di navigazione** con tre sezioni:
- **jackpot**: quanto riceverà chi vince questo round
3. **Tab di navigazione** con quattro sezioni:
### Estrazione del vincitore
Quando il round chiude, **le bet non sono più accettate** e la card del
round 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: il
vincitore viene scelto usando l'hash del primo blocco confermato dopo la
chiusura, quindi il tempo reale dipende dalla rete (mediamente ~2 minuti,
il block time di PLM).
Appena il timer arriva a zero, **nessun nuovo giocatore può più entrare nel
round** — è un "semaforo giallo": il conteggio raggiunto lo zero blocca da
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:
1. conferma dell'ultima giocata rimasta in sospeso (se ce n'era una proprio
allo scadere del timer — altrimenti questo passo è già superato);
2. un nuovo blocco dopo la chiusura, il cui hash serve a scegliere il
vincitore;
3. la conferma della transazione che paga effettivamente la vincita.
Con un blocco PLM ogni ~2 minuti, il tempo reale dall'azzeramento del
timer all'accredito della vincita è quindi in media **4-6 minuti** (se
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:
@@ -52,6 +68,14 @@ messaggio:
Il messaggio resta visibile fino all'apertura del round successivo.
### Avviso di manutenzione
Se l'operatore ha messo in pausa la lotteria per manutenzione, in cima alla
pagina (visibile anche prima del login) compare un avviso: il round
eventualmente in corso viene comunque **completato normalmente**, vincitore
incluso, ma **non ne parte uno nuovo** finché la manutenzione non termina.
L'avviso sparisce da solo appena l'operatore riprende la lotteria.
### Deposito
- Il tuo **saldo interno** (accreditato dopo 1 conferma di rete) con bottone
@@ -79,6 +103,27 @@ Form con due campi:
Il prelievo viene costruito e trasmesso sulla rete; la fee di rete viene
scalata dall'importo richiesto (non si aggiunge separatamente).
> **Nota**: attualmente è supportato solo l'indirizzo esterno in formato
> **P2WPKH bech32** (quelli che iniziano con `plm1q...`). Non inserire
> indirizzi legacy (quelli che iniziano con `P...`) o P2SH: al momento
> non sono gestiti correttamente dal server.
### Profilo
Due card:
- **Profilo**: le tue informazioni account — username, indirizzo di
deposito, saldo interno e data di iscrizione. Sola lettura, nessuna
modifica possibile qui.
- **Impostazioni**: form per **cambiare la password**. Serve la password
attuale (per conferma) più la nuova password (minimo 8 caratteri, digitata
due volte). Non richiede un nuovo login: la sessione attiva resta valida
anche dopo il cambio.
Se hai dimenticato la password e non riesci più ad accedere, questa sezione
non ti aiuta (serve la password attuale) — contatta l'operatore della
piattaforma, che può reimpostartene una nuova dal pannello admin.
## Notifiche
Ogni azione (registrazione, login, bet, prelievo, ecc.) mostra un breve
+21
View File
@@ -52,6 +52,27 @@ file insieme a `XPRV_ENCRYPTION_KEY`** — uno dei due da solo è inutile, ma
perderli entrambi insieme significa perdere i fondi di tutti gli utenti senza
possibilità di recupero.
### Recuperare o portare una xprv esistente
Due script, entrambi manuali/una tantum, per lo scenario di disaster recovery
o per usare una xprv generata altrove (es. offline/air-gapped) invece di
farla generare al server:
- **`scripts/decrypt_master_key.py`**: decifra e stampa a schermo la xprv
già presente in `MASTER_KEY_PATH` (con fallback automatico su
`./data/keys/master.xprv.enc` se il path di `.env` non esiste in locale).
Chiede conferma esplicita prima di stampare.
- **`scripts/encrypt_master_key.py`**: cifra una xprv esterna e la scrive in
`MASTER_KEY_PATH` con lo stesso identico schema (Fernet +
`XPRV_ENCRYPTION_KEY`) usato da `generate_master_key.py`. La xprv va
incollata con input nascosto (non appare a schermo). Si rifiuta di
sovrascrivere un file esistente a meno di passare `--overwrite`.
Entrambi vanno eseguiti localmente (o dentro il container via
`docker compose run --rm app ...`), mai esposti da un endpoint API o dal
pannello admin: chi ottiene questa xprv ottiene il controllo dei fondi di
tutti gli utenti e del pool.
## 4. Installare le dipendenze (solo workflow locale/venv)
Salta questo passaggio se usi solo Docker — l'immagine installa le proprie
@@ -0,0 +1,37 @@
"""add paused to round_config
Revision ID: 5f2079b95b33
Revises: 1db52f3a7c67
Create Date: 2026-07-22 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '5f2079b95b33'
down_revision: Union[str, Sequence[str], None] = '1db52f3a7c67'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# server_default backfills the existing singleton row (if any); dropped right
# after so new rows go through the ORM default instead of a stale constant.
op.add_column(
'round_config', sa.Column('paused', sa.Boolean(), nullable=False, server_default=sa.false())
)
with op.batch_alter_table('round_config') as batch_op:
batch_op.alter_column('paused', server_default=None)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('round_config', 'paused')
# ### end Alembic commands ###
+51
View File
@@ -0,0 +1,51 @@
"""One-time ops recovery: decrypt and print the server's master xprv.
This is the single secret the entire custodial wallet derives from (every
user address, the pool address) — treat the output like a root password.
Not exposed via any API endpoint or the admin panel, by design; run manually,
locally, only when you actually need it (e.g. disaster-recovery backup).
Usage:
python scripts/decrypt_master_key.py
Requires XPRV_ENCRYPTION_KEY to already be set (.env), same as the running
server. Looks for the encrypted key at MASTER_KEY_PATH (.env) — if that path
doesn't exist, falls back to ./data/keys/master.xprv.enc, the location
docker-compose.yml bind-mounts it to, since .env's default (./master.xprv.enc)
often doesn't match wherever the running server actually reads it from.
"""
import os
from app.config import settings
from app.wallet.keystore import decrypt_xprv
_DOCKER_COMPOSE_PATH = "./data/keys/master.xprv.enc"
def _resolve_key_path() -> str:
if os.path.exists(settings.master_key_path):
return settings.master_key_path
if os.path.exists(_DOCKER_COMPOSE_PATH):
print(f"{settings.master_key_path} not found — using {_DOCKER_COMPOSE_PATH} instead.")
return _DOCKER_COMPOSE_PATH
raise SystemExit(f"No master key found at {settings.master_key_path} or {_DOCKER_COMPOSE_PATH}")
if __name__ == "__main__":
if not settings.xprv_encryption_key:
raise SystemExit("XPRV_ENCRYPTION_KEY is not set")
key_path = _resolve_key_path()
print(f"About to decrypt and print the master xprv from {key_path}.")
print("This key controls every user's funds and the pool. Make sure this")
print("terminal isn't logged/recorded and no one is watching your screen.")
confirm = input("Type 'yes' to continue: ")
if confirm.strip().lower() != "yes":
raise SystemExit("Aborted.")
with open(key_path, "rb") as f:
token = f.read()
print(decrypt_xprv(token))
+76
View File
@@ -0,0 +1,76 @@
"""One-time ops bootstrap: encrypt an externally-generated master xprv and
write it to disk, using the exact same scheme generate_master_key.py uses
(Fernet, XPRV_ENCRYPTION_KEY). Use this instead of generate_master_key.py
when you already have an xprv from elsewhere (e.g. generated offline/air-
gapped) and want to bring your own instead of letting the server create one.
This is the single secret the entire custodial wallet derives from (every
user address, the pool address) — treat both the input and the resulting
encrypted file like a root password.
Usage:
python scripts/encrypt_master_key.py
python scripts/encrypt_master_key.py --overwrite # replace an existing key
Requires XPRV_ENCRYPTION_KEY to already be set (.env). Writes to
MASTER_KEY_PATH (.env) — falls back to ./data/keys/master.xprv.enc (the
docker-compose.yml bind-mount location) if that directory exists and .env's
default path doesn't, same fallback as decrypt_master_key.py.
"""
import argparse
import getpass
import os
from embit.bip32 import HDKey
from app.config import settings
from app.wallet.keystore import encrypt_xprv
_DOCKER_COMPOSE_DIR = "./data/keys"
def _resolve_key_path() -> str:
configured_dir = os.path.dirname(settings.master_key_path) or "."
if os.path.isdir(configured_dir):
return settings.master_key_path
if os.path.isdir(_DOCKER_COMPOSE_DIR):
path = os.path.join(_DOCKER_COMPOSE_DIR, os.path.basename(settings.master_key_path) or "master.xprv.enc")
print(f"{configured_dir}/ not found — using {path} instead.")
return path
return settings.master_key_path
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--overwrite", action="store_true", help="replace an existing encrypted key file")
args = parser.parse_args()
if not settings.xprv_encryption_key:
raise SystemExit("XPRV_ENCRYPTION_KEY is not set")
key_path = _resolve_key_path()
if os.path.exists(key_path) and not args.overwrite:
raise SystemExit(f"{key_path} already exists (pass --overwrite to replace it)")
print("Paste the xprv to encrypt. Input is hidden and not echoed to the terminal.")
xprv = getpass.getpass("xprv: ").strip()
try:
parsed = HDKey.from_base58(xprv)
except Exception as exc:
raise SystemExit(f"Not a valid extended key: {exc}") from exc
# Not checking parsed.version against PLM_MAINNET["xprv"]: PLM reuses Bitcoin
# mainnet's own xprv/xpub version bytes (see plm_network.py) — a Bitcoin (or
# any Bitcoin-derived altcoin) xprv passes this check too, so it can't catch
# "wrong network" mistakes. It only tells us this parses as *some* valid
# extended key.
if not parsed.is_private:
raise SystemExit("This is a public key (xpub), not a private key (xprv) — refusing to encrypt it as one.")
os.makedirs(os.path.dirname(key_path) or ".", exist_ok=True)
with open(key_path, "wb") as f:
f.write(encrypt_xprv(xprv))
print(f"Master key written (encrypted) to {key_path}")
+68
View File
@@ -81,6 +81,29 @@ async def test_admin_reads_and_updates_config(client):
assert resp.json()["fee_address"] == "plm1qfeeaddress"
async def test_admin_can_pause_and_resume_the_lottery(client):
headers = {"X-Admin-Token": "test-admin-token"}
resp = await client.get("/admin/config", headers=headers)
assert resp.json()["paused"] is False
resp = await client.post("/admin/pause", headers=headers)
assert resp.status_code == 200
assert resp.json()["paused"] is True
resp = await client.get("/admin/config", headers=headers)
assert resp.json()["paused"] is True
resp = await client.post("/admin/resume", headers=headers)
assert resp.status_code == 200
assert resp.json()["paused"] is False
async def test_admin_pause_requires_token(client):
resp = await client.post("/admin/pause")
assert resp.status_code == 403
async def test_admin_lists_users(client):
from app.db import base as db_base
from app.db.models import User
@@ -143,3 +166,48 @@ async def test_admin_privkey_404_for_unknown_user(client):
headers = {"X-Admin-Token": "test-admin-token"}
resp = await client.get("/admin/users/999/privkey", headers=headers)
assert resp.status_code == 404
async def test_admin_resets_user_password(client):
from app.auth.security import hash_password, verify_password
from app.db import base as db_base
from app.db.models import User
from app.wallet.hd import derive_user_address
old_hash = hash_password("original-password")
async with db_base.AsyncSessionLocal() as session:
user = User(
username="carol",
password_hash=old_hash,
derivation_index=2,
address=derive_user_address(2),
)
session.add(user)
await session.commit()
await session.refresh(user)
user_id = user.id
headers = {"X-Admin-Token": "test-admin-token"}
resp = await client.post(f"/admin/users/{user_id}/reset-password", headers=headers)
assert resp.status_code == 200
body = resp.json()
assert body["username"] == "carol"
new_password = body["new_password"]
assert new_password and new_password != "original-password"
async with db_base.AsyncSessionLocal() as session:
refreshed = await session.get(User, user_id)
assert refreshed.password_hash != old_hash
assert verify_password(new_password, refreshed.password_hash)
assert not verify_password("original-password", refreshed.password_hash)
async def test_admin_reset_password_requires_token(client):
resp = await client.post("/admin/users/1/reset-password")
assert resp.status_code == 403
async def test_admin_reset_password_404_for_unknown_user(client):
headers = {"X-Admin-Token": "test-admin-token"}
resp = await client.post("/admin/users/999/reset-password", headers=headers)
assert resp.status_code == 404
+30 -1
View File
@@ -1,3 +1,5 @@
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
@@ -5,7 +7,8 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.bets.service import BetError, place_bet
from app.config import settings
from app.db.base import Base
from app.db.models import AuditLog, PendingTransaction, RoundParticipant, User, UtxoEvent
from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, RoundParticipant, User, UtxoEvent
from app.rounds.service import open_new_round_if_needed
from app.wallet.hd import derive_user_address
@@ -104,3 +107,29 @@ async def test_place_bet_rejects_second_bet_same_round(session_factory):
async with session_factory() as session:
participants = (await session.scalars(select(RoundParticipant))).all()
assert len(participants) == 1
async def test_place_bet_rejects_after_timer_expires_even_if_still_open(session_factory):
"""The scheduler only flips status "open" -> "closing" on its next tick (up
to a few seconds late) — place_bet must independently refuse bets once the
round's own deadline has passed, so no new player can sneak in during that
gap (see rounds/service.round_accepts_bets)."""
user_id = await _make_funded_user(session_factory, 3, 3_000_000_000)
client = FakeElectrumClient()
async with session_factory() as session:
session.add(RoundConfig(fee_address="", round_duration_seconds=60))
round_ = await open_new_round_if_needed(session)
round_.opened_at = datetime.now(timezone.utc) - timedelta(seconds=61)
await session.commit()
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(BetError, match="closing"):
await place_bet(session, client, user)
async with session_factory() as session:
participants = (await session.scalars(select(RoundParticipant))).all()
assert len(participants) == 0
round_ = (await session.scalars(select(Round))).one()
assert round_.status == "open" # scheduler hasn't ticked — status is unchanged, only the check is deadline-aware
+25 -1
View File
@@ -4,7 +4,7 @@ import pytest
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.db.base import Base
from app.db.models import Round
from app.db.models import Round, RoundConfig
from app.rounds.service import get_active_round, open_new_round_if_needed
ROUND_COOLDOWN_SECONDS = 30 # matches RoundConfig.round_cooldown_seconds' column default
@@ -81,3 +81,27 @@ async def test_opens_new_round_once_cooldown_elapses(session_factory):
async with session_factory() as session:
round_ = await open_new_round_if_needed(session)
assert round_.status == "open"
async def test_withholds_new_round_while_paused(session_factory):
stale_close = datetime.now(timezone.utc) - timedelta(seconds=ROUND_COOLDOWN_SECONDS + 1)
async with session_factory() as session:
session.add(Round(status="closed", closed_at=stale_close))
session.add(RoundConfig(fee_address="", paused=True))
await session.commit()
async with session_factory() as session:
round_ = await open_new_round_if_needed(session)
assert round_ is None
async def test_pause_does_not_interrupt_a_round_in_progress(session_factory):
async with session_factory() as session:
session.add(Round(status="drawing"))
session.add(RoundConfig(fee_address="", paused=True))
await session.commit()
async with session_factory() as session:
returned = await open_new_round_if_needed(session)
assert returned is not None
assert returned.status == "drawing"
+110
View File
@@ -0,0 +1,110 @@
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 before create_all — declarative models only register
# themselves into Base.metadata when their module is first imported, and
# nothing else in this fixture happens to trigger that import beforehand.
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.users import router as users_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(users_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
await db_base.engine.dispose()
async def _register(client, username="alice", password="original-password"):
resp = await client.post("/auth/register", json={"username": username, "password": password})
assert resp.status_code == 201
return resp.json()["access_token"]
async def test_change_password_requires_current_password(client):
token = await _register(client)
headers = {"Authorization": f"Bearer {token}"}
resp = await client.post(
"/users/me/change-password",
headers=headers,
json={"current_password": "wrong-password", "new_password": "brand-new-password"},
)
assert resp.status_code == 401
async def test_change_password_updates_login(client):
token = await _register(client)
headers = {"Authorization": f"Bearer {token}"}
resp = await client.post(
"/users/me/change-password",
headers=headers,
json={"current_password": "original-password", "new_password": "brand-new-password"},
)
assert resp.status_code == 204
resp = await client.post("/auth/login", json={"username": "alice", "password": "original-password"})
assert resp.status_code == 401
resp = await client.post("/auth/login", json={"username": "alice", "password": "brand-new-password"})
assert resp.status_code == 200
async def test_change_password_rejects_too_short(client):
token = await _register(client)
headers = {"Authorization": f"Bearer {token}"}
resp = await client.post(
"/users/me/change-password",
headers=headers,
json={"current_password": "original-password", "new_password": "short"},
)
assert resp.status_code == 400
async def test_change_password_requires_auth(client):
resp = await client.post(
"/users/me/change-password",
json={"current_password": "x", "new_password": "brand-new-password"},
)
assert resp.status_code in (401, 403)