7 Commits
Author SHA1 Message Date
davideandClaude Sonnet 5 0e56f63e63 Document the DB-only config model and the new dashboard sections
CLAUDE.md and docs/guida-admin.md now describe RoundConfig as the sole
source of truth for business parameters, with no env var counterpart —
defaults live as hardcoded model column defaults, not app/config.py.
guida-admin.md documents the four new dashboard sections (Round,
Transazioni pendenti, Audit log alongside Parametri/Utenti). setup.md
points readers to the admin panel instead of .env for those values.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 15:06:51 +02:00
davideandClaude Sonnet 5 d4aadf6b40 Rebuild the admin panel as a full dashboard with a navbar
Replaces the single scrolling page with a sticky top navbar and five
sections: Parametri (all seven RoundConfig fields, now including round
duration/cooldown/min amount/fee rate/RBF timeout alongside fee address
and bet amount), Utenti (unchanged), Round (history: status, winner,
pool/winner/fee amounts, payout txid), Transazioni pendenti (in-flight
bet/payout/withdrawal txs), and Audit log (recent system events with
parsed payload). Everything loads on login; switching a nav tab
refreshes that section's data.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 15:06:38 +02:00
davideandClaude Sonnet 5 ed16e4d50b Add admin endpoints for round history, pending transactions, audit log
GET /admin/rounds: recent rounds with status, winner (joined username),
pool/winner/fee amounts, payout txid. GET /admin/pending-transactions:
in-flight bet/payout/withdrawal txs (RBF candidates). GET /admin/audit-log:
recent audit_log entries with parsed payload. All gated by the existing
require_admin dependency, feeding the new dashboard sections.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 15:05:49 +02:00
davideandClaude Sonnet 5 30bde96b6e Move all business/round parameters into DB config, out of env entirely
RoundConfig gains round_duration_seconds, round_cooldown_seconds,
min_amount_sats, fee_rate_sat_vb and rbf_timeout_seconds (plus a
hardcoded default for the pre-existing bet_amount_sats) as column
defaults on the model itself — get_round_config no longer seeds from
Settings at all. Every call site that read these from settings
(scheduler, bets, withdrawals, rounds service/route, RBF bumper) now
reads the DB-backed RoundConfig instead.

app/config.py now holds only true env-driven infra/secrets (database
URL, Electrum connection, master key, JWT, admin token) — no business
parameter has an env var anymore, matching an explicit decision to drop
the "seed from settings" indirection entirely rather than keep a env
fallback nobody should rely on.

Migration backfills the existing round_config row via server_default
(matching the old settings defaults) then drops the default, so future
rows go through the ORM/model defaults instead of a stale constant.

