Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8627f3fa0c | ||
|
|
4b510f312f | ||
|
|
9e1d7da22d | ||
|
|
7e4b603ae3 | ||
|
|
669c3fb714 | ||
|
|
b52a8023de | ||
|
|
f23640b6b3 | ||
|
|
03cdffb34d |
No files matched your search
@@ -8,12 +8,14 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
|
||||
|
||||
## Project status
|
||||
|
||||
All 10 build-order stages from `/home/davide/.claude/plans/scalable-mixing-sloth.md` are code-complete and unit-tested (49 tests green): project skeleton, DB schema + Alembic migrations, auth, HD wallet derivation, Electrum client, deposit detection, bet flow, round/draw engine, payout, withdrawal, RBF fee-bump, admin config + audit log.
|
||||
All 10 build-order stages from `/home/davide/.claude/plans/scalable-mixing-sloth.md` are code-complete and unit-tested (54 tests green): project skeleton, DB schema + Alembic migrations, auth, HD wallet derivation, Electrum client, deposit detection, bet flow, round/draw engine, payout, withdrawal, RBF fee-bump, admin config + audit log. Beyond the original 10 stages: a Docker + Caddy deployment (see below), a full admin dashboard (`/admin`), and a static test UI for the user-facing flow (`/`).
|
||||
|
||||
Real-money verification on mainnet, done so far: registration + address derivation, deposit crediting (1-conf), a real 10 PLM bet (broadcast, confirmed, change credited back), and a full round cycle — close → draw (real block hash) → payout (70/30 split, exact sat math verified against the broadcast tx) → confirmation → round closed → next round auto-opened. Withdrawal and the RBF bump path are unit-tested but have never been exercised against a live broadcast. See "Known gaps" below before treating this as production-ready.
|
||||
|
||||
Before writing code, always read [flowchart.mmd](flowchart.mmd) in full: every node in the diagram corresponds to a behavior that must be implemented exactly as described, including the labels on the edges (conditions, retries, loops).
|
||||
|
||||
Human-facing guides live in [docs/](docs/) (Italian, per explicit request — an exception to this file's English-only rule below): [setup.md](docs/setup.md), [running-the-server.md](docs/running-the-server.md), [guida-utente.md](docs/guida-utente.md), [guida-admin.md](docs/guida-admin.md).
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
@@ -60,8 +62,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**: 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.
|
||||
- **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.
|
||||
|
||||
## PLM network parameters
|
||||
|
||||
@@ -78,10 +80,10 @@ Mainnet:
|
||||
|
||||
## MVP business parameters
|
||||
|
||||
- Fixed bet cost: **10 PLM** per round.
|
||||
- Prize split: 70% winner / 30% fees (fee address configurable in DB).
|
||||
- Minimum deposit/withdrawal amount: **1 PLM** (business-friendly floor, above the network's technical dust limit).
|
||||
- Confirmations required for all tx types (deposit, bet, payout, withdrawal): **1**.
|
||||
- Bet cost per round: **10 PLM** by default, admin-configurable (`RoundConfig.bet_amount_sats`) — not a fixed constant.
|
||||
- Prize split: **70% winner / 30% fees**, hardcoded in `rounds/scheduler.py` (`winner_share = pool_amount_sats * 70 // 100`) — unlike bet amount, this ratio is not in `RoundConfig` and would need a code change, not an admin-panel edit.
|
||||
- Minimum withdrawal amount: **1 PLM** by default, admin-configurable (`RoundConfig.min_amount_sats`) — a business-friendly floor, above the network's technical dust limit. Deposits have no server-side minimum check.
|
||||
- Confirmations required for all tx types (deposit, bet, payout, withdrawal): **1**, hardcoded in `tx/confirmation.py` — not configurable, per the design decision below.
|
||||
|
||||
## What is PLM Lottery
|
||||
|
||||
@@ -94,11 +96,20 @@ 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). 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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
## 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:
|
||||
|
||||
- **`/` (`app/static/index.html`)**: the end-user test UI. Register/login, then a menu-driven dashboard (Deposito with a QR code of the address via `GET /qr/{address}`, Bet, Prelievo) with a persistent round-status card (`GET /rounds/current`: id/status/timer/participant count/jackpot) above the menu.
|
||||
- **`/admin` (`app/static/admin.html`)**: gated by a token screen (not a real login — just checks `X-Admin-Token` against `ADMIN_TOKEN` from `.env`), then a navbar-driven dashboard with five sections, each backed by its own `/admin/*` endpoint (`app/api/routes/admin.py`): Parametri (`RoundConfig` CRUD), Utenti (list + per-user WIF privkey export, audit-logged), Round (history), Transazioni pendenti (in-flight RBF candidates), Audit log. **`/admin` is deliberately not linked from `/`** in either direction — reachable only by knowing the URL.
|
||||
|
||||
Both pages talk to the same JSON API everything else uses; there's no separate "admin API" vs "user API" boundary beyond the `require_admin` dependency.
|
||||
|
||||
## Non-obvious domain decisions
|
||||
|
||||
These choices were made explicitly during design (not derivable from reading a single file) and must be respected in any implementation:
|
||||
@@ -107,6 +118,8 @@ These choices were made explicitly during design (not derivable from reading a s
|
||||
- The user's personal deposit address always doubles as the winnings-receiving address: there is no separate "winner address".
|
||||
- 1 confirmation is the chosen threshold for all tx types (deposits, bets, payouts, withdrawals): don't introduce different thresholds (e.g. 3 or 6 confirmations) without an explicit decision.
|
||||
- The draw algorithm (node R) is deliberately simple and should be treated as a replaceable/pluggable component, not the final design — don't architect around its current implementation.
|
||||
- The admin panel can export any user's raw WIF private key (`GET /admin/users/{id}/privkey`, `app/wallet/hd.py:derive_user_wif`). This is intentional, not a vulnerability to fix: the server already holds the master key everything derives from (custodial by design, see above), so this only exposes through the API something an operator could already do via a script. Every access is written to `audit_log` (`admin_privkey_accessed`) — don't remove that logging when touching this endpoint.
|
||||
- RBF fee bumps are paid by whoever's change output the tx pays back to — the user for bets/withdrawals, the pool for payouts — never by the fixed counterparty amount (recipient/winner/fee-address outputs are untouched; only the sender's own change shrinks). See `bump_fee` in `app/tx/broadcast.py`.
|
||||
|
||||
## Known gaps / TODO
|
||||
|
||||
@@ -116,8 +129,8 @@ Not blockers for reading the code, but must be addressed before this is producti
|
||||
- **RBF bump only handles one case**: a single change output, paying back to the tx's own sender address, large enough to absorb the fee increase. No additional-input selection fallback — an exact-amount tx (no change) or a change output too small to absorb the bump raises `RbfError` and needs manual operator intervention. Documented in `tx/broadcast.py`.
|
||||
- **Payout retry**: if `_trigger_payout` fails (e.g. insufficient pool UTXOs, Electrum disconnected), it just logs and returns — the round stays stuck in `paying_out` with no automatic retry.
|
||||
- **Withdrawal and RBF bump have never been exercised against a live broadcast** — only deposit and bet flow are verified end-to-end with real PLM as of this commit.
|
||||
- **No user-facing history endpoints** (list my bets / withdrawals / past rounds) — only `/users/me` (balance) exists.
|
||||
- **No deployment setup**: no Dockerfile, process manager, or reconnect/supervision beyond the in-process asyncio tasks. Currently only run manually via `uvicorn` in a dev venv.
|
||||
- **Admin auth is a single shared bearer token** (`ADMIN_TOKEN`, `X-Admin-Token` header) — no per-admin identity or audit trail of who changed config.
|
||||
- **No rate limiting / abuse protection** on any endpoint (register, bet, withdrawal).
|
||||
- **No user-facing history endpoints** (list my own bets / withdrawals / past rounds) — a user still only has `/users/me` (balance). The admin side now has this (`/admin/rounds`, `/admin/pending-transactions`, `/admin/audit-log`), but there's no equivalent scoped to "my own history" for a logged-in user.
|
||||
- **Admin auth is a single shared bearer token** (`ADMIN_TOKEN`, `X-Admin-Token` header) — no per-admin identity or audit trail of *who* changed config (the `audit_log` table records *what* changed, not which operator did it). This token now gates a lot more than config (user list, private key export, round/audit history), so its blast radius if leaked is correspondingly larger.
|
||||
- **No rate limiting / abuse protection** on any endpoint (register, bet, withdrawal, admin).
|
||||
- No automated integration tests against a live Electrum connection — all live-network verification so far has been manual (ad hoc scripts + real mainnet transactions), not part of the `pytest` suite.
|
||||
- **`docker-compose.yml`'s `restart: unless-stopped`** on the app container means a crash mid-round auto-restarts straight into the scheduler-resume gap above — see the Deployment section.
|
||||
@@ -0,0 +1,69 @@
|
||||
# PLM Lottery
|
||||
|
||||
A periodic-round lottery system built on PLM, a Bitcoin-like coin (mainnet).
|
||||
Each user gets a dedicated server-derived P2WPKH address; they deposit PLM to
|
||||
that address, place a fixed-cost bet to enter the current round, and when the
|
||||
round closes a winner is drawn who receives 70% of the prize pool (the
|
||||
remaining 30% goes to fees).
|
||||
|
||||
This is a **custodial** system: private keys are generated and held
|
||||
server-side, encrypted at rest. See [CLAUDE.md](CLAUDE.md) for the full
|
||||
architecture, domain decisions, and known gaps before treating this as
|
||||
production-ready.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp .env.example .env # then fill in the generated secrets, see docs/setup.md
|
||||
python3 -m venv .venv && source .venv/bin/activate
|
||||
pip install -e ".[dev]"
|
||||
PYTHONPATH=. python scripts/generate_master_key.py
|
||||
alembic upgrade head
|
||||
uvicorn app.main:app --reload --port 8123
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8123/` for the test UI, `http://127.0.0.1:8123/admin`
|
||||
for the admin dashboard, `http://127.0.0.1:8123/docs` for the interactive API
|
||||
docs.
|
||||
|
||||
Or run the whole stack (app + Caddy reverse proxy with automatic TLS) via
|
||||
Docker:
|
||||
|
||||
```bash
|
||||
mkdir -p data/db data/keys data/logs
|
||||
docker compose run --rm app python scripts/generate_master_key.py
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
See [docs/setup.md](docs/setup.md) and
|
||||
[docs/running-the-server.md](docs/running-the-server.md) for the full
|
||||
walkthrough (both workflows, dev vs. production TLS).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [CLAUDE.md](CLAUDE.md) — architecture, commands, domain decisions, known gaps (for anyone/anything working on the code)
|
||||
- [flowchart.mmd](flowchart.mmd) — the source-of-truth flow diagram the implementation follows node-by-node
|
||||
- [docs/setup.md](docs/setup.md) — one-time setup (secrets, master key, migrations)
|
||||
- [docs/running-the-server.md](docs/running-the-server.md) — how to launch it (local venv vs. Docker+Caddy, dev vs. production TLS)
|
||||
- [docs/guida-utente.md](docs/guida-utente.md) — end-user guide to the test UI (Italian)
|
||||
- [docs/guida-admin.md](docs/guida-admin.md) — admin dashboard guide (Italian)
|
||||
|
||||
## Tech stack
|
||||
|
||||
Python (FastAPI, SQLAlchemy async + Alembic, Argon2 + JWT auth), Electrum
|
||||
protocol for PLM network access (no full node), Docker + Caddy for
|
||||
deployment. See [CLAUDE.md](CLAUDE.md#tech-stack-mvp) for the complete list
|
||||
and the reasoning behind each choice.
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
python -m pytest # all tests
|
||||
python -m pytest tests/unit/test_hd.py # one file
|
||||
```
|
||||
|
||||
54 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
|
||||
deposits, withdrawals, the round/draw engine, RBF fee-bumping, and admin
|
||||
config. No automated integration tests against a live Electrum connection —
|
||||
mainnet verification so far has been manual (see CLAUDE.md's "Project
|
||||
status").
|
||||
+16
-18
@@ -20,6 +20,18 @@ async def require_admin(x_admin_token: str = Header(default="")) -> None:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid admin token")
|
||||
|
||||
|
||||
_CONFIG_FIELDS = (
|
||||
"fee_address",
|
||||
"bet_amount_sats",
|
||||
"round_duration_seconds",
|
||||
"round_cooldown_seconds",
|
||||
"min_amount_sats",
|
||||
"fee_rate_sat_vb",
|
||||
"rbf_timeout_seconds",
|
||||
"draw_animation_seconds",
|
||||
)
|
||||
|
||||
|
||||
class RoundConfigResponse(BaseModel):
|
||||
fee_address: str
|
||||
bet_amount_sats: int
|
||||
@@ -28,6 +40,7 @@ class RoundConfigResponse(BaseModel):
|
||||
min_amount_sats: int
|
||||
fee_rate_sat_vb: int
|
||||
rbf_timeout_seconds: int
|
||||
draw_animation_seconds: int
|
||||
|
||||
|
||||
class RoundConfigUpdate(BaseModel):
|
||||
@@ -38,18 +51,11 @@ class RoundConfigUpdate(BaseModel):
|
||||
min_amount_sats: int | None = None
|
||||
fee_rate_sat_vb: int | None = None
|
||||
rbf_timeout_seconds: int | None = None
|
||||
draw_animation_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,
|
||||
)
|
||||
return RoundConfigResponse(**{field: getattr(config, field) for field in _CONFIG_FIELDS})
|
||||
|
||||
|
||||
@router.get("/config", response_model=RoundConfigResponse, dependencies=[Depends(require_admin)])
|
||||
@@ -64,15 +70,7 @@ async def update_config(
|
||||
body: RoundConfigUpdate, session: AsyncSession = Depends(get_session)
|
||||
) -> RoundConfigResponse:
|
||||
config = await get_round_config(session)
|
||||
for field in (
|
||||
"fee_address",
|
||||
"bet_amount_sats",
|
||||
"round_duration_seconds",
|
||||
"round_cooldown_seconds",
|
||||
"min_amount_sats",
|
||||
"fee_rate_sat_vb",
|
||||
"rbf_timeout_seconds",
|
||||
):
|
||||
for field in _CONFIG_FIELDS:
|
||||
value = getattr(body, field)
|
||||
if value is not None:
|
||||
setattr(config, field, value)
|
||||
|
||||
@@ -21,6 +21,9 @@ class CurrentRoundResponse(BaseModel):
|
||||
participant_count: int = 0
|
||||
bet_amount_sats: int
|
||||
jackpot_sats: int = 0
|
||||
draw_animation_seconds: int
|
||||
winner_user_id: int | None = None
|
||||
winner_amount_sats: int | None = None
|
||||
|
||||
|
||||
@router.get("/current", response_model=CurrentRoundResponse)
|
||||
@@ -29,7 +32,9 @@ async def current_round(session: AsyncSession = Depends(get_session)) -> Current
|
||||
round_ = await get_active_round(session)
|
||||
if round_ is None:
|
||||
await session.commit()
|
||||
return CurrentRoundResponse(bet_amount_sats=config.bet_amount_sats)
|
||||
return CurrentRoundResponse(
|
||||
bet_amount_sats=config.bet_amount_sats, draw_animation_seconds=config.draw_animation_seconds
|
||||
)
|
||||
|
||||
participant_count = await session.scalar(
|
||||
select(func.count()).select_from(RoundParticipant).where(RoundParticipant.round_id == round_.id)
|
||||
@@ -46,4 +51,7 @@ async def current_round(session: AsyncSession = Depends(get_session)) -> Current
|
||||
participant_count=participant_count,
|
||||
bet_amount_sats=config.bet_amount_sats,
|
||||
jackpot_sats=participant_count * config.bet_amount_sats,
|
||||
draw_animation_seconds=config.draw_animation_seconds,
|
||||
winner_user_id=round_.winner_user_id,
|
||||
winner_amount_sats=round_.winner_amount_sats,
|
||||
)
|
||||
@@ -8,6 +8,7 @@ router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class MeResponse(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
address: str
|
||||
balance_sats: int
|
||||
@@ -15,4 +16,6 @@ class MeResponse(BaseModel):
|
||||
|
||||
@router.get("/me", response_model=MeResponse)
|
||||
async def me(user: User = Depends(get_current_user)) -> MeResponse:
|
||||
return MeResponse(username=user.username, address=user.address, balance_sats=user.cached_balance_sats)
|
||||
return MeResponse(
|
||||
id=user.id, username=user.username, address=user.address, balance_sats=user.cached_balance_sats
|
||||
)
|
||||
@@ -87,6 +87,11 @@ class RoundConfig(Base):
|
||||
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)
|
||||
# Purely a frontend cue: the minimum time the "estrazione in corso" animation
|
||||
# plays for on every user's dashboard before the winner can be revealed. Does
|
||||
# NOT gate the actual draw, which still waits for a real confirmed block for
|
||||
# its entropy (rounds/scheduler.py) — that can take longer than this value.
|
||||
draw_animation_seconds: Mapped[int] = mapped_column(default=20)
|
||||
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)
|
||||
|
||||
@@ -77,6 +77,10 @@ class RoundScheduler:
|
||||
round_ = await session.get(Round, round_id)
|
||||
round_.status = "closing"
|
||||
round_.closed_at = datetime.now(timezone.utc)
|
||||
# Committed on its own so "closing" is actually observable (e.g. by
|
||||
# /rounds/current) instead of being overwritten in memory by "closed"
|
||||
# or "drawing" below before ever reaching the database.
|
||||
await session.commit()
|
||||
|
||||
participants = (
|
||||
await session.scalars(
|
||||
|
||||
@@ -211,6 +211,8 @@
|
||||
<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-draw-animation">Durata animazione estrazione (secondi)</label>
|
||||
<input id="admin-draw-animation" inputmode="numeric" placeholder="es. 20">
|
||||
<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>
|
||||
@@ -391,6 +393,7 @@ async function adminLoadConfig() {
|
||||
document.getElementById('admin-bet-amount').value = data.bet_amount_sats / SATS_PER_PLM;
|
||||
document.getElementById('admin-round-duration').value = data.round_duration_seconds;
|
||||
document.getElementById('admin-round-cooldown').value = data.round_cooldown_seconds;
|
||||
document.getElementById('admin-draw-animation').value = data.draw_animation_seconds;
|
||||
document.getElementById('admin-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;
|
||||
@@ -409,6 +412,7 @@ async function adminSave() {
|
||||
bet_amount_sats: Math.round(betAmountPlm * SATS_PER_PLM),
|
||||
round_duration_seconds: parseInt(document.getElementById('admin-round-duration').value, 10),
|
||||
round_cooldown_seconds: parseInt(document.getElementById('admin-round-cooldown').value, 10),
|
||||
draw_animation_seconds: parseInt(document.getElementById('admin-draw-animation').value, 10),
|
||||
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),
|
||||
|
||||
+106
-7
@@ -140,6 +140,19 @@
|
||||
|
||||
.hidden { display: none !important; }
|
||||
|
||||
.draw-state { display: none; text-align: center; padding: 8px 0 4px; }
|
||||
.draw-state.active { display: block; }
|
||||
.draw-spinner {
|
||||
width: 40px; height: 40px; margin: 0 auto 10px;
|
||||
border: 3px solid var(--color-border); border-top-color: var(--color-primary);
|
||||
border-radius: 50%; animation: spin 900ms linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.draw-state .draw-label { font-weight: 600; font-size: 0.95rem; }
|
||||
.draw-result { font-size: 1.05rem; font-weight: 700; padding: 6px 0; }
|
||||
.draw-result.win { color: var(--color-success); }
|
||||
.draw-result.lose { color: var(--color-muted-foreground); }
|
||||
|
||||
#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;
|
||||
@@ -201,11 +214,11 @@
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="row-between">
|
||||
<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>
|
||||
</div>
|
||||
<div class="row-between" style="margin-top:10px">
|
||||
<div class="row-between" style="margin-top:10px" id="round-stats-row">
|
||||
<div>
|
||||
<div class="hint" style="margin-bottom:2px">Giocatori</div>
|
||||
<span class="mono" id="round-players">—</span>
|
||||
@@ -215,6 +228,13 @@
|
||||
<span class="mono" id="round-jackpot">—</span> <span class="balance-unit">PLM</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="draw-state" id="draw-state">
|
||||
<div class="draw-spinner"></div>
|
||||
<div class="draw-label">Estrazione del vincitore in corso…</div>
|
||||
</div>
|
||||
|
||||
<div class="hidden" id="draw-result"></div>
|
||||
</div>
|
||||
|
||||
<nav class="menu" aria-label="Sezioni">
|
||||
@@ -337,7 +357,7 @@ function switchPanel(name) {
|
||||
|
||||
let roundCloseAt = null;
|
||||
let roundTimerInterval = null;
|
||||
let roundPollInterval = null;
|
||||
let roundPollTimeout = null;
|
||||
|
||||
const ROUND_STATUS_LABELS = {
|
||||
open: 'aperto',
|
||||
@@ -346,6 +366,15 @@ const ROUND_STATUS_LABELS = {
|
||||
paying_out: 'pagamento in corso',
|
||||
};
|
||||
|
||||
const DRAWING_STATUSES = ['closing', 'drawing', 'paying_out'];
|
||||
|
||||
// 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
|
||||
|
||||
function updateRoundTimer() {
|
||||
const el = document.getElementById('round-timer');
|
||||
if (!roundCloseAt) { el.textContent = '--:--'; return; }
|
||||
@@ -355,6 +384,30 @@ function updateRoundTimer() {
|
||||
el.textContent = mm + ':' + ss;
|
||||
}
|
||||
|
||||
function showDrawingState() {
|
||||
document.getElementById('round-normal-row').classList.add('hidden');
|
||||
document.getElementById('round-stats-row').classList.add('hidden');
|
||||
document.getElementById('draw-state').classList.add('active');
|
||||
document.getElementById('draw-result').classList.add('hidden');
|
||||
}
|
||||
|
||||
function showResultState(html, cls) {
|
||||
document.getElementById('round-normal-row').classList.add('hidden');
|
||||
document.getElementById('round-stats-row').classList.add('hidden');
|
||||
document.getElementById('draw-state').classList.remove('active');
|
||||
const el = document.getElementById('draw-result');
|
||||
el.className = 'draw-result ' + cls;
|
||||
el.innerHTML = html;
|
||||
el.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function showNormalState() {
|
||||
document.getElementById('round-normal-row').classList.remove('hidden');
|
||||
document.getElementById('round-stats-row').classList.remove('hidden');
|
||||
document.getElementById('draw-state').classList.remove('active');
|
||||
document.getElementById('draw-result').classList.add('hidden');
|
||||
}
|
||||
|
||||
async function refreshRound() {
|
||||
try {
|
||||
const data = await call('GET', '/rounds/current');
|
||||
@@ -365,7 +418,48 @@ async function refreshRound() {
|
||||
document.getElementById('round-jackpot').textContent = data.jackpot_sats / SATS_PER_PLM;
|
||||
roundCloseAt = data.closes_at ? new Date(data.closes_at) : null;
|
||||
updateRoundTimer();
|
||||
} catch (e) {}
|
||||
|
||||
const isDrawing = data.round_id && DRAWING_STATUSES.includes(data.status);
|
||||
|
||||
if (isDrawing) {
|
||||
if (!(data.round_id in drawStartedAt)) drawStartedAt[data.round_id] = Date.now();
|
||||
const elapsedMs = Date.now() - drawStartedAt[data.round_id];
|
||||
const minMs = data.draw_animation_seconds * 1000;
|
||||
|
||||
if (data.winner_user_id != null && elapsedMs >= minMs && !revealedRounds.has(data.round_id)) {
|
||||
revealedRounds.add(data.round_id);
|
||||
activeResultRoundId = data.round_id;
|
||||
if (myUserId != null && data.winner_user_id === myUserId) {
|
||||
const won = (data.winner_amount_sats / SATS_PER_PLM);
|
||||
showResultState('🎉 Hai vinto! +' + won + ' PLM', 'win');
|
||||
toast('Hai vinto il round #' + data.round_id + '! +' + won + ' PLM', 'success');
|
||||
} else {
|
||||
showResultState('Non hai vinto questa volta.', 'lose');
|
||||
}
|
||||
} else if (!revealedRounds.has(data.round_id)) {
|
||||
showDrawingState();
|
||||
}
|
||||
} 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;
|
||||
showNormalState();
|
||||
} else if (!data.round_id && activeResultRoundId == null) {
|
||||
// nothing has ever been revealed and there's no active round — plain empty state
|
||||
showNormalState();
|
||||
}
|
||||
// else: no active round right now, but we just revealed a result for the last
|
||||
// one — keep it on screen through the cooldown gap instead of flashing back to
|
||||
// "Nessun round attivo".
|
||||
|
||||
scheduleNextRoundPoll(isDrawing);
|
||||
} catch (e) {
|
||||
scheduleNextRoundPoll(false);
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleNextRoundPoll(fast) {
|
||||
clearTimeout(roundPollTimeout);
|
||||
roundPollTimeout = setTimeout(refreshRound, fast ? 3000 : 15000);
|
||||
}
|
||||
|
||||
function showDashboard() {
|
||||
@@ -377,9 +471,7 @@ function showDashboard() {
|
||||
refreshMe();
|
||||
refreshRound();
|
||||
clearInterval(roundTimerInterval);
|
||||
clearInterval(roundPollInterval);
|
||||
roundTimerInterval = setInterval(updateRoundTimer, 1000);
|
||||
roundPollInterval = setInterval(refreshRound, 15000);
|
||||
}
|
||||
|
||||
function persistSession(data, u) {
|
||||
@@ -429,8 +521,12 @@ async function login() {
|
||||
function logout() {
|
||||
localStorage.clear();
|
||||
token = username = address = null;
|
||||
myUserId = null;
|
||||
activeResultRoundId = null;
|
||||
revealedRounds.clear();
|
||||
for (const key of Object.keys(drawStartedAt)) delete drawStartedAt[key];
|
||||
clearInterval(roundTimerInterval);
|
||||
clearInterval(roundPollInterval);
|
||||
clearTimeout(roundPollTimeout);
|
||||
document.getElementById('dashboard-section').classList.add('hidden');
|
||||
document.getElementById('auth-section').classList.remove('hidden');
|
||||
}
|
||||
@@ -444,11 +540,14 @@ async function copyAddress() {
|
||||
}
|
||||
}
|
||||
|
||||
let myUserId = null;
|
||||
|
||||
async function refreshMe() {
|
||||
const btn = document.getElementById('refresh-btn');
|
||||
await withLoading(btn, '…', async () => {
|
||||
try {
|
||||
const data = await call('GET', '/users/me');
|
||||
myUserId = data.id;
|
||||
document.getElementById('dash-balance').textContent = data.balance_sats / SATS_PER_PLM;
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
|
||||
+36
-1
@@ -40,6 +40,7 @@ business — quelli si toccano solo da qui.
|
||||
| **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. |
|
||||
| **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. |
|
||||
| **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. |
|
||||
@@ -49,9 +50,43 @@ 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
|
||||
10 minuti, cooldown 30s, animazione estrazione 20s, minimo 1 PLM, fee 1
|
||||
sat/vB, RBF timeout 900s) — vanno
|
||||
comunque rivisti e confermati dal pannello prima del primo utilizzo reale.
|
||||
|
||||
**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
|
||||
sempre **chi ha originato la transazione**, non il destinatario: per bet e
|
||||
prelievi è l'utente stesso (gli torna un resto più piccolo), per i payout è
|
||||
il pool (il resto che torna all'indirizzo pool si riduce) — la quota del
|
||||
vincitore e quella delle fee, già fissate, non vengono mai toccate. Se non
|
||||
c'è un resto abbastanza grande da assorbire l'aumento, il bump fallisce e
|
||||
resta un intervento manuale (vedi "Limiti noti").
|
||||
|
||||
## Round
|
||||
|
||||
La sezione "Round" mostra lo storico (`GET /admin/rounds`, ultimi 50 per
|
||||
default): id, stato, orario di apertura, vincitore (username), importo del
|
||||
pool, importo vinto, importo di fee, txid del payout — tutti in PLM salvo il
|
||||
txid.
|
||||
|
||||
## Transazioni pendenti
|
||||
|
||||
`GET /admin/pending-transactions` elenca bet, payout e prelievi ancora senza
|
||||
conferma: tipo, stato, txid corrente, fee rate usata, numero di tentativi
|
||||
(si incrementa a ogni bump RBF) e orario dell'ultima trasmissione. Una riga
|
||||
che resta qui a lungo, con `attempt_count` che sale, indica una transazione
|
||||
in difficoltà — vedi "Limiti noti" sul fallback RBF.
|
||||
|
||||
## Audit log
|
||||
|
||||
`GET /admin/audit-log` elenca gli ultimi 200 eventi registrati dal sistema
|
||||
(tipo evento, payload JSON, utente/round coinvolti, timestamp): bet
|
||||
piazzate, payout inviati, round chiusi, configurazione modificata, accessi
|
||||
alle chiavi private, ecc. È il primo posto da controllare per ricostruire
|
||||
cosa è successo dopo un problema.
|
||||
|
||||
## Alternative all'interfaccia grafica
|
||||
|
||||
Le stesse operazioni si possono fare da terminale o da Swagger UI
|
||||
|
||||
@@ -32,6 +32,26 @@ Dopo l'accesso vedi, in ordine:
|
||||
30% in fee)
|
||||
3. **Menu di navigazione** con tre 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 vincitore è determinato, l'animazione lascia spazio a un
|
||||
messaggio:
|
||||
- **"🎉 Hai vinto! +N PLM"** se sei tu il vincitore — l'importo ti verrà
|
||||
accreditato non appena la transazione di payout viene confermata (il
|
||||
round successivo non si apre finché questo non accade)
|
||||
- **"Non hai vinto questa volta."** altrimenti
|
||||
|
||||
Il messaggio resta visibile fino all'apertura del round successivo.
|
||||
|
||||
### Deposito
|
||||
|
||||
- Il tuo **saldo interno** (accreditato dopo 1 conferma di rete) con bottone
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""add draw_animation_seconds to round_config
|
||||
|
||||
Revision ID: 1db52f3a7c67
|
||||
Revises: 53cc70d16e63
|
||||
Create Date: 2026-07-21 15:45:16.434942
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '1db52f3a7c67'
|
||||
down_revision: Union[str, Sequence[str], None] = '53cc70d16e63'
|
||||
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('draw_animation_seconds', sa.Integer(), nullable=False, server_default='20')
|
||||
)
|
||||
with op.batch_alter_table('round_config') as batch_op:
|
||||
batch_op.alter_column('draw_animation_seconds', server_default=None)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column('round_config', 'draw_animation_seconds')
|
||||
# ### end Alembic commands ###
|
||||
Reference in new issue
Block a user