Tests updated: should_bump's timeout_seconds is now required (no
settings fallback); test_scheduler.py seeds a RoundConfig row directly
instead of monkeypatching settings; test_withdrawals.py and
test_rounds_service.py use local constants mirroring the model
defaults instead of reading them off settings.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 15:05:40 +02:00
davideandClaude Sonnet 5 48a9eeb839 Gate the admin panel behind a real login screen
/admin now shows only a token field + "Accedi" button on first load —
config and users are structurally in the page but empty/hidden, no data
requested until the token is verified. On successful login (a GET
/admin/config that doesn't 403) it reveals the dashboard and loads
config + users automatically; no more separate "Carica configurazione"/
"Carica utenti" buttons. Token is kept in sessionStorage (cleared on
tab close) so a reload during the same session skips straight back to
the dashboard. Added a Logout button and Enter-to-submit on the token
field.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 14:28:29 +02:00
davideandClaude Sonnet 5 f6035a888b Add password confirmation and an admin users/privkey panel
Registration now requires the password twice, rejected client-side on
mismatch before hitting the API. The admin page gets a Utenti card:
loads the user list (id, username, address, balance in PLM) and a
per-row "Mostra" button that reveals the private key after an explicit
confirm() — click again to hide it. A persistent warning banner notes
that every reveal is audit-logged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 14:22:03 +02:00
davideandClaude Sonnet 5 39c6ea1950 Add admin endpoints to list users and export a user's private key
GET /admin/users lists id/username/address/balance_sats/created_at.
GET /admin/users/{id}/privkey derives and returns that user's raw WIF
private key, for manual intervention (e.g. sweeping funds back if
something's stuck) — this is already a custodial system, the server
holds the master key everything is derived from, so this doesn't grant
a new capability, just exposes an existing one through the API. Every
access is audit-logged (admin_privkey_accessed).

Also fixes a pre-existing test-isolation bug in test_admin.py's client
fixture: app.db.session.get_session had `from app.db.base import
AsyncSessionLocal`, a one-time reference copy at first import — later
tests reassigning db_base.AsyncSessionLocal never reached it, so any
test mixing direct DB writes with router calls silently read/wrote
against a stale, possibly-disposed engine from whichever test ran
first. Fixed by also rebinding app.db.session.AsyncSessionLocal in the
fixture on every run.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 14:21:55 +02:00
22 changed files with 858 additions and 118 deletions

No files matched your search

+3 -2
View File
@@ -17,5 +17,6 @@ JWT_SECRET=
# python -c "import secrets; print(secrets.token_urlsafe(32))"
ADMIN_TOKEN=
ROUND_DURATION_SECONDS=600
ROUND_COOLDOWN_SECONDS=30
# Every business/round parameter (bet amount, round duration/cooldown, min
# amount, fee rate, RBF timeout, fee address) is configured live from the
# admin panel (/admin) instead of here — see docs/guida-admin.md.
+2 -3
View File
@@ -60,9 +60,8 @@ Known risk: `docker-compose.yml` sets `restart: unless-stopped` on `app`, so a c
- **PLM node access**: Electrum protocol only (no full node/P2P). Bootstrap server for development: `santantonio.sytes.net:50002` (SSL).
- **Auth**: Argon2 password hashing + JWT sessions.
- **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** (fee/commission address, RBF fee-bump wallet, etc.): stored in a DB config table, not env vars — must be editable without a redeploy.
- **Round duration**: configurable via env var, default 10 minutes (not hardcoded).
- **Round cooldown**: `ROUND_COOLDOWN_SECONDS` (default 30s) — gap after a round closes before the next one opens, so players have time to see the outcome. Not in the original flowchart; added afterwards as an explicit design decision.
- **Operational config**: every business/round parameter (fee address, bet amount, round duration, round cooldown, 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**: 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.
## PLM network parameters
+202 -6
View File
@@ -1,10 +1,16 @@
import json
from fastapi import APIRouter, Depends, Header, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.log import write_audit_log
from app.config import settings
from app.db.models import AuditLog, PendingTransaction, Round, User
from app.db.session import get_session
from app.rounds.config import get_round_config
from app.wallet.hd import derive_user_wif
router = APIRouter(prefix="/admin", tags=["admin"])
@@ -17,18 +23,40 @@ async def require_admin(x_admin_token: str = Header(default="")) -> None:
class RoundConfigResponse(BaseModel):
fee_address: str
bet_amount_sats: int
round_duration_seconds: int
round_cooldown_seconds: int
min_amount_sats: int
fee_rate_sat_vb: int
rbf_timeout_seconds: int
class RoundConfigUpdate(BaseModel):
fee_address: str | None = None
bet_amount_sats: int | None = None
round_duration_seconds: int | None = None
round_cooldown_seconds: int | None = None
min_amount_sats: int | None = None
fee_rate_sat_vb: int | None = None
rbf_timeout_seconds: int | None = None
def _config_response(config) -> RoundConfigResponse:
return RoundConfigResponse(
fee_address=config.fee_address,
bet_amount_sats=config.bet_amount_sats,
round_duration_seconds=config.round_duration_seconds,
round_cooldown_seconds=config.round_cooldown_seconds,
min_amount_sats=config.min_amount_sats,
fee_rate_sat_vb=config.fee_rate_sat_vb,
rbf_timeout_seconds=config.rbf_timeout_seconds,
)
@router.get("/config", response_model=RoundConfigResponse, dependencies=[Depends(require_admin)])
async def read_config(session: AsyncSession = Depends(get_session)) -> RoundConfigResponse:
config = await get_round_config(session)
await session.commit()
return RoundConfigResponse(fee_address=config.fee_address, bet_amount_sats=config.bet_amount_sats)
return _config_response(config)
@router.put("/config", response_model=RoundConfigResponse, dependencies=[Depends(require_admin)])
@@ -36,9 +64,177 @@ async def update_config(
body: RoundConfigUpdate, session: AsyncSession = Depends(get_session)
) -> RoundConfigResponse:
config = await get_round_config(session)
if body.fee_address is not None:
config.fee_address = body.fee_address
if body.bet_amount_sats is not None:
config.bet_amount_sats = body.bet_amount_sats
for field in (
"fee_address",
"bet_amount_sats",
"round_duration_seconds",
"round_cooldown_seconds",
"min_amount_sats",
"fee_rate_sat_vb",
"rbf_timeout_seconds",
):
value = getattr(body, field)
if value is not None:
setattr(config, field, value)
await session.commit()
return RoundConfigResponse(fee_address=config.fee_address, bet_amount_sats=config.bet_amount_sats)
return _config_response(config)
class AdminUserResponse(BaseModel):
id: int
username: str
address: str
balance_sats: int
created_at: str
@router.get("/users", response_model=list[AdminUserResponse], dependencies=[Depends(require_admin)])
async def list_users(session: AsyncSession = Depends(get_session)) -> list[AdminUserResponse]:
users = (await session.scalars(select(User).order_by(User.id))).all()
return [
AdminUserResponse(
id=u.id,
username=u.username,
address=u.address,
balance_sats=u.cached_balance_sats,
created_at=u.created_at.isoformat(),
)
for u in users
]
class AdminPrivkeyResponse(BaseModel):
address: str
wif: str
@router.get(
"/users/{user_id}/privkey", response_model=AdminPrivkeyResponse, dependencies=[Depends(require_admin)]
)
async def user_privkey(user_id: int, session: AsyncSession = Depends(get_session)) -> AdminPrivkeyResponse:
"""Exports a user's raw private key for manual intervention (e.g. sweeping
funds back if something's stuck). Every access is audit-logged since this is
the most sensitive data the platform holds."""
user = await session.get(User, user_id)
if user is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "user not found")
wif = derive_user_wif(user.derivation_index)
await write_audit_log(session, "admin_privkey_accessed", {"user_id": user_id}, user_id=user_id)
await session.commit()
return AdminPrivkeyResponse(address=user.address, wif=wif)
class AdminRoundResponse(BaseModel):
id: int
status: str
opened_at: str
closed_at: str | None
draw_block_height: int | None
draw_block_hash: str | None
winner_user_id: int | None
winner_username: str | None
pool_amount_sats: int | None
winner_amount_sats: int | None
fee_amount_sats: int | None
payout_txid: str | None
@router.get("/rounds", response_model=list[AdminRoundResponse], dependencies=[Depends(require_admin)])
async def list_rounds(session: AsyncSession = Depends(get_session), limit: int = 50) -> list[AdminRoundResponse]:
rounds = (await session.scalars(select(Round).order_by(Round.id.desc()).limit(limit))).all()
winner_ids = {r.winner_user_id for r in rounds if r.winner_user_id is not None}
winners = {}
if winner_ids:
users = (await session.scalars(select(User).where(User.id.in_(winner_ids)))).all()
winners = {u.id: u.username for u in users}
return [
AdminRoundResponse(
id=r.id,
status=r.status,
opened_at=r.opened_at.isoformat(),
closed_at=r.closed_at.isoformat() if r.closed_at else None,
draw_block_height=r.draw_block_height,
draw_block_hash=r.draw_block_hash,
winner_user_id=r.winner_user_id,
winner_username=winners.get(r.winner_user_id) if r.winner_user_id is not None else None,
pool_amount_sats=r.pool_amount_sats,
winner_amount_sats=r.winner_amount_sats,
fee_amount_sats=r.fee_amount_sats,
payout_txid=r.payout_txid,
)
for r in rounds
]
class AdminAuditLogResponse(BaseModel):
id: int
event_type: str
payload: dict
user_id: int | None
round_id: int | None
created_at: str
@router.get(
"/audit-log", response_model=list[AdminAuditLogResponse], dependencies=[Depends(require_admin)]
)
async def list_audit_log(
session: AsyncSession = Depends(get_session), limit: int = 200
) -> list[AdminAuditLogResponse]:
entries = (await session.scalars(select(AuditLog).order_by(AuditLog.id.desc()).limit(limit))).all()
return [
AdminAuditLogResponse(
id=e.id,
event_type=e.event_type,
payload=json.loads(e.payload_json),
user_id=e.user_id,
round_id=e.round_id,
created_at=e.created_at.isoformat(),
)
for e in entries
]
class AdminPendingTransactionResponse(BaseModel):
id: int
kind: str
status: str
round_id: int | None
withdrawal_id: int | None
user_id: int | None
current_txid: str
fee_rate_sat_vb: int
attempt_count: int
broadcast_at: str
replaced_by_txid: str | None
@router.get(
"/pending-transactions",
response_model=list[AdminPendingTransactionResponse],
dependencies=[Depends(require_admin)],
)
async def list_pending_transactions(
session: AsyncSession = Depends(get_session),
) -> list[AdminPendingTransactionResponse]:
entries = (
await session.scalars(select(PendingTransaction).order_by(PendingTransaction.id.desc()))
).all()
return [
AdminPendingTransactionResponse(
id=p.id,
kind=p.kind,
status=p.status,
round_id=p.round_id,
withdrawal_id=p.withdrawal_id,
user_id=p.user_id,
current_txid=p.current_txid,
fee_rate_sat_vb=p.fee_rate_sat_vb,
attempt_count=p.attempt_count,
broadcast_at=p.broadcast_at.isoformat(),
replaced_by_txid=p.replaced_by_txid,
)
for p in entries
]
+1 -2
View File
@@ -5,7 +5,6 @@ from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.db.models import RoundParticipant
from app.db.session import get_session
from app.rounds.config import get_round_config
@@ -36,7 +35,7 @@ async def current_round(session: AsyncSession = Depends(get_session)) -> Current
select(func.count()).select_from(RoundParticipant).where(RoundParticipant.round_id == round_.id)
) or 0
opened_at = round_.opened_at.replace(tzinfo=timezone.utc)
closes_at = opened_at + timedelta(seconds=settings.round_duration_seconds)
closes_at = opened_at + timedelta(seconds=config.round_duration_seconds)
await session.commit()
return CurrentRoundResponse(
+6 -5
View File
@@ -5,7 +5,6 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.log import write_audit_log
from app.config import settings
from app.db.models import PendingTransaction, RoundParticipant, User, UtxoEvent
from app.electrum.client import ElectrumClient
from app.rounds.config import get_round_config
@@ -57,7 +56,7 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
to_address=derive_pool_address(),
amount_sats=bet_amount,
change_address=user.address,
fee_rate_sat_vb=settings.fee_rate_sat_vb,
fee_rate_sat_vb=config.fee_rate_sat_vb,
)
except InsufficientFundsError as exc:
raise BetError(str(exc)) from exc
@@ -80,7 +79,7 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
status="broadcast",
)
session.add(participant)
session.add(_pending_transaction(round_.id, user.id, built))
session.add(_pending_transaction(round_.id, user.id, built, config.fee_rate_sat_vb))
await write_audit_log(
session,
"bet_placed",
@@ -94,13 +93,15 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
return participant
def _pending_transaction(round_id: int, user_id: int, built: BuiltTransaction) -> PendingTransaction:
def _pending_transaction(
round_id: int, user_id: int, built: BuiltTransaction, fee_rate_sat_vb: int
) -> PendingTransaction:
return PendingTransaction(
kind="bet",
round_id=round_id,
user_id=user_id,
current_txid=built.txid,
fee_rate_sat_vb=settings.fee_rate_sat_vb,
fee_rate_sat_vb=fee_rate_sat_vb,
raw_tx_hex=built.raw_hex,
status="pending",
)
+5 -8
View File
@@ -17,14 +17,11 @@ class Settings(BaseSettings):
jwt_expire_minutes: int = 60 * 24
admin_token: str = ""
round_duration_seconds: int = 600
round_cooldown_seconds: int = 30
bet_amount_sats: int = 10 * 100_000_000
min_amount_sats: int = 1 * 100_000_000
confirmations_required: int = 1
fee_rate_sat_vb: int = 1
rbf_timeout_seconds: int = 900
# Every business/round parameter (bet amount, round duration/cooldown,
# min amount, fee rate, RBF timeout, fee address) lives in the round_config
# DB table instead (app/db/models.py RoundConfig, app/rounds/config.py) —
# editable live via the admin panel/API, no env var, no restart. Only true
# infra/secrets belong in this Settings class.
settings = Settings()
+11 -4
View File
@@ -74,15 +74,22 @@ class RoundParticipant(Base):
class RoundConfig(Base):
"""Single-row operational config, DB-backed so it's editable without a redeploy.
round_duration is intentionally NOT here: it stays env-var-driven per spec.
Don't move it here without an explicit decision to change that.
"""
Everything business/round-related lives here (round timing, bet amount, fee
rate, RBF timeout, minimum amount) so an operator can tune it live. Secrets
and infra wiring (master key, JWT secret, Electrum host, admin token,
database URL) deliberately stay env-var-driven — those require a restart
anyway and aren't safe to hot-swap."""
__tablename__ = "round_config"
id: Mapped[int] = mapped_column(primary_key=True)
fee_address: Mapped[str] = mapped_column(String(128))
bet_amount_sats: Mapped[int] = mapped_column(BigInteger)
bet_amount_sats: Mapped[int] = mapped_column(BigInteger, default=1_000_000_000)
round_duration_seconds: Mapped[int] = mapped_column(default=600)
round_cooldown_seconds: Mapped[int] = mapped_column(default=30)
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)
updated_at: Mapped[datetime] = mapped_column(default=utcnow, onupdate=utcnow)
+5 -5
View File
@@ -1,17 +1,17 @@
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.db.models import RoundConfig
async def get_round_config(session: AsyncSession) -> RoundConfig:
"""Single-row operational config, lazily seeded from settings defaults on
first use. fee_address starts empty until an operator sets it (admin
endpoint, stage 10) — payouts must refuse to run until it's set."""
"""Single-row operational config, lazily created on first use with the
column defaults declared on RoundConfig itself (app/db/models.py) — no env
var involved. fee_address starts empty until an operator sets it via the
admin panel/API — payouts must refuse to run until it's set."""
config = await session.scalar(select(RoundConfig))
if config is None:
config = RoundConfig(fee_address="", bet_amount_sats=settings.bet_amount_sats)
config = RoundConfig(fee_address="")
session.add(config)
await session.flush()
return config
+4 -4
View File
@@ -7,7 +7,6 @@ from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import async_sessionmaker
from app.audit.log import write_audit_log
from app.config import settings
from app.db.models import PendingTransaction, Round, RoundParticipant, User
from app.electrum.listener import ElectrumListener
from app.electrum.scripthash import address_to_scripthash
@@ -53,12 +52,13 @@ class RoundScheduler:
if round_ is None:
return # still in the cooldown window after the last round closed
round_id, status, opened_at = round_.id, round_.status, round_.opened_at
round_duration_seconds = (await get_round_config(session)).round_duration_seconds
if status != "open":
return # already closing/drawing/paying_out; progress happens elsewhere
opened_at = opened_at.replace(tzinfo=timezone.utc)
if datetime.now(timezone.utc) < opened_at + timedelta(seconds=settings.round_duration_seconds):
if datetime.now(timezone.utc) < opened_at + timedelta(seconds=round_duration_seconds):
return
async with self._session_factory() as session:
@@ -175,7 +175,7 @@ class RoundScheduler:
fee_address=config.fee_address,
commission_sats=commission_share,
change_address=pool_address,
fee_rate_sat_vb=settings.fee_rate_sat_vb,
fee_rate_sat_vb=config.fee_rate_sat_vb,
)
except InsufficientFundsError:
logger.exception("round %s payout failed: insufficient pool UTXOs", round_id)
@@ -191,7 +191,7 @@ class RoundScheduler:
kind="payout",
round_id=round_id,
current_txid=built.txid,
fee_rate_sat_vb=settings.fee_rate_sat_vb,
fee_rate_sat_vb=config.fee_rate_sat_vb,
raw_tx_hex=built.raw_hex,
status="pending",
)
+3 -2
View File
@@ -3,8 +3,8 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.db.models import Round
from app.rounds.config import get_round_config
_ACTIVE_STATUSES = ("open", "closing", "drawing", "paying_out")
@@ -30,7 +30,8 @@ async def open_new_round_if_needed(session: AsyncSession) -> Round | 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)
if datetime.now(timezone.utc) < closed_at + timedelta(seconds=settings.round_cooldown_seconds):
cooldown_seconds = (await get_round_config(session)).round_cooldown_seconds
if datetime.now(timezone.utc) < closed_at + timedelta(seconds=cooldown_seconds):
return None
round_ = Round(status="open")
+383 -39
View File
@@ -29,17 +29,40 @@
font-family: 'Fira Sans', system-ui, sans-serif;
background: var(--color-background);
color: var(--color-foreground);
max-width: 480px;
margin: 0 auto;
padding: 32px 20px 80px;
margin: 0;
line-height: 1.5;
}
.mono { font-family: 'Fira Code', monospace; }
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; }
/* --- login screen: narrow, centered --- */
#login-section { max-width: 420px; margin: 15vh auto 0; padding: 0 20px; }
#login-section header { margin-bottom: 24px; }
#login-section header h1 { font-size: 1.375rem; font-weight: 700; margin: 0; letter-spacing: -0.01em; }
#login-section header p { color: var(--color-muted-foreground); font-size: 0.9rem; margin: 4px 0 0; }
/* --- dashboard: navbar + content --- */
.navbar {
display: flex; align-items: center; gap: 4px; flex-wrap: wrap;
background: var(--color-surface); border-bottom: 1px solid var(--color-border);
padding: 0 20px; position: sticky; top: 0; z-index: 10;
}
.navbar .brand { font-weight: 700; font-size: 1.05rem; padding: 14px 16px 14px 0; white-space: nowrap; }
.navbar .nav-tab {
padding: 16px 14px; font-size: 0.9rem; font-weight: 600; cursor: pointer;
color: var(--color-muted-foreground); border-bottom: 2px solid transparent;
margin-bottom: -1px; transition: color 150ms, border-color 150ms; white-space: nowrap;
}
.navbar .nav-tab.active { color: var(--color-foreground); border-bottom-color: var(--color-primary); }
.navbar .nav-tab:hover { color: var(--color-foreground); }
.navbar .spacer { flex: 1; }
main { max-width: 960px; margin: 0 auto; padding: 24px 20px 80px; }
.view { display: none; }
.view.active { display: block; }
h2.section-title { font-size: 1.15rem; font-weight: 700; margin: 0 0 4px; }
.card {
background: var(--color-surface);
@@ -51,6 +74,8 @@
.card .hint { color: var(--color-muted-foreground); font-size: 0.85rem; margin: 0 0 14px; }
.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0 20px; }
label { display: block; font-size: 0.85rem; font-weight: 500; color: var(--color-muted-foreground); margin-top: 12px; margin-bottom: 6px; }
label:first-child { margin-top: 0; }
@@ -78,12 +103,48 @@
button:focus-visible { outline: 2px solid var(--color-ring); outline-offset: 2px; }
button.secondary {
width: auto; margin-top: 0; min-height: 36px; padding: 0 14px;
background: var(--color-background); color: var(--color-foreground);
border: 1px solid var(--color-border);
}
.hidden { display: none !important; }
table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
th, td { text-align: left; padding: 8px 6px; border-bottom: 1px solid var(--color-border); vertical-align: top; }
th { color: var(--color-muted-foreground); font-weight: 500; }
td.addr, td.txid { font-family: 'Fira Code', monospace; word-break: break-all; max-width: 200px; }
.table-wrap { overflow-x: auto; }
.badge {
display: inline-block; font-size: 0.72rem; font-weight: 600; padding: 2px 8px;
border-radius: 999px; background: var(--color-background); border: 1px solid var(--color-border);
}
.badge.status-open, .badge.status-confirmed, .badge.status-closed { background: var(--color-success-bg); color: var(--color-success); border-color: var(--color-success); }
.badge.status-pending, .badge.status-drawing, .badge.status-paying_out, .badge.status-closing, .badge.status-broadcast {
background: #FEF3C7; color: #92400E; border-color: #F59E0B;
}
button.reveal {
width: auto; margin-top: 0; padding: 4px 10px; min-height: 30px; font-size: 0.78rem;
background: var(--color-destructive-bg); color: var(--color-destructive); border: 1px solid var(--color-destructive);
}
.privkey-box {
margin-top: 6px; padding: 8px; border-radius: 6px; font-size: 0.78rem;
background: var(--color-destructive-bg); border: 1px solid var(--color-destructive);
word-break: break-all; font-family: 'Fira Code', monospace; color: var(--color-foreground);
}
.warning-banner {
background: var(--color-destructive-bg); border: 1px solid var(--color-destructive); color: var(--color-destructive);
border-radius: 8px; padding: 10px 12px; font-size: 0.8rem; margin-bottom: 14px; font-weight: 500;
}
pre.payload {
background: var(--color-background); border: 1px solid var(--color-border); border-radius: 6px;
padding: 6px 8px; font-size: 0.75rem; margin: 0; white-space: pre-wrap; word-break: break-all;
}
#toast-container {
position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
display: flex; flex-direction: column; gap: 8px; z-index: 100; width: calc(100% - 40px); max-width: 440px;
@@ -104,35 +165,138 @@
</head>
<body>
<header>
<h1>PLM Lottery — Admin</h1>
<p>Configurazione operativa del round</p>
</header>
<section id="login-section">
<header>
<h1>PLM Lottery — Admin</h1>
<p>Accesso riservato</p>
</header>
<div class="card">
<p class="hint">
Salvata nel database, modificabile in qualsiasi momento senza riavviare il server.
Serve il token admin (<code>ADMIN_TOKEN</code> nel <code>.env</code> del server).
</p>
<label for="admin-token">Admin token</label>
<input id="admin-token" type="password" placeholder="valore di ADMIN_TOKEN">
<button class="secondary" onclick="adminLoad()" id="load-btn">Carica configurazione attuale</button>
<div id="admin-form" class="hidden">
<label for="admin-fee-address">Fee address (dove finisce il 30% di ogni round)</label>
<input id="admin-fee-address" class="mono" placeholder="plm1q...">
<label for="admin-bet-amount">Bet amount (PLM)</label>
<input id="admin-bet-amount" inputmode="decimal" placeholder="es. 10">
<button onclick="adminSave()" id="save-btn">Salva</button>
<div class="card">
<label for="admin-token">Admin token</label>
<input id="admin-token" type="password" placeholder="valore di ADMIN_TOKEN" autofocus>
<button onclick="adminLogin()" id="login-btn">Accedi</button>
</div>
</section>
<div id="dashboard-section" class="hidden">
<nav class="navbar">
<span class="brand">PLM Lottery — Admin</span>
<span class="nav-tab active" id="nav-parametri" onclick="switchView('parametri')">Parametri</span>
<span class="nav-tab" id="nav-utenti" onclick="switchView('utenti')">Utenti</span>
<span class="nav-tab" id="nav-round" onclick="switchView('round')">Round</span>
<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>
</nav>
<main>
<div class="view active" id="view-parametri">
<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">
<div class="grid-2">
<div>
<label for="admin-fee-address">Fee address (dove finisce il 30% di ogni round)</label>
<input id="admin-fee-address" class="mono" placeholder="plm1q...">
<label for="admin-bet-amount">Bet amount (PLM)</label>
<input id="admin-bet-amount" inputmode="decimal" placeholder="es. 10">
<label for="admin-min-amount">Importo minimo deposito/prelievo (PLM)</label>
<input id="admin-min-amount" inputmode="decimal" placeholder="es. 1">
</div>
<div>
<label for="admin-round-duration">Durata round (secondi)</label>
<input id="admin-round-duration" inputmode="numeric" placeholder="es. 600">
<label for="admin-round-cooldown">Pausa tra un round e il successivo (secondi)</label>
<input id="admin-round-cooldown" inputmode="numeric" placeholder="es. 30">
<label for="admin-fee-rate">Fee rate di rete (sat/vB)</label>
<input id="admin-fee-rate" inputmode="numeric" placeholder="es. 1">
<label for="admin-rbf-timeout">Timeout prima del fee-bump RBF (secondi)</label>
<input id="admin-rbf-timeout" inputmode="numeric" placeholder="es. 900">
</div>
</div>
<button onclick="adminSave()" id="save-btn">Salva</button>
</div>
</div>
<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>
<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.
</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>
</thead>
<tbody id="users-tbody"></tbody>
</table>
</div>
</div>
</div>
<div class="view" id="view-round">
<h2 class="section-title">Round</h2>
<p class="hint">Ultimi round: stato, vincitore, importi e transazione di payout.</p>
<div class="card">
<div class="table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Stato</th><th>Apertura</th><th>Vincitore</th><th>Pool (PLM)</th><th>Vincita (PLM)</th><th>Fee (PLM)</th><th>Payout txid</th></tr>
</thead>
<tbody id="rounds-tbody"></tbody>
</table>
</div>
</div>
</div>
<div class="view" id="view-pending">
<h2 class="section-title">Transazioni pendenti</h2>
<p class="hint">Bet, payout e prelievi non ancora confermati — candidati al fee-bump RBF se scade il timeout.</p>
<div class="card">
<div class="table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Tipo</th><th>Stato</th><th>Txid</th><th>Fee rate</th><th>Tentativi</th><th>Trasmessa</th></tr>
</thead>
<tbody id="pending-tbody"></tbody>
</table>
</div>
</div>
</div>
<div class="view" id="view-audit">
<h2 class="section-title">Audit log</h2>
<p class="hint">Ultimi eventi registrati dal sistema (config, bet, payout, accessi a chiavi private, ecc.).</p>
<div class="card">
<div class="table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Evento</th><th>Dettagli</th><th>Utente</th><th>Round</th><th>Quando</th></tr>
</thead>
<tbody id="audit-tbody"></tbody>
</table>
</div>
</div>
</div>
</main>
</div>
<div id="toast-container" aria-live="polite"></div>
<script>
const SATS_PER_PLM = 100000000;
let adminToken = sessionStorage.getItem('plm_admin_token');
function toast(message, type) {
const container = document.getElementById('toast-container');
@@ -156,7 +320,6 @@ async function withLoading(button, label, fn) {
}
async function callAdmin(method, path, body) {
const adminToken = document.getElementById('admin-token').value;
const headers = { 'Content-Type': 'application/json', 'X-Admin-Token': adminToken };
const res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined });
const data = await res.json().catch(() => ({}));
@@ -164,35 +327,216 @@ async function callAdmin(method, path, body) {
return data;
}
async function adminLoad() {
const btn = document.getElementById('load-btn');
await withLoading(btn, 'Caricamento…', async () => {
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function badge(status) {
return `<span class="badge status-${escapeHtml(status)}">${escapeHtml(status)}</span>`;
}
function fmtDate(iso) {
if (!iso) return '—';
return new Date(iso).toLocaleString('it-IT');
}
const VIEWS = ['parametri', 'utenti', 'round', 'pending', 'audit'];
function switchView(name) {
for (const key of VIEWS) {
document.getElementById('nav-' + key).classList.toggle('active', key === name);
document.getElementById('view-' + key).classList.toggle('active', key === name);
}
const loaders = { utenti: loadUsers, round: loadRounds, pending: loadPending, audit: loadAuditLog };
if (loaders[name]) loaders[name]();
}
function showDashboard() {
document.getElementById('login-section').classList.add('hidden');
document.getElementById('dashboard-section').classList.remove('hidden');
}
async function loadDashboard() {
await Promise.all([adminLoadConfig(), loadUsers(), loadRounds(), loadPending(), loadAuditLog()]);
}
async function adminLogin() {
const btn = document.getElementById('login-btn');
adminToken = document.getElementById('admin-token').value;
await withLoading(btn, 'Verifica…', async () => {
try {
const data = await callAdmin('GET', '/admin/config');
document.getElementById('admin-fee-address').value = data.fee_address;
document.getElementById('admin-bet-amount').value = data.bet_amount_sats / SATS_PER_PLM;
document.getElementById('admin-form').classList.remove('hidden');
toast('Configurazione caricata.', 'success');
await callAdmin('GET', '/admin/config');
sessionStorage.setItem('plm_admin_token', adminToken);
showDashboard();
await loadDashboard();
} catch (e) {
toast('Errore: ' + e.message, 'error');
adminToken = null;
toast('Token non valido.', 'error');
}
});
}
function adminLogout() {
sessionStorage.removeItem('plm_admin_token');
adminToken = null;
document.getElementById('admin-token').value = '';
document.getElementById('dashboard-section').classList.add('hidden');
document.getElementById('login-section').classList.remove('hidden');
}
async function adminLoadConfig() {
try {
const data = await callAdmin('GET', '/admin/config');
document.getElementById('admin-fee-address').value = data.fee_address;
document.getElementById('admin-bet-amount').value = data.bet_amount_sats / SATS_PER_PLM;
document.getElementById('admin-round-duration').value = data.round_duration_seconds;
document.getElementById('admin-round-cooldown').value = data.round_cooldown_seconds;
document.getElementById('admin-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;
} catch (e) {
toast('Errore nel caricamento configurazione: ' + e.message, 'error');
}
}
async function adminSave() {
const btn = document.getElementById('save-btn');
const feeAddress = document.getElementById('admin-fee-address').value;
const betAmountPlm = parseFloat(document.getElementById('admin-bet-amount').value);
const betAmountSats = Math.round(betAmountPlm * SATS_PER_PLM);
const minAmountPlm = parseFloat(document.getElementById('admin-min-amount').value);
const body = {
fee_address: feeAddress,
bet_amount_sats: Math.round(betAmountPlm * SATS_PER_PLM),
round_duration_seconds: parseInt(document.getElementById('admin-round-duration').value, 10),
round_cooldown_seconds: parseInt(document.getElementById('admin-round-cooldown').value, 10),
min_amount_sats: Math.round(minAmountPlm * SATS_PER_PLM),
fee_rate_sat_vb: parseInt(document.getElementById('admin-fee-rate').value, 10),
rbf_timeout_seconds: parseInt(document.getElementById('admin-rbf-timeout').value, 10),
};
await withLoading(btn, 'Salvataggio…', async () => {
try {
await callAdmin('PUT', '/admin/config', { fee_address: feeAddress, bet_amount_sats: betAmountSats });
await callAdmin('PUT', '/admin/config', body);
toast('Configurazione salvata.', 'success');
} catch (e) {
toast('Errore nel salvataggio: ' + e.message, 'error');
}
});
}
async function loadUsers() {
try {
const users = await callAdmin('GET', '/admin/users');
const tbody = document.getElementById('users-tbody');
tbody.innerHTML = users.map((u) => `
<tr>
<td>${u.id}</td>
<td>${escapeHtml(u.username)}</td>
<td class="addr">${escapeHtml(u.address)}</td>
<td>${u.balance_sats / SATS_PER_PLM}</td>
<td>${fmtDate(u.created_at)}</td>
<td>
<button class="reveal" onclick="revealPrivkey(${u.id}, this)">Mostra</button>
<div class="privkey-box hidden" id="privkey-${u.id}"></div>
</td>
</tr>
`).join('') || '<tr><td colspan="6" class="hint">Nessun utente registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento utenti: ' + e.message, 'error');
}
}
async function revealPrivkey(userId, button) {
const box = document.getElementById('privkey-' + userId);
if (!box.classList.contains('hidden')) {
box.classList.add('hidden');
box.textContent = '';
button.textContent = 'Mostra';
return;
}
if (!window.confirm('Stai per visualizzare la chiave privata di questo utente. L\'accesso verrà registrato nell\'audit log. Continuare?')) {
return;
}
await withLoading(button, '…', async () => {
try {
const data = await callAdmin('GET', '/admin/users/' + userId + '/privkey');
box.textContent = data.wif;
box.classList.remove('hidden');
button.textContent = 'Nascondi';
} catch (e) {
toast('Errore: ' + e.message, 'error');
}
});
}
async function loadRounds() {
try {
const rounds = await callAdmin('GET', '/admin/rounds');
const tbody = document.getElementById('rounds-tbody');
tbody.innerHTML = rounds.map((r) => `
<tr>
<td>${r.id}</td>
<td>${badge(r.status)}</td>
<td>${fmtDate(r.opened_at)}</td>
<td>${r.winner_username ? escapeHtml(r.winner_username) : '—'}</td>
<td>${r.pool_amount_sats != null ? r.pool_amount_sats / SATS_PER_PLM : '—'}</td>
<td>${r.winner_amount_sats != null ? r.winner_amount_sats / SATS_PER_PLM : '—'}</td>
<td>${r.fee_amount_sats != null ? r.fee_amount_sats / SATS_PER_PLM : '—'}</td>
<td class="txid">${r.payout_txid ? escapeHtml(r.payout_txid) : '—'}</td>
</tr>
`).join('') || '<tr><td colspan="8" class="hint">Nessun round ancora.</td></tr>';
} catch (e) {
toast('Errore nel caricamento round: ' + e.message, 'error');
}
}
async function loadPending() {
try {
const items = await callAdmin('GET', '/admin/pending-transactions');
const tbody = document.getElementById('pending-tbody');
tbody.innerHTML = items.map((p) => `
<tr>
<td>${p.id}</td>
<td>${escapeHtml(p.kind)}</td>
<td>${badge(p.status)}</td>
<td class="txid">${escapeHtml(p.current_txid)}</td>
<td>${p.fee_rate_sat_vb} sat/vB</td>
<td>${p.attempt_count}</td>
<td>${fmtDate(p.broadcast_at)}</td>
</tr>
`).join('') || '<tr><td colspan="7" class="hint">Nessuna transazione pendente.</td></tr>';
} catch (e) {
toast('Errore nel caricamento transazioni pendenti: ' + e.message, 'error');
}
}
async function loadAuditLog() {
try {
const entries = await callAdmin('GET', '/admin/audit-log');
const tbody = document.getElementById('audit-tbody');
tbody.innerHTML = entries.map((e) => `
<tr>
<td>${e.id}</td>
<td>${escapeHtml(e.event_type)}</td>
<td><pre class="payload">${escapeHtml(JSON.stringify(e.payload))}</pre></td>
<td>${e.user_id ?? '—'}</td>
<td>${e.round_id ?? '—'}</td>
<td>${fmtDate(e.created_at)}</td>
</tr>
`).join('') || '<tr><td colspan="6" class="hint">Nessun evento registrato.</td></tr>';
} catch (e) {
toast('Errore nel caricamento audit log: ' + e.message, 'error');
}
}
document.getElementById('admin-token').addEventListener('keydown', (e) => {
if (e.key === 'Enter') adminLogin();
});
if (adminToken) {
callAdmin('GET', '/admin/config')
.then(() => { showDashboard(); return loadDashboard(); })
.catch(() => { sessionStorage.removeItem('plm_admin_token'); adminToken = null; });
}
</script>
</body>
+7
View File
@@ -185,6 +185,8 @@
<input id="reg-username" autocomplete="username">
<label for="reg-password">Password</label>
<input id="reg-password" type="password" autocomplete="new-password">
<label for="reg-password-confirm">Conferma password</label>
<input id="reg-password-confirm" type="password" autocomplete="new-password">
<button onclick="register()" id="register-btn">Crea account</button>
</div>
</section>
@@ -391,6 +393,11 @@ async function register() {
const btn = document.getElementById('register-btn');
const u = document.getElementById('reg-username').value;
const p = document.getElementById('reg-password').value;
const pConfirm = document.getElementById('reg-password-confirm').value;
if (p !== pConfirm) {
toast('Le password non coincidono.', 'error');
return;
}
await withLoading(btn, 'Creazione…', async () => {
try {
const data = await call('POST', '/auth/register', { username: u, password: p });
+7 -7
View File
@@ -9,9 +9,9 @@ from embit.finalizer import finalize_psbt
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from app.config import settings
from app.db.models import PendingTransaction, User
from app.electrum.client import ElectrumClient
from app.rounds.config import get_round_config
from app.wallet.hd import derive_pool_key, derive_user_key
from app.wallet.plm_network import PLM_MAINNET
from app.wallet.psbt_builder import RBF_SEQUENCE, estimate_vsize
@@ -26,14 +26,13 @@ class RbfError(Exception):
pass
def should_bump(pending: PendingTransaction, now: datetime, timeout_seconds: int | None = None) -> bool:
def should_bump(pending: PendingTransaction, now: datetime, timeout_seconds: int) -> bool:
"""Pure decision: has this pending tx been unconfirmed for longer than the
configured timeout? Kept separate from the I/O-heavy bump_fee() so it's
trivially unit-testable."""
timeout = timeout_seconds if timeout_seconds is not None else settings.rbf_timeout_seconds
configured timeout (RoundConfig.rbf_timeout_seconds)? Kept separate from the
I/O-heavy bump_fee() so it's trivially unit-testable."""
if pending.status != "pending":
return False
return now >= pending.broadcast_at.replace(tzinfo=timezone.utc) + timedelta(seconds=timeout)
return now >= pending.broadcast_at.replace(tzinfo=timezone.utc) + timedelta(seconds=timeout_seconds)
async def _signing_context(session: AsyncSession, pending: PendingTransaction) -> tuple:
@@ -145,10 +144,11 @@ class RbfBumper:
async def _tick(self, client: ElectrumClient) -> None:
now = datetime.now(timezone.utc)
async with self._session_factory() as session:
timeout_seconds = (await get_round_config(session)).rbf_timeout_seconds
candidates = (
await session.scalars(select(PendingTransaction).where(PendingTransaction.status == "pending"))
).all()
due = [p for p in candidates if should_bump(p, now)]
due = [p for p in candidates if should_bump(p, now, timeout_seconds=timeout_seconds)]
for pending in due:
async with self._session_factory() as session:
+11
View File
@@ -2,6 +2,7 @@ import os
from embit import script
from embit.bip32 import HDKey
from embit.ec import PrivateKey
from app.config import settings
from app.wallet.keystore import decrypt_xprv, encrypt_xprv
@@ -39,6 +40,16 @@ def derive_user_address(derivation_index: int) -> str:
return script.p2wpkh(pub).address(network=PLM_MAINNET)
def derive_user_wif(derivation_index: int) -> str:
"""Exports a user's raw private key (WIF) for manual server-side intervention
(e.g. sweeping funds back to a user, or out, if something gets stuck). This is
a custodial system — the server already holds the master key this is derived
from — but callers must still treat the result as a live secret: log access,
never persist it, never return it over an unauthenticated channel."""
key = derive_user_key(derivation_index)
return PrivateKey(key.secret, compressed=True, network=PLM_MAINNET).wif(network=PLM_MAINNET)
def derive_pool_key() -> HDKey:
"""The "indirizzo padre" from the flowchart: all bets are sent here, and
payouts are signed with this key. Reserved on branch 1 of the account (branch 0
+6 -5
View File
@@ -3,9 +3,9 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.log import write_audit_log
from app.config import settings
from app.db.models import PendingTransaction, User, UtxoEvent, Withdrawal
from app.electrum.client import ElectrumClient
from app.rounds.config import get_round_config
from app.wallet.balance import recompute_balance
from app.wallet.hd import derive_user_key
from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_signed_transaction
@@ -18,8 +18,9 @@ class WithdrawalError(Exception):
async def request_withdrawal(
session: AsyncSession, client: ElectrumClient, user: User, external_address: str, amount_sats: int
) -> Withdrawal:
if amount_sats < settings.min_amount_sats:
raise WithdrawalError(f"amount below the minimum of {settings.min_amount_sats} sats")
config = await get_round_config(session)
if amount_sats < config.min_amount_sats:
raise WithdrawalError(f"amount below the minimum of {config.min_amount_sats} sats")
unspent = (
await session.scalars(
@@ -41,7 +42,7 @@ async def request_withdrawal(
to_address=external_address,
amount_sats=amount_sats,
change_address=user.address,
fee_rate_sat_vb=settings.fee_rate_sat_vb,
fee_rate_sat_vb=config.fee_rate_sat_vb,
)
except InsufficientFundsError as exc:
raise WithdrawalError(str(exc)) from exc
@@ -69,7 +70,7 @@ async def request_withdrawal(
withdrawal_id=withdrawal.id,
user_id=user.id,
current_txid=built.txid,
fee_rate_sat_vb=settings.fee_rate_sat_vb,
fee_rate_sat_vb=config.fee_rate_sat_vb,
raw_tx_hex=built.raw_hex,
status="pending",
)
+49 -16
View File
@@ -7,28 +7,50 @@ server sia già avviato — vedi [running-the-server.md](running-the-server.md).
Il pannello admin è su **`https://<host>/admin`** — **non è collegato** da
nessun link nell'interfaccia utente (né in entrata né in uscita): ci si
arriva solo conoscendo l'URL. Non è protetto da login personale, ma da un
**token condiviso** (`ADMIN_TOKEN`, definito in `.env`).
arriva solo conoscendo l'URL. La pagina mostra solo un campo token finché non
accedi: non è protetta da login personale, ma da un **token condiviso**
(`ADMIN_TOKEN`, definito in `.env`).
Apri la pagina, incolla il valore di `ADMIN_TOKEN` nel campo "Admin token" e
usa i bottoni:
Incolla il valore di `ADMIN_TOKEN` e premi "Accedi" (o Invio): se il token è
valido, si apre la dashboard con una navbar in alto e carica automaticamente
tutte le sezioni — nessun bottone "Carica" separato. Il token resta in
`sessionStorage` (si perde chiudendo la tab/il browser); "Esci" torna alla
sola schermata di login.
- **"Carica configurazione attuale"** → mostra `fee_address` e
`bet_amount_sats` (in PLM) correnti
- **"Salva"** → aggiorna i valori nel database, effetto immediato, nessun
riavvio del server necessario
## Sezioni della dashboard
## Cosa si configura
- **Parametri** — configurazione operativa (vedi tabella sotto)
- **Utenti** — elenco utenti, saldo, accesso alla chiave privata
- **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.)
## Parametri
Tutti i parametri operativi/di business sono nella sezione "Parametri",
salvati nel database — modificabili in qualsiasi momento, effetto immediato,
**nessun riavvio del server necessario**. Non esiste alcuna variabile
d'ambiente equivalente: `.env` contiene solo segreti e configurazione di
infrastruttura (chiave master, JWT, Electrum, token admin), non parametri di
business — quelli si toccano solo da qui.
| Campo | Significato |
|---|---|
| **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, mostrato/impostato in PLM (internamente il backend lavora in sats: 1 PLM = 100.000.000 sats). |
| **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. |
| **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. |
| **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. |
`ROUND_DURATION_SECONDS` (durata del round) e `ROUND_COOLDOWN_SECONDS` (pausa
tra un round e il successivo, default 30s) **non** sono qui: sono variabili
d'ambiente in `.env`, non modificabili a runtime — per cambiarle serve
riavviare il server con il nuovo valore.
Tutti gli importi in PLM vengono convertiti in sats (1 PLM = 100.000.000 sats)
solo nella chiamata API — il backend lavora sempre in sats.
Su un'istanza nuova (mai avviata), questi campi partono con dei default
hardcoded nel codice (`RoundConfig` in `app/db/models.py`: bet 10 PLM, round
10 minuti, cooldown 30s, minimo 1 PLM, fee 1 sat/vB, RBF timeout 900s) — vanno
comunque rivisti e confermati dal pannello prima del primo utilizzo reale.
## Alternative all'interfaccia grafica
@@ -40,13 +62,24 @@ nell'header `X-Admin-Token`:
# leggere la configurazione
curl https://<host>/admin/config -H "X-Admin-Token: <ADMIN_TOKEN>"
# aggiornarla (importi in sats: 10 PLM = 1000000000)
# aggiornarla (importi in sats: 10 PLM = 1000000000; solo i campi passati vengono cambiati)
curl -X PUT https://<host>/admin/config \
-H "X-Admin-Token: <ADMIN_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"fee_address": "plm1q...", "bet_amount_sats": 1000000000}'
-d '{"fee_address": "plm1q...", "bet_amount_sats": 1000000000, "round_duration_seconds": 600}'
```
## Utenti e chiave privata
La card "Utenti" elenca id, username, indirizzo e saldo di ogni utente
registrato. Il bottone "Mostra" su ogni riga rivela la chiave privata (WIF)
di quell'utente, dietro conferma esplicita — serve per interventi manuali
(es. restituire fondi bloccati). **Ogni visualizzazione viene registrata
nell'audit log** (`admin_privkey_accessed`). Questo non introduce una nuova
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.
## Limiti noti
- Il token è unico e condiviso: non c'è identità per singolo admin né audit
+4 -2
View File
@@ -29,8 +29,10 @@ cp .env.example .env
| `ADMIN_TOKEN` | Token bearer richiesto sugli endpoint admin (header `X-Admin-Token`). | `python -c "import secrets; print(secrets.token_urlsafe(32))"` |
Le altre chiavi di `.env` (`DATABASE_URL`, `ELECTRUM_HOST`/`PORT`/`USE_SSL`,
`MASTER_KEY_PATH`, `ROUND_DURATION_SECONDS`) hanno default sensati in
`.env.example` — modificali se serve (es. round più corti per i test).
`MASTER_KEY_PATH`) hanno default sensati in `.env.example`. Nota: `.env`
contiene solo segreti e configurazione di infrastruttura — i parametri di
business (bet amount, durata round, fee, ecc.) si configurano dal pannello
admin dopo l'avvio, non qui — vedi [guida-admin.md](guida-admin.md).
**Non committare mai `.env`.** È già escluso da `.gitignore`.
@@ -0,0 +1,59 @@
"""add operational params to round_config
Revision ID: 53cc70d16e63
Revises: 274efdcbfbcc
Create Date: 2026-07-21 14:44:09.866407
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '53cc70d16e63'
down_revision: Union[str, Sequence[str], None] = '274efdcbfbcc'
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) with the same
# defaults app/config.py used before these became DB-editable; dropped right
# after so new rows go through the ORM defaults instead of a stale constant.
op.add_column(
'round_config', sa.Column('round_duration_seconds', sa.Integer(), nullable=False, server_default='600')
)
op.add_column(
'round_config', sa.Column('round_cooldown_seconds', sa.Integer(), nullable=False, server_default='30')
)
op.add_column(
'round_config',
sa.Column('min_amount_sats', sa.BigInteger(), nullable=False, server_default='100000000'),
)
op.add_column(
'round_config', sa.Column('fee_rate_sat_vb', sa.Integer(), nullable=False, server_default='1')
)
op.add_column(
'round_config', sa.Column('rbf_timeout_seconds', sa.Integer(), nullable=False, server_default='900')
)
with op.batch_alter_table('round_config') as batch_op:
batch_op.alter_column('round_duration_seconds', server_default=None)
batch_op.alter_column('round_cooldown_seconds', server_default=None)
batch_op.alter_column('min_amount_sats', server_default=None)
batch_op.alter_column('fee_rate_sat_vb', server_default=None)
batch_op.alter_column('rbf_timeout_seconds', server_default=None)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('round_config', 'rbf_timeout_seconds')
op.drop_column('round_config', 'fee_rate_sat_vb')
op.drop_column('round_config', 'min_amount_sats')
op.drop_column('round_config', 'round_cooldown_seconds')
op.drop_column('round_config', 'round_duration_seconds')
# ### end Alembic commands ###
+81
View File
@@ -1,4 +1,5 @@
import pytest
from cryptography.fernet import Fernet
from httpx import ASGITransport, AsyncClient
from app.config import settings
@@ -9,6 +10,13 @@ async def client(monkeypatch, tmp_path):
monkeypatch.setattr(settings, "database_url", f"sqlite+aiosqlite:///{tmp_path}/test.db")
monkeypatch.setattr(settings, "admin_token", "test-admin-token")
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 create_async_engine
@@ -19,6 +27,15 @@ async def client(monkeypatch, tmp_path):
db_base.AsyncSessionLocal = async_sessionmaker(db_base.engine, expire_on_commit=False)
# app.db.session did `from app.db.base import AsyncSessionLocal` at its own
# first import, which only copies the reference as it was at that moment —
# reassigning db_base.AsyncSessionLocal above doesn't reach it. get_session()
# looks up its module global at call time, so rebinding it here (every test)
# keeps it pointed at *this* test's engine instead of whichever ran first.
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)
@@ -62,3 +79,67 @@ async def test_admin_reads_and_updates_config(client):
resp = await client.get("/admin/config", headers=headers)
assert resp.json()["fee_address"] == "plm1qfeeaddress"
async def test_admin_lists_users(client):
from app.db import base as db_base
from app.db.models import User
from app.wallet.hd import derive_user_address
async with db_base.AsyncSessionLocal() as session:
session.add(
User(
username="alice",
password_hash="unused",
derivation_index=0,
address=derive_user_address(0),
cached_balance_sats=1_000_000_000,
)
)
await session.commit()
headers = {"X-Admin-Token": "test-admin-token"}
resp = await client.get("/admin/users", headers=headers)
assert resp.status_code == 200
body = resp.json()
assert len(body) == 1
assert body[0]["username"] == "alice"
assert body[0]["balance_sats"] == 1_000_000_000
async def test_admin_exports_user_privkey(client):
from embit.ec import PrivateKey
from app.db import base as db_base
from app.db.models import User
from app.wallet.hd import derive_user_address, derive_user_key
from app.wallet.plm_network import PLM_MAINNET
async with db_base.AsyncSessionLocal() as session:
user = User(
username="bob",
password_hash="unused",
derivation_index=1,
address=derive_user_address(1),
)
session.add(user)
await session.commit()
await session.refresh(user)
user_id = user.id
headers = {"X-Admin-Token": "test-admin-token"}
resp = await client.get(f"/admin/users/{user_id}/privkey", headers=headers)
assert resp.status_code == 200
body = resp.json()
expected_wif = PrivateKey(derive_user_key(1).secret, compressed=True, network=PLM_MAINNET).wif(
network=PLM_MAINNET
)
assert body["wif"] == expected_wif
assert body["address"] == derive_user_address(1)
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
+3 -2
View File
@@ -3,11 +3,12 @@ from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.config import settings
from app.db.base import Base
from app.db.models import Round
from app.rounds.service import get_active_round, open_new_round_if_needed
ROUND_COOLDOWN_SECONDS = 30 # matches RoundConfig.round_cooldown_seconds' column default
@pytest.fixture
async def session_factory():
@@ -72,7 +73,7 @@ async def test_withholds_new_round_during_cooldown(session_factory):
async def test_opens_new_round_once_cooldown_elapses(session_factory):
stale_close = datetime.now(timezone.utc) - timedelta(seconds=settings.round_cooldown_seconds + 1)
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))
await session.commit()
+3 -4
View File
@@ -4,9 +4,8 @@ import pytest
from sqlalchemy import select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.config import settings
from app.db.base import Base
from app.db.models import Round
from app.db.models import Round, RoundConfig
from app.rounds.scheduler import RoundScheduler
@@ -31,8 +30,8 @@ async def test_tick_survives_sqlite_naive_datetime_roundtrip(session_factory, mo
it directly against datetime.now(timezone.utc) and crashed with
"can't compare offset-naive and offset-aware datetimes" on every tick once a
round existed — this must not happen."""
monkeypatch.setattr(settings, "round_duration_seconds", 3600) # not due yet
async with session_factory() as session:
session.add(RoundConfig(fee_address="", round_duration_seconds=3600)) # not due yet
session.add(Round(status="open", opened_at=datetime.now(timezone.utc)))
await session.commit()
@@ -41,9 +40,9 @@ async def test_tick_survives_sqlite_naive_datetime_roundtrip(session_factory, mo
async def test_tick_closes_round_with_no_participants_once_due(session_factory, monkeypatch):
monkeypatch.setattr(settings, "round_duration_seconds", 1)
past = datetime.now(timezone.utc) - timedelta(seconds=10)
async with session_factory() as session:
session.add(RoundConfig(fee_address="", round_duration_seconds=1))
session.add(Round(status="open", opened_at=past))
await session.commit()
+3 -2
View File
@@ -19,6 +19,7 @@ class FakeElectrumClient:
EXTERNAL_ADDRESS = "plm1qqph9qup2mp7w7g5nlsdhdc9m2pp44ampzw0ctx"
MIN_AMOUNT_SATS = 100_000_000 # matches RoundConfig.min_amount_sats' column default
@pytest.fixture
@@ -85,7 +86,7 @@ async def test_withdrawal_rejects_amount_below_minimum(session_factory):
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(WithdrawalError, match="minimum"):
await request_withdrawal(session, client, user, EXTERNAL_ADDRESS, settings.min_amount_sats - 1)
await request_withdrawal(session, client, user, EXTERNAL_ADDRESS, MIN_AMOUNT_SATS - 1)
async def test_withdrawal_rejects_insufficient_balance(session_factory):
@@ -95,4 +96,4 @@ async def test_withdrawal_rejects_insufficient_balance(session_factory):
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(WithdrawalError, match="insufficient balance"):
await request_withdrawal(session, client, user, EXTERNAL_ADDRESS, settings.min_amount_sats)
await request_withdrawal(session, client, user, EXTERNAL_ADDRESS, MIN_AMOUNT_SATS)