Author SHA1 Message Date
davideandClaude Opus 5 025754c860 Cap participants per round and give the payout its own input limit (B-52)
The payout has to spend one pool UTXO per bet, so reusing MAX_TX_INPUTS (50)
for it made any round past ~50 players unpayable: select_utxos raised
too_many_inputs, the round stayed "paying_out" retrying every 60s forever, and
since no new round may open while one is active, the whole lottery stopped with
the pool stuck. The cap was being enforced on the payout side, i.e. discovered
once the money was already committed and there was no way back.

Two halves:

- select_utxos takes the cap as a parameter. Bets and withdrawals keep
  MAX_TX_INPUTS = 50, which protects a user from a fee that eats into the amount
  they are moving; the payout uses MAX_PAYOUT_TX_INPUTS = 500, where that
  argument doesn't apply — 400 inputs at 1 sat/vB cost ~0.00027 PLM out of the
  winner's 70% share. What actually bounds it is relay policy: 500 inputs is
  ~34 kvB against the 100 kvB standardness limit, and signing that many measures
  ~0.4s, once per round, inside a background task.

- place_bet refuses the 401st bet with a new round_full error (translated into
  all 7 languages), so "a round can always be paid out" is an invariant checked
  before any money moves. MAX_PARTICIPANTS_PER_ROUND sits below the input cap to
  leave the payout headroom for pool change from earlier rounds, and counts every
  participant row rather than only confirmed ones, since a failed bet frees a slot.

A round already wedged past the old cap now pays out on the next retry tick.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 16:21:33 +02:00
davideandClaude Opus 5 99d7a1ee00 Open the 2026-08-03 audit list (B-52 … B-72)
Third full-codebase audit, after the two earlier lists (B-01 … B-24 and
B-25 … B-49) were emptied and BUGS.md deleted. Analysis only — nothing is
fixed yet; each entry gets its own commit with its own regression test.

Branched off feature/bug-reports rather than main on purpose: the audit
describes this tree, /report-bug included (see B-68).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 15:51:00 +02:00
davideandClaude Sonnet 5 e5af15087c Polish /report-bug's visual design and refine bug report semantics
Design pass on the bug report page, staying inside the site's existing
design system (tokens, IBM Plex Sans, card/badge/pill components, stroke
icon set) rather than introducing a new one:
- A slim top bar (brand mark + back-to-home pill button + language switcher)
  replaces the bare floating heading, so the page reads as part of the
  product instead of an orphaned form.
- The "write in English" notice moves inside the form card, right above the
  field it applies to, and switches from the amber "needs attention" tone to
  an accent-tinted info tone, so it doesn't visually collide with the
  bug-status badges' own use of amber for "not read yet".
- "Your reports" is promoted to a proper labeled section with a cleaner row
  layout (truncated description with a title tooltip, compact date).
- A character counter on the description field.
- The back-to-home control is now a bordered pill with an arrow icon instead
  of a bare text link with a hardcoded "←", which also meant dropping that
  hardcoded arrow from all 7 translations.

Also, two content refinements based on feedback:
- Max description length dropped from 5000 to 2000 characters, enforced on
  both the textarea and the API's Pydantic validator.
- The "read" status is relabeled from a passive "read"/"letta" to an active
  "acknowledged"/"presa in carico" (and each other language's own equivalent
  helpdesk term) — it communicates a team is on it, not just that someone
  glanced at it. Only the label changed; the underlying "read" status value
  in the API/DB is untouched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 16:28:37 +02:00
davideandClaude Sonnet 5 a384b08044 Translate /report-bug into all 7 languages, require English in the report itself
The bug report form previously shipped as plain Italian only. It now shares
i18n.js with / (same TRANSLATIONS table, new bugReport.* keys in all 7
languages, own language switcher since the page has no navbar to hang one
off), so a non-Italian speaker can read the form and their own report
history in their language.

The description field itself still has to reach the admin panel in English
(operator-facing, untranslated by design), so the page states that
explicitly via a standing banner (bugReport.englishNotice) — translated
into every language rather than left in English, so the instruction to
write in English is itself understandable to whoever's reading it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 16:03:38 +02:00
davideandClaude Sonnet 5 ee4e845c89 Add user bug reporting with admin triage (open/read/resolved)
Turns the /report-bug placeholder into a real form (POST /bug-reports,
optionally attributed to the logged-in user) and adds a "Segnalazioni bug"
section to /admin to view and triage them. A logged-in reporter can also
check their own report's status via GET /bug-reports/mine, since anonymous
submissions have no user to show a history to.

Status is a three-state lifecycle (open -> read -> resolved) rather than a
plain boolean, so an admin can acknowledge a report distinctly from actually
fixing it. The schema went through two migrations because the first one
(add bug_reports table) had already been applied against the running
instance with a `resolved` boolean before the three-state design was
decided, so a follow-up migration backfills it into `status` instead of
rewriting already-applied history.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 15:50:40 +02:00
davideandClaude Sonnet 5 977bb762c7 Deduplicate the 70/30 prize split formula
pool_amount_sats * 70 // 100 was hardcoded identically in both
rounds/scheduler.py (the actual payout) and api/routes/rounds.py (the
advertised jackpot). They happened to agree, but nothing enforced it —
changing one without the other would have made GET /rounds/current's
jackpot silently diverge from the real payout. Extract winner_share()
into rounds/service.py as the single source of truth.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 15:04:33 +02:00
davideandClaude Sonnet 5 fe909bedcf Don't double-count a bet/withdrawal's own change in pending balance (B-51)
A change output's confirmation is credited by two independent, unordered
paths: the Electrum listener (event-driven, near-instant — credits it as
a UtxoEvent and folds it into cached_balance_sats via recompute_balance)
and this module's PendingTransaction.status flip (tx/confirmation.py,
polled every 10s). The listener normally wins that race, so for the gap
until the poller catches up, compute_pending_balance kept adding the same
change on top of a cached_balance_sats that already included it —
observed live as a user's displayed balance briefly jumping by exactly
the change amount before self-correcting a few seconds later.

Fix: skip any change output whose (txid, vout) already has a UtxoEvent
for this user before summing pending_change_sats.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 15:03:53 +02:00
davideandClaude Sonnet 5 9207bbcb8f Don't reveal the win banner before winner_amount_sats is known (B-50)
winner_user_id is committed as soon as the draw picks a winner, but
winner_amount_sats isn't set until the payout tx is built afterwards
(a real Electrum listunspent round-trip later, in a separate DB
transaction). The frontend revealed the win banner as soon as
winner_user_id appeared, formatPlm(undefined) rendered as "—", and
the toast/result box briefly showed "You won! +— PLM" until the next
poll picked up the real amount. Gate the winner's own reveal on
winner_amount_sats also being non-null; a loss can still reveal
immediately since it never needs the amount.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 15:03:42 +02:00
davide 5cfe2d6f95 Merge audit-2026-07-27: fix all 25 findings of the second audit
B-25 … B-49, each in its own commit with its own regression test — the suite
went from 139 to 253 tests. Also on this branch: Docker + Caddy security
headers, the API docs gate, admin endpoint limits, and the SSE gaps.
2026-07-27 23:37:12 +02:00
davide 0d2fef6502 Delete BUGS.md now that both audits' findings are closed
B-01 … B-49 are all fixed, so the file held no open work — only a history that
git already keeps. CLAUDE.md now explains how to resolve the B-nn markers left
throughout the code against that history, and repeats the caveat the empty list
does not carry on its own: no open findings is not the same as no bugs.

The one remaining reference, in an already-applied migration's docstring, is
left as the historical record it is.
2026-07-27 23:37:02 +02:00
davide e7f844b11f Publish an SSE update from the bet/withdrawal rollback paths (B-49)
_release_failed_bet and _release_failed_withdrawal restored the balance, freed
the reserved UTXOs and (for a bet) removed the participant without calling
broadcaster.publish(), so every dashboard kept showing the phantom bet and the
reduced balance until its next poll — while the success path and the
reconciler's own abandon path both published.

The two regression tests pre-open the round before subscribing: place_bet opens
one itself, and that publish() would otherwise satisfy the assertion whether or
not the rollback published anything.
2026-07-27 23:35:10 +02:00
davide 4c80c1c5bf Cap the number of inputs a transaction may spend (B-48)
select_utxos had no ceiling on input count, so an address fragmented into many
small deposits built an ever-larger transaction whose fee — deducted from the
amount being moved — eroded the bet's share of the pool or the withdrawn amount,
and past a few hundred inputs stopped being standard at all.

MAX_TX_INPUTS (50) now bounds the selection. Reaching the cap without covering
the target is reported as its own "too_many_inputs" code, distinct from having
no funds, with the cap carried in the error params for the 7 translations. The
payout path records the same distinction in its payout_failed audit reason.
2026-07-27 23:30:06 +02:00
29 changed files with 1774 additions and 107 deletions

No files matched your search

+353 -60
View File
@@ -1,75 +1,368 @@
# Known bugs
# BUGS.md — audit of 2026-08-03
A second full-codebase audit on 2026-07-27 found **25 further issues** (4 critical, 6 high,
7 medium, 8 low), listed below as B-48 … B-49. B-25 through B-47 are fixed (see "Previously
fixed" below) — no Critical-, High- or Medium-severity finding remains open; the remaining 2 are
Low/hygiene. The 139-test suite was green at the time of the audit, so none of these were caught
by existing coverage — every fix lands with a regression test (the twenty-three fixes so far
brought the suite from 139 to 248).
Third full-codebase audit, opened after the 2026-07-26 (B-01 … B-24) and
2026-07-27 (B-25 … B-49) lists were emptied. Numbering continues from the last
fixed finding, B-51.
The recurring pattern across the open findings is worth stating once: the code is rigorous
about the failure modes that have actually been hit, and silent about the ones that have not.
The payout phase is now fully recoverable; the "drawing" phase (waiting on a block) is now
observable (B-36) but still has no equivalent resume-after-restart — see "Known gaps / TODO"
in [CLAUDE.md](CLAUDE.md), which is also where other by-design limitations (single-shared-token
admin auth, single-process assumptions, no user-facing history, etc.) are documented.
Nothing in this list is fixed yet — it is the analysis pass only. Per CLAUDE.md's
convention each entry gets its own commit with its own regression test, and the
`B-nn` marker goes in a comment next to the fix so `git log --all --grep 'B-nn'`
finds it later.
State of the tree at audit time: 264 unit tests, all passing; `tests/integration/`
still empty; withdrawal and the RBF bump path still never live-broadcast.
Verified as *not* broken while looking for these: i18n key parity (146 identical
keys across all 7 languages), HTML escaping of every user-controlled value in
`admin.js`, the Alembic chain (linear, single head, matching `models.py`),
strictly-integer satoshi arithmetic everywhere, and `.gitignore` coverage of
secrets/DB/logs (nothing sensitive is tracked in git).
Severity is about consequence, not likelihood:
**critical** = money stuck or lost, or the lottery stops;
**high** = a security control that does not hold;
**medium** = wrong behaviour with a bounded blast radius;
**low** = drift between documentation and code.
---
## Low / hygiene
## Critical
### B-48 — No cap on input count in `select_utxos`
### B-52 — a round with more than ~50 participants deadlocks the platform permanently — **FIXED**
A user with hundreds of small UTXOs builds a huge transaction whose fee — deducted from the bet
amount — materially erodes their contribution to the pool, and it can exceed standardness
limits.
**Fix:** cap the selected inputs (e.g. 50) and fail with a translatable error suggesting a
consolidation, or consolidate the address automatically when the count crosses a threshold.
`app/wallet/psbt_builder.py:42` (`MAX_TX_INPUTS = 50`),
`app/rounds/scheduler.py:349-373`.
### B-49 — Rollback paths do not publish an SSE update
Every confirmed bet leaves exactly one UTXO on the pool address, and the payout's
selection target is `winner_share + commission`, i.e. the whole pool — so it needs
*all* n bet UTXOs as inputs. At n ≥ 51 `select_utxos` raises `too_many_inputs`,
`_trigger_payout` records `payout_failed`, and `_retry_payout_if_due` re-attempts
every 60 s forever. The round stays `paying_out`, so `open_new_round_if_needed`
never opens another round: the lottery halts, the pool is unspendable through the
normal path, and the only way out is a manual consolidation with the pool key.
`bets/service.py:_release_failed_bet` and `withdrawals/service.py:_release_failed_withdrawal`
restore the balance without calling `broadcaster.publish()`, so dashboards only find out on
their next poll.
**Fix:** one `broadcaster.publish()` at the end of each, as every other state-changing path
already does.
CLAUDE.md presents B-48's input cap purely as a fragmented *user* address problem.
The pool case is structural rather than an edge case: participant count alone
causes it, with the default bet amount and no unusual deposit pattern.
**Fixed** by moving the limit from where it was *discovered* to where it can still be
*enforced*:
- `select_utxos` takes the cap as a parameter. Bets and withdrawals keep
`MAX_TX_INPUTS = 50` (a user-protection limit: the fee comes out of the amount
they are moving); the payout uses the new `MAX_PAYOUT_TX_INPUTS = 500`, since the
pool's UTXO count is just the number of bets and the fee comes out of a 70% share
of the whole pool. 500 inputs is ~34 kvB, about a third of the 100 kvB relay
standardness budget; signing that many costs ~0.4 s of event loop, once per round,
in a background task.
- `place_bet` refuses the bet past `MAX_PARTICIPANTS_PER_ROUND = 400` with a new
`round_full` error (400, translated into all 7 languages), counting every
participant row rather than only the confirmed ones. The cap sits below the input
cap so the payout keeps headroom for pool change accumulated by earlier rounds.
The invariant is now "a round can always be paid out", enforced before any of the
401st player's money moves. A round already wedged with 51–499 participants pays out
by itself on the next `_retry_payout_if_due` tick.
Not addressed, and deliberately so: periodic pool consolidation, which is what would
be needed to go beyond this order of magnitude (see the audit discussion — it needs a
new PendingTransaction kind, must not run mid-round, and would force the payout math
to tolerate a pool short of its exact target). Raising these two constants covers
anything up to ~1400 participants first.
### B-53 — a bet can pay into the pool and still be left out of the draw
`app/bets/service.py:80-92`, `app/rounds/scheduler.py:101-129`.
`place_bet` commits its participant row as `building` *before* broadcasting
(the deliberate two-phase write of B-08). The scheduler counts in-flight
participants in one session and then reads the `confirmed` participants in a
second, separate session. A bet that passed `round_accepts_bets` just before the
deadline can commit its phase-1 row *between* those two queries: the count saw
zero, so the round draws and pays out, while the new row — not yet `confirmed` —
is excluded from `participants`. The bet then confirms normally and its sats land
in the pool address, credited to no round and to no participant. There is no
refund path, and the money silently improves the *next* round's payout change.
The window is one task switch wide, but both queries do real DB I/O, so it is
reachable rather than theoretical.
Fix directions: re-check the in-flight count inside the same transaction that
snapshots the participants (and abort the close if it is non-zero), or make the
deadline authoritative at the row level so a bet cannot commit against a round
whose timer has expired.
### (not new) `drawing` does not resume after a restart
Already tracked as an accepted gap in CLAUDE.md's "Known gaps", not re-numbered
here. Worth restating in context: with `restart: unless-stopped` on the app
container, this is the one state that gets stuck with money in play, and it
remains the last prerequisite for running unattended.
---
## Previously fixed
## High — security
- **B-25** — the payout had no two-phase write, unlike bets and withdrawals
- **B-26** — a payout failure or a process restart could wedge a round in `paying_out` forever
- **B-27** — an RBF bump reset the reconciler's own abandon clock, so a repeatedly-bumped tx was never abandoned
- **B-28** — a hostile Electrum server (or a MITM) could single-handedly pick the round's winner
- **B-29** — a UTXO absent from one server's `listunspent` was marked spent immediately, irreversibly, on a single unauthenticated reply
- **B-30** — a lost scripthash subscription meant a user's deposits were never credited, with no periodic safety net
- **B-31** — resubscribing on reconnect ran serially before anything else started, freezing the chain tip (and so an in-flight draw) for the whole sweep
- **B-42** — Swagger/ReDoc/the raw OpenAPI JSON enumerated the entire API surface, admin endpoints included, to anyone who requested them; now off by default and gated behind `ENABLE_API_DOCS`
- **B-43** — the Caddyfile sent no CSP, no `X-Frame-Options`/`frame-ancestors`, and no HSTS, on a page whose JWT lives in `localStorage`
- **B-44** — README's Quick start documented a bare `uvicorn --reload` workflow, and `docs/running-the-server.md` still had a matching "Locale / venv" section, both contradicting CLAUDE.md's Docker-only policy
- **B-45** — `/admin/rounds`/`/admin/audit-log`'s `limit` had no bounds (`-1` means "everything" on SQLite), and `/admin/pending-transactions` had no limit or status filter at all
- **B-46** — `secrets.compare_digest` on a `str` raises `TypeError` on non-ASCII input, turning an invalid admin token with non-ASCII characters into a 500 instead of a 403
- **B-47** — `raw_tx_hex` and `payload_json` were unbounded `String` columns (`VARCHAR` with no length) — fine on SQLite/PostgreSQL, rejected by backends like MySQL that require a length
- **B-32** — an RBF bump could retry forever below BIP125's relay-mandated minimum fee delta, with no ceiling on the fee rate either
- **B-33** — `POST /auth/login` had no rate limiting, so a password could be brute-forced against an enumerable username list
- **B-34** — password change/reset didn't invalidate already-issued JWTs, so a stolen token survived a change meant to lock it out
- **B-35** — API timestamps round-tripped as naive datetimes, so the frontend parsed them as local time instead of UTC
- **B-36** — a stalled draw wait had no timeout, no log, and no audit trail, so a frozen round showed nothing in `/admin`
- **B-37** — a withdrawal covered by unconfirmed change answered "insufficient balance" instead of distinguishing it from actually having no funds
- **B-38** — the SSE subscriber cap was global, so one client opening enough connections degraded every other user to polling
- **B-39** — SQLite ran without WAL or a `busy_timeout`, so a writer could block every reader and a second writer failed immediately instead of waiting
- **B-40** — `bump_fee` held a DB session open across N slow network calls, and computed a prevout's value from a server-reported float instead of an exact integer
- **B-41** — confirmation/reconciliation depended on a verbose `blockchain.transaction.get` reply many Electrum servers reject, and abandonment relied on fragile substring-matching of an error message
### B-54 — `X-Forwarded-For` is trusted blindly, so every IP-keyed control is bypassable
See git history for the fix-by-fix breakdown (commits `f13f685`, `50a43ae`, `933760e`, and the
B-28/B-29/B-30/B-31/B-32/B-33/B-34/B-35/B-36/B-37/B-38/B-39/B-40/B-41/B-42/B-43/B-44/B-45/B-46/B-47 fixes). Suite grew from 139 to 248 tests over the twenty-three.
`app/api/client_ip.py:14-17`, `Caddyfile`.
A full-codebase audit on 2026-07-26 (commit `d4e0974`) found 24 bugs across every Python
module under `app/`, both static frontends, and the Docker/Caddy deployment — 5 critical,
7 high, 7 medium, 5 low. All 24 were fixed and verified against the current code on
2026-07-27; the fixes are covered by the regression suite (grew from 79 to 139 tests) and
five of them were additionally confirmed against a real mainnet deployment (see git history
between `fb734bb` (documenting the findings) and `845ba98` (recording the audit outcome) for
the fix-by-fix breakdown — each commit message names the bugs it closes and where their
tests live).
`client_ip()` returns `xff.split(",")[0]`. Caddy's `reverse_proxy` *appends* the
real peer address to an incoming `X-Forwarded-For` rather than replacing it, so
the first element is whatever the client sent. Rotating a fake value per request
defeats `login_ip`, `register_ip` (B-33) and the per-IP SSE subscriber cap
(B-38) outright; only the per-username login bucket still bites.
Fix: take the *last* element of the header, or force it at the proxy with
`header_up X-Forwarded-For {remote_host}` and keep reading element 0. The proxy-side
fix is the more robust of the two, since it makes the app's assumption true.
### B-55 — Argon2 hashing runs on the event loop
`app/auth/security.py:20-39`, called from `app/auth/routes.py` and
`app/api/routes/users.py`.
`hash_password`/`verify_password` are synchronous and cost tens of milliseconds
each, so every login, registration and password change blocks the whole process —
including all six background tasks (scheduler, confirmation poller, RBF bumper,
listener, both reconcilers). A burst of unauthenticated login attempts (which,
per B-54, is not effectively throttled) is a cheap denial of service that also
delays draws and confirmations.
Fix: run both through `starlette.concurrency.run_in_threadpool`.
### B-56 — `RateLimiter._buckets` is never pruned
`app/auth/rate_limit.py:37`.
The dict grows without bound, keyed by attacker-chosen strings (arbitrary
usernames, and — via B-54 — arbitrary IPs). `decay_seconds` ages a bucket's
*counter* but never removes the entry.
Fix: evict entries whose last failure is older than `decay_seconds` (opportunistically
on `record_failure`, or on a periodic sweep), and cap the dict size.
### B-57 — username matching is case-sensitive while the login throttle key is not
`app/auth/routes.py:126` (`body.username.lower()`) vs `:132`
(`User.username == body.username`).
Two consequences: `Bob` and `bob` are separate accounts sharing a single rate-limit
bucket (one locks the other out), and registration happily accepts near-duplicate
usernames, which is an impersonation vector on a custodial system.
Fix: make username uniqueness case-insensitive (store a normalized form, or a
functional unique index) and key the throttle on the same normalized value.
### B-58 — the registration throttle counts successes as failures and is IP-only
`app/auth/routes.py:66-71`.
`record_failure` is called on every registration attempt, successful ones
included. Five legitimate signups from one shared/NAT address lock the sixth real
user out with exponential backoff up to 600 s — while an attacker skips the limiter
entirely through B-54. The intent (bounding accounts per source) is reasonable;
the current shape punishes only honest users. The inline comment also cites B-31
(the resubscribe finding) where it means B-33.
Fix: keep an accounts-per-IP quota if that is the goal, but express it as a quota
rather than as failure backoff, and fix the B-nn reference.
### B-59 — deposit crediting is not corroborated, unlike external-spend detection
`app/deposits/service.py:31-45`, `app/electrum/listener.py:401-433`.
A candidate external spend is corroborated across the other configured servers
before it can reduce a balance (B-29), but `value` and `height` for a *credit*
are taken from the single active connection with no cross-check. A hostile or
broken server can inflate a user's displayed balance with outpoints that do not
exist. The blast radius is bounded — a bet or withdrawal built on a phantom UTXO
is refused at broadcast and the rollback releases it — but it wedges the user's
balance display and burns build attempts.
Fix: either corroborate credits the same way (symmetry with B-29), or record the
asymmetry explicitly as an accepted risk in CLAUDE.md with its bound stated.
### B-60 — `POST /admin/bug-reports/{id}/status` writes no audit entry
`app/api/routes/admin.py:404-419`.
Every other admin mutation (config edit, pause/resume, privkey export, password
reset) is audit-logged. This one is not, so a report can be silently marked
`resolved` with no trace — and with one shared `ADMIN_TOKEN` and no per-admin
identity, the audit log is the only accountability there is.
---
## Medium — correctness and robustness
### B-61 — config edits apply retroactively to the round already in progress
`app/rounds/scheduler.py:71`, `app/rounds/service.py:51-61`,
`app/api/routes/admin.py:106-128`.
`round_duration_seconds` is read live on every tick and on every bet check, and the
deadline is computed as `opened_at + duration`. Lowering it from 600 to 60 while a
round is 300 s in closes that round instantly; raising it moves the `closes_at`
clients are already counting down to. `round_cooldown_seconds` has the same
property for the gap after a close.
B-11 fixed exactly this class of problem for `bet_amount_sats` (an in-progress
round's advertised jackpot must not move when an operator edits the bet amount);
the timing fields were left live.
Fix: snapshot the duration (and cooldown) onto the `Round` row when it opens and
read them from there, leaving the config row as the value for the *next* round.
### B-62 — "withdraw the full amount" reliably produces an unbumpable transaction
`app/static/app.js:798-807`, `app/wallet/psbt_builder.py:138-141`,
`app/tx/broadcast.py:150-152`.
The max-amount checkbox sends `amount_sats == myBalanceSats == total_in`, so
`change == 0`, the change output is dropped, and the tx has a single output. `bump_fee`
then finds no change output to absorb the increase and raises `RbfError` every 30 s
until the reconciler abandons the row six hours later. The RBF single-change-output
limitation is a documented gap, but the UI makes it the *default* withdrawal path
rather than a corner case (the same applies to an exact-amount bet).
Fix directions: leave a change output above `DUST_LIMIT_SATS` when the requested
amount would consume the whole input total (i.e. reserve a little), or warn in the
UI that a full-balance withdrawal cannot be fee-bumped, or implement the
extra-input RBF fallback.
### B-63 — `tip_height == 0` window right after connecting can seed a draw from a pre-close block
`app/electrum/listener.py:160-167`, `app/rounds/scheduler.py:153`.
`_run_once` assigns `self.client` *before* `subscribe_headers()` returns, so there
is a window in which the client looks alive while `tip_height` is still 0 and
`tip_header_hex` is `None`. A `_close_and_draw` entering that window records
`tip_at_close = 0`, and the first header applied — the current tip, a block mined
*before* the round closed — satisfies `tip_height > tip_at_close` and becomes the
draw's entropy. The draw must use a block that did not exist at close time; a block
whose hash was already public before betting closed is not the guarantee the
flowchart describes.
Fix: publish `self.client` only after the first header has been applied, or refuse
to draw while `tip_header_hex is None` / `tip_height == 0`.
### B-64 — `_apply_header` accepts a same-height header without the chaining check
`app/electrum/listener.py:271-296`.
The chain check only runs for `height == self.tip_height + 1`. A header at exactly
the current tip height replaces `tip_header_hex` after passing only the
self-target check — which, as the docstring of `header_meets_its_own_target`
already notes, a server can satisfy with a self-declared easy target. Separately,
a header with no `hex` field sets `tip_header_hex = None`, discarding a tip we
otherwise accepted.
Fix: treat a same-height header as either ignorable or as a reorg signal rather
than silently replacing the entropy source, and don't clear `tip_header_hex` on a
hex-less notification.
### B-65 — `/rounds/current` counts unconfirmed participants; the draw and payout do not
`app/api/routes/rounds.py:131-143` vs `app/rounds/scheduler.py:126`.
`participant_count` and `jackpot_sats` are computed over *all* `round_participants`
rows, while the draw and the payout only use `status == "confirmed"`. So the
advertised jackpot can exceed what is actually paid out, and a participant whose
bet is later abandoned appears in the count and then vanishes from it.
Fix: either count only `confirmed` (and accept that a fresh bet takes a block to
show up), or expose the two figures separately (confirmed vs in-flight) so the
number on screen and the number that gets paid agree by construction.
### B-66 — nothing stops rounds from opening with no `fee_address` configured
`app/rounds/config.py:12-17`, `app/rounds/scheduler.py:330-335`.
A fresh instance starts with `fee_address = ""`. Rounds open, bets are accepted and
confirm, and only then does the payout refuse to build — leaving the round in
`paying_out`, retrying every 60 s, with the audit log as the only signal.
Fix: refuse to open a round while `fee_address` is unset (and surface it on
`/admin` and as a maintenance-style banner), so the failure happens before anyone's
money is committed.
### B-67 — `/qr/{address}` is unauthenticated, synchronous and only shape-validated
`app/api/routes/qr.py:11-21`.
`qrcode.make` runs on the event loop, so the endpoint is a cheap CPU amplifier for
an unauthenticated caller, and the regex accepts any `plm1[a-z0-9]{10,90}` string
without validating the bech32 checksum — so it happily renders a QR for a
non-address.
Fix: validate with `is_valid_plm_address` (already used by withdrawals and by the
admin `fee_address` validator), and either offload the render or cache it per
address.
---
## Low — documentation and consistency drift
### B-68 — CLAUDE.md and README describe a state the code has moved past
- CLAUDE.md's tech-stack line still says JWT has **no revocation (B-34)**; `token_version`
implements exactly that revocation (`app/db/models.py:29`, `app/auth/dependencies.py:26`).
- "Known gaps" still says **no rate limiting anywhere (B-33)**; login and registration
are throttled (`app/auth/rate_limit.py`). What is genuinely still unthrottled is
bets, withdrawals and the admin endpoints — that is the claim worth keeping.
- "Known gaps" still says **`/report-bug` is a placeholder**; it is fully implemented
and translated, with admin triage. Only `/guida` is still a stub.
- Test counts are stale in three places: 264 actual, CLAUDE.md says 253 twice,
README says 232.
- The code map omits `app/auth/rate_limit.py`, `app/api/client_ip.py` and
`app/api/routes/bug_reports.py`.
- README links `flowchart.mmd`, which does not exist (the diagrams live in
`flowchart/`), describes `docs/running-the-server.md` as covering "local venv vs.
Docker" (that workflow was removed in B-44), and links the anchor
`CLAUDE.md#tech-stack-mvp`, which no longer exists.
### B-69 — stale in-code comments
- `app/tx/reconcile.py:206` calls the payout retry "a future payout-retry routine —
still an open gap"; it exists (B-26).
- `app/db/base.py:9` says "five concurrent background tasks"; there are six.
- `app/auth/routes.py:31` cites B-31 where it means B-33 (see B-58).
### B-70 — the flowchart's WITHDRAW precondition is not implemented as written
`flowchart/platform-overview.mmd:39` (node E1) states a withdrawal cannot happen
together with a bet in progress. The code only serializes the *builds* through the
per-user lock (`app/tx/locks.py`): a withdrawal is accepted while a bet is still
unconfirmed, as long as confirmed UTXOs cover it.
CLAUDE.md declares every node and edge label of the diagrams a behaviour that must
be implemented as described, so one of the two has to move — most likely the
diagram, since the lock already prevents the actual double-spend hazard, but that
is a decision, not a cleanup.
### B-71 — `.env` points `MASTER_KEY_PATH` at a second copy of the master key
CLAUDE.md's deployment section prescribes pointing `MASTER_KEY_PATH` at the
host-side `./data/keys/master.xprv.enc` so the venv scripts and the container read
one file. `.env` instead sets `./master.xprv.enc`, and both files now exist in the
working tree (both gitignored). They were verified during this audit to decrypt to
the *same* xprv, so nothing has diverged yet — but `scripts/decrypt_master_key.py`
reads a different file from the one the container uses, and a future
`generate_master_key.py --overwrite` would split them silently, with an ops
recovery path that then reports the wrong key.
The same duplication exists for the database (`./plm_lottery.db` next to
`data/db/plm_lottery.db`), which is less dangerous but equally confusing.
Fix: set `MASTER_KEY_PATH=./data/keys/master.xprv.enc` in `.env`, delete the stray
root copy once confirmed redundant, and state the same for `DATABASE_URL`.
### B-72 — `docs/setup.md` still frames setup as "locally or via Docker"
`docs/setup.md:1-10` lists Python as a prerequisite "for the local/venv workflow"
and describes the master-key step as local *or* Docker, while B-44 made Docker the
only supported way to run the server (`docs/running-the-server.md` and README were
updated, this file was not). The venv genuinely is needed for tests, migrations and
the key scripts — the wording just needs to say that instead of implying a second
way to run the server.
+13 -9
View File
@@ -8,11 +8,11 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
## Project status
All 10 stages of the original build order are code-complete and unit-tested — 185 tests, all under `tests/unit/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below.
All 10 stages of the original build order are code-complete and unit-tested — 253 tests, all under `tests/unit/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below.
Verified on mainnet with real money: registration + address derivation, deposit crediting (1-conf), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only.
**Read [BUGS.md](BUGS.md) before trusting any behaviour here.** Two audits: 2026-07-26 found 24 bugs (5 critical), all fixed; 2026-07-27 found 25 more (B-25 … B-49), of which **2 are still open** — no Critical, High or Medium remains, only Low/hygiene: no cap on input count in `select_utxos` (B-48) and rollback paths not publishing an SSE update (B-49). BUGS.md is the live open list with a proposed fix per finding; "Known gaps" at the end of this file is for limitations accepted **by design** instead. Don't fix a BUGS.md item silently as a side effect of other work — each fix lands with its own regression test.
Two full-codebase audits — 2026-07-26 (24 findings, 5 critical) and 2026-07-27 (25 more, B-25 … B-49) — are **all fixed** as of 2026-07-27, each with its own regression test. They were tracked in a `BUGS.md` that was deleted once the list emptied, so the ~276 `B-nn` markers left in comments across the code are pointers into git history (`git log --all --grep 'B-nn'` finds the commit that fixed one, and `git show f1a1145:BUGS.md`-style the file as it stood). A closed list is not the same as no bugs: the suite is unit-only (`tests/integration/` is empty), and withdrawal and the RBF bump have never been live-broadcast. "Known gaps" at the end of this file is for limitations accepted **by design** instead. A new finding gets the next B-nn, in its own commit with its own regression test.
Before writing code, read the "Architecture" section below in full plus the diagrams in [flowchart/](flowchart/): [platform-overview.mmd](flowchart/platform-overview.mmd) (the 5-phase flow) and [round-lifecycle.mmd](flowchart/round-lifecycle.mmd) (the round/draw lifecycle). Every node **and edge label** (conditions, retries, loops) is a behaviour that must be implemented as described. Regenerate the companion PDFs with `flowchart/render-pdf.sh <file>.mmd` after editing either.
@@ -33,7 +33,7 @@ PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+pr
PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace)
PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip
python -m pytest # all 185 tests
python -m pytest # all 253 tests
python -m pytest tests/unit/test_hd.py # one file
python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test
```
@@ -91,6 +91,9 @@ Source of truth: the `PalladiumWallet` repo — [ChainProfiles.cs](../PalladiumW
| Min deposit | none | — |
| Min password length | 8 | `auth/security.py:MIN_PASSWORD_LENGTH` |
| Confirmations, every tx kind | **1** | hardcoded in `tx/confirmation.py` |
| Max inputs per *user* tx (bet, withdrawal) | 50 (`MAX_TX_INPUTS`, B-48) — over it the build fails with `too_many_inputs`, it never spends more | hardcoded in `wallet/psbt_builder.py` |
| Max inputs per *payout* | 500 (`MAX_PAYOUT_TX_INPUTS`, B-52) — the pool holds one UTXO per bet, so reusing the user cap made any round past ~50 players unpayable | hardcoded in `wallet/psbt_builder.py` |
| Max participants per round | 400 (`MAX_PARTICIPANTS_PER_ROUND`, B-52) — the 401st bet is refused with `round_full` *before* any money moves, so "a round can always be paid out" is an invariant rather than something discovered at payout time | hardcoded in `wallet/psbt_builder.py`, enforced in `bets/service.py` |
`GET /rounds/current`'s `jackpot_sats` is the winner's 70% share, not the whole pool, and the pool is summed from the participants' actual `bet_amount_sats` (each already net of its own bet fee) rather than `count × current bet amount` — editing the bet amount mid-round must not move an in-progress round's advertised jackpot (B-11).
@@ -149,7 +152,7 @@ Diagrams: [platform-overview.mmd](flowchart/platform-overview.mmd), [round-lifec
**DEP** — the listener subscribes to the user's scripthash; balance is credited after **1 confirmation**, with the 1-conf reorg risk knowingly accepted and no rollback logic. `deposits/service.py` also detects UTXOs that vanished (spent outside the platform — corroborated per B-29 first) and *reinstates* ones that reappear.
**PLAY** — fixed cost, **at most one active bet per user**. PSBT user-address → pool-address, always with a **change output back to the same user address** (a user's balance must never exactly equal the bet). Fee ~1 sat/vB, **deducted from the bet amount**. No confirmation within the timeout → RBF bump and rebroadcast.
**PLAY** — fixed cost, **at most one active bet per user**, and **at most `MAX_PARTICIPANTS_PER_ROUND` (400) players per round** — past that the bet is refused with `round_full` and the player waits for the next round (B-52: the payout must spend one pool UTXO per bet, so a round is only ever allowed to grow to what a single payout tx can drain). PSBT user-address → pool-address, always with a **change output back to the same user address** (a user's balance must never exactly equal the bet). Fee ~1 sat/vB, **deducted from the bet amount**. No confirmation within the timeout → RBF bump and rebroadcast.
**DRAW** — configurable timer (default 600s):
- *Bet cutoff is the round's own deadline* (`opened_at + round_duration_seconds`), **not** the DB status: `place_bet` calls `rounds/service.round_accepts_bets`, which rejects once the deadline passes even while `status` is still `"open"` (the 5s scheduler tick can lag behind it). Once a round leaves `open`, no new bets either, and no new round opens until this one is fully `closed`.
@@ -180,7 +183,7 @@ At 120s blocks that's ~4–6 min worst case (last bet confirms right at the dead
`GET /rounds/stream` is **additive to** the polling loops in the two SPAs, not a replacement — a blocked or dropped stream just degrades to the old behaviour. No payload, no auth: it's a "something changed, go refetch" ping, with all personalization (e.g. `user_played`) staying in the authenticated REST endpoints. The generator re-checks `request.is_disconnected()` every 5s and sends a keep-alive comment every 20s, so neither a client that vanished without a clean close nor a proxy idle timeout breaks it silently.
`rounds/events.py`'s `RoundEventBroadcaster` (singleton `broadcaster`) is in-process pub/sub, one `asyncio.Queue(maxsize=1)` per client so redundant notifications coalesce. `publish()` is called on: a round opening (`rounds/service.py`), every status transition (`scheduler.py`), a bet or withdrawal broadcast, any pending tx confirming (`tx/confirmation.py`), a deposit credited (`deposits/service.py`), and a new tip arriving (`electrum/listener.py` — exactly what the drawing phase waits on). Rollback paths are the known exception (B-49).
`rounds/events.py`'s `RoundEventBroadcaster` (singleton `broadcaster`) is in-process pub/sub, one `asyncio.Queue(maxsize=1)` per client so redundant notifications coalesce. `publish()` is called on: a round opening (`rounds/service.py`), every status transition (`scheduler.py`), a bet or withdrawal broadcast, any pending tx confirming (`tx/confirmation.py`), a deposit credited (`deposits/service.py`), and a new tip arriving (`electrum/listener.py` — exactly what the drawing phase waits on). The rollback paths (`_release_failed_bet`, `_release_failed_withdrawal`, the reconciler's abandon) publish too — a rollback moves as much state as the success path, so it must ping the dashboards the same way (B-49).
Deliberate scope limits, not oversights: **single-process only** (fine for one uvicorn process; a multi-worker deployment needs e.g. Redis pub/sub — don't add it speculatively); **generic broadcast, not per-user** (everyone refetches on every event; acceptable at ~100 concurrent users, and a targeted channel would need auth on the stream plus server-side knowledge of who each event affects); `MAX_SUBSCRIBERS` (500) is defensive only — past it the endpoint returns 503 and `EventSource` falls back to polling, which being global and unauthenticated makes the cap itself a cheap DoS of the realtime feature (B-38).
@@ -209,12 +212,13 @@ Two static SPAs served directly by FastAPI (`main.py` mounts `app/static/` and a
Both talk to the same JSON API; there's no admin/user API split beyond `require_admin`.
## Internationalization (`/` only)
## Internationalization (`/` and `/report-bug`)
`app/static/i18n.js` holds every user-facing string of `/` in 7 languages (en, it, es, fr, de, ru, zh) as one flat `TRANSLATIONS` table — no build step, no fetch, loaded before `app.js` so `t()` is always available. Language: `localStorage.plm_lang` → `navigator.language` → `en`. The switcher sits in the **chain-bar, not the navbar**, deliberately: the navbar is hidden until login, which would leave the landing page and login form untranslatable for exactly the users who need it.
`app/static/i18n.js` holds every user-facing string of `/` and `/report-bug` in 7 languages (en, it, es, fr, de, ru, zh) as one flat `TRANSLATIONS` table — no build step, no fetch. `/` loads it before `app.js`; `/report-bug` loads it before its own inline script — either way `t()` is always available by the time it's called. Language: `localStorage.plm_lang` → `navigator.language` → `en`, shared across both pages since they read/write the same `localStorage` key. On `/` the switcher sits in the **chain-bar, not the navbar**, deliberately: the navbar is hidden until login, which would leave the landing page and login form untranslatable for exactly the users who need it. `/report-bug` has no navbar at all, so its switcher is just a top-right bar of its own.
- Static markup is translated by attribute (`data-i18n`, plus `-html`, `-placeholder`, `-title`, `-aria-label`, `-alt`) via `applyStaticTranslations(root?)`; anything rendered from server data uses `t()` in `app.js` and is re-rendered by `onLanguageChange()`. An element belongs to one camp or the other, **never both**, or the two mechanisms overwrite each other — that's why `#bet-btn` has no `data-i18n`: its label carries the configurable bet amount, so `renderBetButton()` owns it.
- Static markup is translated by attribute (`data-i18n`, plus `-html`, `-placeholder`, `-title`, `-aria-label`, `-alt`) via `applyStaticTranslations(root?)`; anything rendered from server data uses `t()` directly (`app.js`'s `onLanguageChange()`, `report-bug.html`'s own inline equivalent) and is re-rendered on a language switch. An element belongs to one camp or the other, **never both**, or the two mechanisms overwrite each other — that's why `#bet-btn` has no `data-i18n`: its label carries the configurable bet amount, so `renderBetButton()` owns it.
- **Every language must have exactly the same key set.** There is no fallback beyond `en`; a missing key renders as the raw key string.
- `/report-bug`'s `bugReport.englishNotice` string is itself translated into all 7 languages — it just always *says*, in whichever language the visitor reads, to write the actual bug description in English (so the admin panel, which is Italian-operator-facing and untranslated, doesn't end up with reports in 7 different languages).
- `/admin` is intentionally untranslated (operator-facing, Italian), as is `/guida`.
**API error contract** (`app/api/errors.py`) — the API is single-language by design. Failures answer with a structured `detail`: `{"code", "message", "params"}`, where `message` is English for non-dashboard consumers and `code` is what the frontend maps to `error.<code>` in `i18n.js` (falling back to `message` for an unknown code). `BetError`/`WithdrawalError` subclass `ApiError` and carry the code from where the failure happens. Even the catch-all 500 handler answers in that shape (`internal_error`), so clients never special-case unexpected errors, and the exception text stays in `logs/app.log`. Adding a user-facing error: give it a code, add `error.<code>` to all 7 languages, and pass values through `params` (amounts as `*_sats` — the frontend derives a `*_plm` sibling) instead of baking them into English text.
@@ -233,7 +237,7 @@ Explicit design choices, not derivable from any single file — respect them:
## Known gaps / TODO
Accepted **by design**. For actual bugs see [BUGS.md](BUGS.md) (2 open) — not duplicated here.
Accepted **by design** — distinct from the audit findings above (all fixed), which are not duplicated here.
- **`drawing` doesn't resume after a restart.** `_tick()` handles `open`, `closing` and `paying_out` (the last via `_retry_payout_if_due`); nothing re-enters `_wait_for_next_block` after a crash. That wait is unbounded by design (the draw's entropy genuinely depends on a future block) but no longer silent — past `_DRAW_STALL_THRESHOLD_SECONDS` it logs progress and writes a `draw_stalled` audit entry, and `GET /rounds/current`'s `draw_waiting_since` surfaces it live (B-36). Restart-resumption itself remains the last prerequisite for running unattended.
- **RBF handles one shape only**: a single change output, back to the tx's own sender, big enough to absorb the increase. No extra-input fallback — an exact-amount tx or too-small change raises `RbfError`. Not permanent, though: an unbumpable tx that never confirms is eventually abandoned and its UTXOs released.
+72 -1
View File
@@ -10,7 +10,7 @@ from app.api.timeutil import isoformat_utc
from app.audit.log import write_audit_log
from app.auth.security import hash_password
from app.config import settings
from app.db.models import AuditLog, PendingTransaction, Round, User
from app.db.models import AuditLog, BugReport, PendingTransaction, Round, User
from app.db.session import get_session
from app.rounds.config import get_round_config
from app.wallet.address import is_valid_plm_address
@@ -346,3 +346,74 @@ async def list_pending_transactions(
)
for p in entries
]
_BUG_REPORT_STATUSES = ("open", "read", "resolved")
class AdminBugReportResponse(BaseModel):
id: int
description: str
contact: str | None
user_id: int | None
username: str | None
status: str
created_at: str
def _bug_report_response(report: BugReport, username: str | None) -> AdminBugReportResponse:
return AdminBugReportResponse(
id=report.id,
description=report.description,
contact=report.contact,
user_id=report.user_id,
username=username,
status=report.status,
created_at=isoformat_utc(report.created_at),
)
@router.get(
"/bug-reports", response_model=list[AdminBugReportResponse], dependencies=[Depends(require_admin)]
)
async def list_bug_reports(
session: AsyncSession = Depends(get_session), limit: int = Query(default=200, ge=1, le=500)
) -> list[AdminBugReportResponse]:
reports = (await session.scalars(select(BugReport).order_by(BugReport.id.desc()).limit(limit))).all()
user_ids = {r.user_id for r in reports if r.user_id is not None}
usernames = {}
if user_ids:
users = (await session.scalars(select(User).where(User.id.in_(user_ids)))).all()
usernames = {u.id: u.username for u in users}
return [
_bug_report_response(r, usernames.get(r.user_id) if r.user_id is not None else None)
for r in reports
]
class BugReportStatusUpdate(BaseModel):
status: str = Field(pattern="^(open|read|resolved)$")
@router.post(
"/bug-reports/{report_id}/status",
response_model=AdminBugReportResponse,
dependencies=[Depends(require_admin)],
)
async def update_bug_report_status(
report_id: int, body: BugReportStatusUpdate, session: AsyncSession = Depends(get_session)
) -> AdminBugReportResponse:
report = await session.get(BugReport, report_id)
if report is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "bug report not found")
report.status = body.status
await session.commit()
username = None
if report.user_id is not None:
user = await session.get(User, report.user_id)
username = user.username if user is not None else None
return _bug_report_response(report, username)
+79
View File
@@ -0,0 +1,79 @@
from fastapi import APIRouter, Depends, status
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.timeutil import isoformat_utc
from app.auth.dependencies import get_current_user, get_optional_user
from app.db.models import BugReport, User
from app.db.session import get_session
router = APIRouter(prefix="/bug-reports", tags=["bug-reports"])
class BugReportCreate(BaseModel):
description: str = Field(min_length=1, max_length=2000)
contact: str | None = Field(default=None, max_length=256)
@field_validator("description")
@classmethod
def _description_not_blank(cls, value: str) -> str:
value = value.strip()
if not value:
raise ValueError("description must not be blank")
return value
@field_validator("contact")
@classmethod
def _contact_stripped(cls, value: str | None) -> str | None:
if value is None:
return None
value = value.strip()
return value or None
class BugReportResponse(BaseModel):
id: int
@router.post("", response_model=BugReportResponse, status_code=status.HTTP_201_CREATED)
async def create_bug_report(
body: BugReportCreate,
user: User | None = Depends(get_optional_user),
session: AsyncSession = Depends(get_session),
) -> BugReportResponse:
report = BugReport(
description=body.description,
contact=body.contact,
user_id=user.id if user is not None else None,
)
session.add(report)
await session.commit()
return BugReportResponse(id=report.id)
class MyBugReportResponse(BaseModel):
id: int
description: str
status: str
created_at: str
@router.get("/mine", response_model=list[MyBugReportResponse])
async def list_my_bug_reports(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
) -> list[MyBugReportResponse]:
"""The one user-facing history view for bug reports (anonymous submissions have
no user to attribute this to, so this only ever covers ones filed while logged in)."""
reports = (
await session.scalars(
select(BugReport).where(BugReport.user_id == user.id).order_by(BugReport.id.desc())
)
).all()
return [
MyBugReportResponse(
id=r.id, description=r.description, status=r.status, created_at=isoformat_utc(r.created_at)
)
for r in reports
]
+2 -2
View File
@@ -15,7 +15,7 @@ from app.db.models import RoundParticipant, User
from app.db.session import get_session
from app.rounds.config import get_round_config
from app.rounds.events import EVICTED, RoundEventCapacityError, broadcaster
from app.rounds.service import get_active_round
from app.rounds.service import get_active_round, winner_share
router = APIRouter(prefix="/rounds", tags=["rounds"])
@@ -165,7 +165,7 @@ async def current_round(
# upper bound by the payout tx's own fee, which is deducted from the winner's
# share and isn't knowable until the payout is built — a few hundred sat on a
# 1 sat/vB payout, i.e. invisible at PLM amounts, but it is not exact.
jackpot_sats = pool_amount_sats * 70 // 100
jackpot_sats = winner_share(pool_amount_sats)
return CurrentRoundResponse(
server_time=datetime.now(timezone.utc).isoformat(),
+34 -3
View File
@@ -1,7 +1,7 @@
from datetime import datetime, timezone
from embit import script
from sqlalchemy import select
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.errors import ApiError
@@ -13,7 +13,13 @@ from app.rounds.events import broadcaster
from app.rounds.service import open_new_round_if_needed, round_accepts_bets
from app.wallet.balance import recompute_balance
from app.wallet.hd import derive_pool_address, derive_user_key
from app.wallet.psbt_builder import BuiltTransaction, InsufficientFundsError, Utxo, build_signed_transaction
from app.wallet.psbt_builder import (
MAX_PARTICIPANTS_PER_ROUND,
BuiltTransaction,
InsufficientFundsError,
Utxo,
build_signed_transaction,
)
class BetError(ApiError):
@@ -37,6 +43,26 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
if already_playing is not None:
raise BetError("already_betting", "you already have an active bet in the current round")
# B-52: "this round can always be paid out" is an invariant, and this is where it
# gets enforced — before any of this user's money moves. The payout has to spend
# one pool UTXO per bet, so a round that grew past what a single payout
# transaction may spend was unpayable: it stayed "paying_out" retrying forever,
# and because no new round may open while one is active, the whole lottery
# stopped. Refusing the bet costs the player one round of waiting; accepting it
# cost everyone the platform. Counted over every participant row, not just the
# confirmed ones: a bet that later fails frees a slot, so counting them all is
# the conservative direction.
participant_count = await session.scalar(
select(func.count()).select_from(RoundParticipant).where(RoundParticipant.round_id == round_.id)
)
if participant_count >= MAX_PARTICIPANTS_PER_ROUND:
raise BetError(
"round_full",
f"this round already has its maximum of {MAX_PARTICIPANTS_PER_ROUND} players, "
"wait for the next one",
max_participants=MAX_PARTICIPANTS_PER_ROUND,
)
bet_amount = config.bet_amount_sats
unspent = (
@@ -62,7 +88,7 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
fee_rate_sat_vb=config.fee_rate_sat_vb,
)
except InsufficientFundsError as exc:
raise BetError(exc.code, str(exc)) from exc
raise BetError(exc.code, str(exc), **exc.params) from exc
# --- Phase 1: record the intent, *then* broadcast (B-08) --------------------
# Broadcasting first meant a failure (or a crash) between the broadcast and the
@@ -144,6 +170,11 @@ async def _release_failed_bet(
user_id=user_id,
)
await session.commit()
# The rollback moved as much state as the successful path did — the balance is
# back, the participant is gone, so participant_count and jackpot shrank again.
# Without this the dashboards kept showing the phantom bet until their next poll
# (B-49); the reconciler's own abandon path has always published here.
broadcaster.publish()
def _pending_transaction(
+18
View File
@@ -188,6 +188,24 @@ class Withdrawal(Base):
confirmed_at: Mapped[datetime | None] = mapped_column(default=None)
class BugReport(Base):
__tablename__ = "bug_reports"
id: Mapped[int] = mapped_column(primary_key=True)
description: Mapped[str] = mapped_column(Text)
contact: Mapped[str | None] = mapped_column(String(256), default=None)
# Set when the reporter was logged in at submission time; the report page is
# reachable both logged-in and logged-out (like GET /rounds/current), so this
# stays nullable rather than requiring auth just to file a report.
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), default=None)
# open -> read -> resolved, admin-driven (app/api/routes/admin.py). "read" is a
# distinct step from "resolved" so a reporter checking their own status (only
# possible when logged in — see GET /bug-reports/mine) can tell "an admin has
# seen this" apart from "this has actually been fixed".
status: Mapped[str] = mapped_column(String(16), default="open")
created_at: Mapped[datetime] = mapped_column(default=utcnow)
class AuditLog(Base):
__tablename__ = "audit_log"
+3 -1
View File
@@ -15,6 +15,7 @@ import app.rounds.confirmation # noqa: F401 (registers the "payout" confirmati
import app.withdrawals.confirmation # noqa: F401 (registers the "withdrawal" confirmation handler)
from app.api.routes.admin import router as admin_router
from app.api.routes.bets import router as bets_router
from app.api.routes.bug_reports import router as bug_reports_router
from app.api.routes.qr import router as qr_router
from app.api.routes.rounds import router as rounds_router
from app.api.routes.users import router as users_router
@@ -41,7 +42,7 @@ def _make_electrum_client(endpoint: ElectrumEndpoint) -> ElectrumClient:
@asynccontextmanager
async def lifespan(app: FastAPI):
# Refuses to serve rather than starting up half-configured — see B-15 in BUGS.md.
# Refuses to serve rather than starting up half-configured (B-15).
validate_runtime_secrets()
endpoints = parse_endpoints(
@@ -99,6 +100,7 @@ app.include_router(users_router)
app.include_router(bets_router)
app.include_router(withdrawals_router)
app.include_router(admin_router)
app.include_router(bug_reports_router)
app.include_router(qr_router)
app.include_router(rounds_router)
+14 -7
View File
@@ -14,7 +14,7 @@ from app.electrum.scripthash import address_to_scripthash
from app.rounds.config import get_round_config
from app.rounds.draw import draw_winner, header_hex_to_block_hash
from app.rounds.events import broadcaster
from app.rounds.service import open_new_round_if_needed
from app.rounds.service import open_new_round_if_needed, winner_share
from app.wallet.hd import derive_pool_key
from app.wallet.plm_network import PLM_MAINNET
from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_payout_transaction
@@ -338,8 +338,8 @@ class RoundScheduler:
await self._log_payout_failure(round_id, winner_user_id, "winner user not found")
return
winner_share = pool_amount_sats * 70 // 100
commission_share = pool_amount_sats - winner_share # remainder from rounding goes to fees
winner_sats = winner_share(pool_amount_sats)
commission_share = pool_amount_sats - winner_sats # remainder from rounding goes to fees
# --- Phase 2: build (network read only, no DB write yet) -----------------
try:
@@ -358,15 +358,22 @@ class RoundScheduler:
from_script=pool_script_obj,
utxos=utxos,
winner_address=winner_address,
winner_share_sats=winner_share,
winner_share_sats=winner_sats,
fee_address=fee_address,
commission_sats=commission_share,
change_address=pool_address,
fee_rate_sat_vb=fee_rate,
)
except InsufficientFundsError:
logger.exception("round %s payout failed: insufficient pool UTXOs", round_id)
await self._log_payout_failure(round_id, winner_user_id, "insufficient pool UTXOs")
except InsufficientFundsError as exc:
# Includes the "too_many_inputs" case: the pool holds enough, but spread over
# more UTXOs than one transaction may spend, so /admin has to say which. Since
# B-52 that means MAX_PAYOUT_TX_INPUTS, and participants are capped below it at
# bet time (bets/service.py), so reaching it now takes pool change accumulated
# over many rounds rather than one busy round — an operator consolidation job,
# not a dead end for the bets of the round in progress.
reason = "insufficient pool UTXOs" if exc.code == "insufficient_balance" else exc.code
logger.exception("round %s payout failed: %s", round_id, reason)
await self._log_payout_failure(round_id, winner_user_id, reason)
return
except Exception:
# Anything else — a malformed fee_address (EmbitError) or similar. This
+8
View File
@@ -18,6 +18,14 @@ _ACTIVE_STATUSES = ("open", "closing", "drawing", "paying_out")
# broken in a way we don't anticipate.
_OPEN_ROUND_ATTEMPTS = 3
# 70% winner / 30% fees. Hardcoded by design (see CLAUDE.md) — changing the split
# is a code change, not an admin-editable setting. Single source of truth so the
# advertised jackpot (rounds.py) and the actual payout (scheduler.py) can't diverge.
def winner_share(pool_amount_sats: int) -> int:
return pool_amount_sats * 70 // 100
async def get_active_round(session: AsyncSession) -> Round | None:
"""The round currently in progress (in any non-closed state), if any. Rounds
+8
View File
@@ -133,6 +133,7 @@ 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; }
td.payload-cell { max-width: 360px; white-space: pre-wrap; word-break: break-word; }
.table-wrap { overflow-x: auto; }
.badge {
@@ -144,6 +145,13 @@ td.addr, td.txid { font-family: 'Fira Code', monospace; word-break: break-all; m
background: #FEF3C7; color: #92400E; border-color: #F59E0B;
}
.badge.bug-status-open { background: #FEF3C7; color: #92400E; border-color: #F59E0B; }
.badge.bug-status-read { background: var(--color-background); color: var(--color-muted-foreground); }
.badge.bug-status-resolved { background: var(--color-success-bg); color: var(--color-success); border-color: var(--color-success); }
.bug-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
.bug-actions button { width: auto; margin-top: 0; min-height: 30px; padding: 4px 10px; font-size: 0.78rem; }
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);
+17
View File
@@ -30,6 +30,7 @@
<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="nav-tab" id="nav-bugreports" onclick="switchView('bugreports')">Segnalazioni bug</span>
<span class="spacer"></span>
<span class="chain-status-pill">
<span class="status-dot" id="chain-status-dot"></span>
@@ -153,6 +154,22 @@
</div>
</div>
<div class="view" id="view-bugreports">
<h2 class="section-title">Segnalazioni bug</h2>
<p class="hint">Segnalazioni inviate dagli utenti tramite la pagina "Segnala un bug".</p>
<div class="card">
<div class="table-wrap">
<table>
<thead>
<tr><th>ID</th><th>Descrizione</th><th>Contatto</th><th>Utente</th><th>Quando</th><th>Stato</th></tr>
</thead>
<tbody id="bugreports-tbody"></tbody>
</table>
</div>
</div>
</div>
</main>
</div>
+46 -3
View File
@@ -89,8 +89,8 @@ function stopChainStatusPolling() {
chainStatusInterval = null;
}
const VIEWS = ['parametri', 'utenti', 'round', 'pending', 'audit'];
const VIEW_LOADERS = { utenti: loadUsers, round: loadRounds, pending: loadPending, audit: loadAuditLog };
const VIEWS = ['parametri', 'utenti', 'round', 'pending', 'audit', 'bugreports'];
const VIEW_LOADERS = { utenti: loadUsers, round: loadRounds, pending: loadPending, audit: loadAuditLog, bugreports: loadBugReports };
let currentAdminView = 'parametri';
function switchView(name) {
@@ -109,7 +109,7 @@ function showDashboard() {
}
async function loadDashboard() {
await Promise.all([adminLoadConfig(), loadUsers(), loadRounds(), loadPending(), loadAuditLog()]);
await Promise.all([adminLoadConfig(), loadUsers(), loadRounds(), loadPending(), loadAuditLog(), loadBugReports()]);
}
async function adminLogin() {
@@ -346,6 +346,49 @@ async function loadAuditLog() {
}
}
const BUG_REPORT_STATUS_LABELS = { open: 'Da leggere', read: 'Presa in carico', resolved: 'Risolta' };
function bugReportBadge(status) {
return `<span class="badge bug-status-${escapeHtml(status)}">${escapeHtml(BUG_REPORT_STATUS_LABELS[status] || status)}</span>`;
}
async function loadBugReports() {
try {
const reports = await callAdmin('GET', '/admin/bug-reports');
const tbody = document.getElementById('bugreports-tbody');
tbody.innerHTML = reports.map((r) => `
<tr>
<td>${r.id}</td>
<td class="payload-cell">${escapeHtml(r.description)}</td>
<td>${r.contact ? escapeHtml(r.contact) : '—'}</td>
<td>${r.username ? escapeHtml(r.username) : '—'}</td>
<td>${fmtDate(r.created_at)}</td>
<td>
${bugReportBadge(r.status)}
<div class="bug-actions">
${r.status === 'open' ? `<button class="secondary" onclick="setBugReportStatus(${r.id}, 'read', this)">Segna come presa in carico</button>` : ''}
${r.status !== 'resolved' ? `<button class="secondary" onclick="setBugReportStatus(${r.id}, 'resolved', this)">Segna come risolta</button>` : ''}
${r.status !== 'open' ? `<button class="secondary" onclick="setBugReportStatus(${r.id}, 'open', this)">Riapri</button>` : ''}
</div>
</td>
</tr>
`).join('') || '<tr><td colspan="6" class="hint">Nessuna segnalazione ricevuta.</td></tr>';
} catch (e) {
toast('Errore nel caricamento segnalazioni: ' + e.message, 'error');
}
}
async function setBugReportStatus(reportId, newStatus, button) {
await withLoading(button, '…', async () => {
try {
await callAdmin('POST', '/admin/bug-reports/' + reportId + '/status', { status: newStatus });
await loadBugReports();
} catch (e) {
toast('Errore: ' + e.message, 'error');
}
});
}
document.getElementById('admin-token').addEventListener('keydown', (e) => {
if (e.key === 'Enter') adminLogin();
});
+12 -2
View File
@@ -488,11 +488,21 @@ async function refreshRound() {
// myUserId may not be loaded yet on the very first tick after a reload
// (refreshMe() and refreshRound() run concurrently) — fall back to the
// persisted result rather than risk showing nothing or the wrong side.
// winner_user_id is committed as soon as the draw picks a winner, but
// winner_amount_sats isn't set until the payout tx is built afterwards
// (a real Electrum round-trip later) — revealing a win before then would
// show "+— PLM". Only the winner's own reveal needs to wait for it.
const iWon = myUserId != null && data.winner_user_id === myUserId;
const amountReady = !iWon || data.winner_amount_sats != null;
const canReveal =
data.user_played && data.winner_user_id != null && (alreadyKnown || elapsedMs >= minMs) && myUserId != null;
data.user_played &&
data.winner_user_id != null &&
(alreadyKnown || elapsedMs >= minMs) &&
myUserId != null &&
amountReady;
if (canReveal) {
const won = data.winner_user_id === myUserId;
const won = iWon;
if (!alreadyKnown) {
persistResult(data.round_id, won, data.winner_amount_sats);
if (won) {
+154
View File
@@ -10,6 +10,26 @@ const TRANSLATIONS = {
'nav.guideTitle': 'Guide',
'nav.guideAria': 'Open the user guide',
'nav.bugReport': 'Report a bug',
'bugReport.pageTitle': 'Report a bug',
'bugReport.heading': 'Report a bug',
'bugReport.intro': 'Found a problem? Describe it below — your report goes straight to the admin panel.',
'bugReport.englishNotice': "Please write your bug report in English, regardless of the language you're browsing in — this helps us handle it faster.",
'bugReport.descriptionLabel': 'What happened?',
'bugReport.descriptionPlaceholder': 'Describe the bug: what you were doing, what you expected, and what happened instead.',
'bugReport.contactLabel': 'Contact (optional)',
'bugReport.contactPlaceholder': "Email or other contact, if you'd like a reply",
'bugReport.submitBtn': 'Send report',
'bugReport.submitting': 'Sending…',
'bugReport.blankError': 'Describe the bug before sending.',
'bugReport.successToast': 'Thanks! Report sent.',
'bugReport.errorPrefix': 'Error sending: ',
'bugReport.myReportsTitle': 'Your reports',
'bugReport.myReportsHint': 'Only reports sent from this account, with the status set by the admin team.',
'bugReport.myReportsEmpty': "You haven't sent any reports yet.",
'bugReport.statusOpen': 'Not read yet',
'bugReport.statusRead': 'Acknowledged',
'bugReport.statusResolved': 'Resolved',
'bugReport.backLink': 'Back to home',
'nav.logoutTitle': 'Log out',
'nav.logoutAria': 'Log out of your account',
'nav.deposit': 'Deposit',
@@ -119,6 +139,7 @@ const TRANSLATIONS = {
'error.network_unavailable': 'Not connected to the network, please try again shortly.',
'error.no_round_open': 'No round is open right now, please try again shortly.',
'error.round_closing': 'The current round is closing, please try again shortly.',
'error.round_full': 'This round has reached its maximum of {max_participants} players — wait for the next one, it opens shortly.',
'error.already_betting': 'You already have an active bet in the current round.',
'error.insufficient_balance': 'Insufficient balance.',
'error.balance_pending_confirmation': 'You have {pending_plm} PLM pending confirmation — it is not spendable yet.',
@@ -135,6 +156,7 @@ const TRANSLATIONS = {
'error.invalid_amount': 'Enter an amount greater than zero.',
'error.broadcast_failed': 'The network refused the transaction. Please try again shortly.',
'error.amount_below_dust_limit': 'The amount is too small to be sent.',
'error.too_many_inputs': 'Your balance is split across too many small deposits to be spent in a single transaction (max {max_inputs}). Please contact support to consolidate it.',
'error.withdrawal_to_own_address': 'That is your own deposit address — withdraw to an external wallet.',
'error.internal_error': 'Unexpected server error. Please try again shortly.',
'error.guide_unavailable': 'The guide is not available right now.',
@@ -152,6 +174,26 @@ const TRANSLATIONS = {
'nav.guideTitle': 'Guida',
'nav.guideAria': 'Apri la guida utente',
'nav.bugReport': 'Segnala un bug',
'bugReport.pageTitle': 'Segnala un bug',
'bugReport.heading': 'Segnala un bug',
'bugReport.intro': 'Hai trovato un problema? Descrivilo qui sotto: la segnalazione arriva direttamente al pannello di amministrazione.',
'bugReport.englishNotice': "Scrivi la segnalazione in inglese, indipendentemente dalla lingua che stai usando per navigare: questo ci aiuta a gestirla più velocemente.",
'bugReport.descriptionLabel': 'Cosa è successo?',
'bugReport.descriptionPlaceholder': 'Descrivi il bug: cosa stavi facendo, cosa ti aspettavi e cosa è successo invece.',
'bugReport.contactLabel': 'Contatto (opzionale)',
'bugReport.contactPlaceholder': 'Email o altro recapito, se vuoi essere ricontattato',
'bugReport.submitBtn': 'Invia segnalazione',
'bugReport.submitting': 'Invio…',
'bugReport.blankError': 'Descrivi il bug prima di inviare.',
'bugReport.successToast': 'Grazie! Segnalazione inviata.',
'bugReport.errorPrefix': "Errore nell'invio: ",
'bugReport.myReportsTitle': 'Le tue segnalazioni',
'bugReport.myReportsHint': "Solo le segnalazioni inviate da questo account, con lo stato aggiornato dall'amministrazione.",
'bugReport.myReportsEmpty': 'Non hai ancora inviato segnalazioni.',
'bugReport.statusOpen': 'Da leggere',
'bugReport.statusRead': 'Presa in carico',
'bugReport.statusResolved': 'Risolta',
'bugReport.backLink': 'Torna alla home',
'nav.logoutTitle': 'Esci',
'nav.logoutAria': "Esci dall'account",
'nav.deposit': 'Deposito',
@@ -258,6 +300,7 @@ const TRANSLATIONS = {
'error.network_unavailable': 'Nessuna connessione alla rete, riprova tra poco.',
'error.no_round_open': 'Nessun round aperto in questo momento, riprova tra poco.',
'error.round_closing': 'Il round corrente si sta chiudendo, riprova tra poco.',
'error.round_full': 'Questo round ha raggiunto il massimo di {max_participants} giocatori — aspetta il prossimo, si apre tra poco.',
'error.already_betting': 'Hai già una bet attiva nel round corrente.',
'error.insufficient_balance': 'Saldo insufficiente.',
'error.balance_pending_confirmation': 'Hai {pending_plm} PLM in attesa di conferma — non ancora disponibili per la spesa.',
@@ -274,6 +317,7 @@ const TRANSLATIONS = {
'error.invalid_amount': 'Inserisci un importo maggiore di zero.',
'error.broadcast_failed': 'La rete ha rifiutato la transazione. Riprova tra poco.',
'error.amount_below_dust_limit': "L'importo è troppo basso per essere inviato.",
'error.too_many_inputs': 'Il tuo saldo è suddiviso in troppi piccoli depositi per essere speso in una sola transazione (max {max_inputs}). Contatta l\'assistenza per consolidarlo.',
'error.withdrawal_to_own_address': 'Questo è il tuo indirizzo di deposito — preleva verso un wallet esterno.',
'error.internal_error': 'Errore inatteso del server. Riprova tra poco.',
'error.guide_unavailable': 'La guida non è disponibile in questo momento.',
@@ -291,6 +335,26 @@ const TRANSLATIONS = {
'nav.guideTitle': 'Guía',
'nav.guideAria': 'Abrir la guía del usuario',
'nav.bugReport': 'Reportar un error',
'bugReport.pageTitle': 'Reportar un error',
'bugReport.heading': 'Reportar un error',
'bugReport.intro': '¿Encontraste un problema? Descríbelo a continuación: el informe llega directamente al panel de administración.',
'bugReport.englishNotice': 'Escribe el informe en inglés, independientemente del idioma que estés usando para navegar: esto nos ayuda a gestionarlo más rápido.',
'bugReport.descriptionLabel': '¿Qué pasó?',
'bugReport.descriptionPlaceholder': 'Describe el error: qué estabas haciendo, qué esperabas y qué sucedió en su lugar.',
'bugReport.contactLabel': 'Contacto (opcional)',
'bugReport.contactPlaceholder': 'Correo u otro contacto, si quieres que te respondamos',
'bugReport.submitBtn': 'Enviar informe',
'bugReport.submitting': 'Enviando…',
'bugReport.blankError': 'Describe el error antes de enviarlo.',
'bugReport.successToast': '¡Gracias! Informe enviado.',
'bugReport.errorPrefix': 'Error al enviar: ',
'bugReport.myReportsTitle': 'Tus informes',
'bugReport.myReportsHint': 'Solo los informes enviados desde esta cuenta, con el estado actualizado por el equipo de administración.',
'bugReport.myReportsEmpty': 'Todavía no has enviado ningún informe.',
'bugReport.statusOpen': 'Sin leer',
'bugReport.statusRead': 'En curso',
'bugReport.statusResolved': 'Resuelto',
'bugReport.backLink': 'Volver al inicio',
'nav.logoutTitle': 'Salir',
'nav.logoutAria': 'Cerrar sesión',
'nav.deposit': 'Depósito',
@@ -397,6 +461,7 @@ const TRANSLATIONS = {
'error.network_unavailable': 'Sin conexión con la red, inténtalo de nuevo en un momento.',
'error.no_round_open': 'No hay ninguna ronda abierta ahora mismo, inténtalo de nuevo en un momento.',
'error.round_closing': 'La ronda actual se está cerrando, inténtalo de nuevo en un momento.',
'error.round_full': 'Esta ronda ha alcanzado su máximo de {max_participants} jugadores: espera la siguiente, se abre en breve.',
'error.already_betting': 'Ya tienes una apuesta activa en la ronda actual.',
'error.insufficient_balance': 'Saldo insuficiente.',
'error.balance_pending_confirmation': 'Tienes {pending_plm} PLM pendientes de confirmación — todavía no se pueden gastar.',
@@ -413,6 +478,7 @@ const TRANSLATIONS = {
'error.invalid_amount': 'Introduce un importe mayor que cero.',
'error.broadcast_failed': 'La red rechazó la transacción. Inténtalo de nuevo en un momento.',
'error.amount_below_dust_limit': 'El importe es demasiado pequeño para enviarse.',
'error.too_many_inputs': 'Tu saldo está repartido en demasiados depósitos pequeños para gastarse en una sola transacción (máx. {max_inputs}). Contacta con soporte para consolidarlo.',
'error.withdrawal_to_own_address': 'Esa es tu propia dirección de depósito — retira a una cartera externa.',
'error.internal_error': 'Error inesperado del servidor. Inténtalo de nuevo en un momento.',
'error.guide_unavailable': 'La guía no está disponible en este momento.',
@@ -430,6 +496,26 @@ const TRANSLATIONS = {
'nav.guideTitle': 'Guide',
'nav.guideAria': "Ouvrir le guide de l'utilisateur",
'nav.bugReport': 'Signaler un bug',
'bugReport.pageTitle': 'Signaler un bug',
'bugReport.heading': 'Signaler un bug',
'bugReport.intro': "Vous avez trouvé un problème ? Décrivez-le ci-dessous : le signalement arrive directement dans le panneau d'administration.",
'bugReport.englishNotice': "Rédigez votre signalement en anglais, quelle que soit la langue que vous utilisez pour naviguer : cela nous aide à le traiter plus rapidement.",
'bugReport.descriptionLabel': "Que s'est-il passé ?",
'bugReport.descriptionPlaceholder': "Décrivez le bug : ce que vous faisiez, ce que vous attendiez et ce qui s'est passé à la place.",
'bugReport.contactLabel': 'Contact (facultatif)',
'bugReport.contactPlaceholder': 'Email ou autre contact, si vous souhaitez une réponse',
'bugReport.submitBtn': 'Envoyer le signalement',
'bugReport.submitting': 'Envoi…',
'bugReport.blankError': "Décrivez le bug avant d'envoyer.",
'bugReport.successToast': 'Merci ! Signalement envoyé.',
'bugReport.errorPrefix': "Erreur lors de l'envoi : ",
'bugReport.myReportsTitle': 'Vos signalements',
'bugReport.myReportsHint': "Seulement les signalements envoyés depuis ce compte, avec le statut mis à jour par l'équipe d'administration.",
'bugReport.myReportsEmpty': "Vous n'avez encore envoyé aucun signalement.",
'bugReport.statusOpen': 'Non lu',
'bugReport.statusRead': 'Prise en charge',
'bugReport.statusResolved': 'Résolu',
'bugReport.backLink': "Retour à l'accueil",
'nav.logoutTitle': 'Se déconnecter',
'nav.logoutAria': 'Se déconnecter du compte',
'nav.deposit': 'Dépôt',
@@ -536,6 +622,7 @@ const TRANSLATIONS = {
'error.network_unavailable': 'Pas de connexion au réseau, réessayez dans un instant.',
'error.no_round_open': "Aucun round n'est ouvert pour le moment, réessayez dans un instant.",
'error.round_closing': 'Le round en cours est en train de se fermer, réessayez dans un instant.',
'error.round_full': 'Ce tour a atteint son maximum de {max_participants} joueurs — attendez le prochain, il ouvre dans un instant.',
'error.already_betting': 'Vous avez déjà une mise active dans le round en cours.',
'error.insufficient_balance': 'Solde insuffisant.',
'error.balance_pending_confirmation': 'Vous avez {pending_plm} PLM en attente de confirmation — pas encore disponibles.',
@@ -552,6 +639,7 @@ const TRANSLATIONS = {
'error.invalid_amount': 'Saisissez un montant supérieur à zéro.',
'error.broadcast_failed': 'Le réseau a refusé la transaction. Veuillez réessayer dans un instant.',
'error.amount_below_dust_limit': "Le montant est trop faible pour être envoyé.",
'error.too_many_inputs': 'Votre solde est réparti sur trop de petits dépôts pour être dépensé en une seule transaction (max {max_inputs}). Contactez le support pour le consolider.',
'error.withdrawal_to_own_address': "C'est votre propre adresse de dépôt — retirez vers un portefeuille externe.",
'error.internal_error': 'Erreur inattendue du serveur. Veuillez réessayer dans un instant.',
'error.guide_unavailable': "Le guide n'est pas disponible pour le moment.",
@@ -569,6 +657,26 @@ const TRANSLATIONS = {
'nav.guideTitle': 'Anleitung',
'nav.guideAria': 'Benutzerhandbuch öffnen',
'nav.bugReport': 'Fehler melden',
'bugReport.pageTitle': 'Fehler melden',
'bugReport.heading': 'Fehler melden',
'bugReport.intro': 'Ein Problem gefunden? Beschreibe es unten — die Meldung geht direkt an das Admin-Panel.',
'bugReport.englishNotice': 'Bitte schreibe die Fehlermeldung auf Englisch, unabhängig von der Sprache, die du gerade verwendest — das hilft uns, sie schneller zu bearbeiten.',
'bugReport.descriptionLabel': 'Was ist passiert?',
'bugReport.descriptionPlaceholder': 'Beschreibe den Fehler: was du getan hast, was du erwartet hast und was stattdessen passiert ist.',
'bugReport.contactLabel': 'Kontakt (optional)',
'bugReport.contactPlaceholder': 'E-Mail oder anderer Kontakt, falls du eine Antwort möchtest',
'bugReport.submitBtn': 'Meldung senden',
'bugReport.submitting': 'Senden…',
'bugReport.blankError': 'Beschreibe den Fehler, bevor du sendest.',
'bugReport.successToast': 'Danke! Meldung gesendet.',
'bugReport.errorPrefix': 'Fehler beim Senden: ',
'bugReport.myReportsTitle': 'Deine Meldungen',
'bugReport.myReportsHint': 'Nur Meldungen, die von diesem Konto gesendet wurden, mit dem vom Admin-Team aktualisierten Status.',
'bugReport.myReportsEmpty': 'Du hast noch keine Meldungen gesendet.',
'bugReport.statusOpen': 'Ungelesen',
'bugReport.statusRead': 'In Bearbeitung',
'bugReport.statusResolved': 'Gelöst',
'bugReport.backLink': 'Zurück zur Startseite',
'nav.logoutTitle': 'Abmelden',
'nav.logoutAria': 'Vom Konto abmelden',
'nav.deposit': 'Einzahlung',
@@ -675,6 +783,7 @@ const TRANSLATIONS = {
'error.network_unavailable': 'Keine Verbindung zum Netzwerk, bitte versuche es gleich erneut.',
'error.no_round_open': 'Derzeit ist keine Runde offen, bitte versuche es gleich erneut.',
'error.round_closing': 'Die laufende Runde wird gerade geschlossen, bitte versuche es gleich erneut.',
'error.round_full': 'Diese Runde hat ihr Maximum von {max_participants} Spielern erreicht — warten Sie auf die nächste, sie beginnt in Kürze.',
'error.already_betting': 'Du hast bereits eine aktive Wette in der laufenden Runde.',
'error.insufficient_balance': 'Nicht genügend Guthaben.',
'error.balance_pending_confirmation': 'Sie haben {pending_plm} PLM, die noch auf Bestätigung warten — noch nicht verfügbar.',
@@ -691,6 +800,7 @@ const TRANSLATIONS = {
'error.invalid_amount': 'Gib einen Betrag größer als null ein.',
'error.broadcast_failed': 'Das Netzwerk hat die Transaktion abgelehnt. Bitte versuche es in Kürze erneut.',
'error.amount_below_dust_limit': 'Der Betrag ist zu klein, um gesendet zu werden.',
'error.too_many_inputs': 'Ihr Guthaben ist auf zu viele kleine Einzahlungen verteilt, um in einer einzigen Transaktion ausgegeben zu werden (max. {max_inputs}). Bitte wenden Sie sich an den Support, um es zusammenzufassen.',
'error.withdrawal_to_own_address': 'Das ist deine eigene Einzahlungsadresse — zahle auf eine externe Wallet aus.',
'error.internal_error': 'Unerwarteter Serverfehler. Bitte versuche es in Kürze erneut.',
'error.guide_unavailable': 'Die Anleitung ist derzeit nicht verfügbar.',
@@ -708,6 +818,26 @@ const TRANSLATIONS = {
'nav.guideTitle': 'Инструкция',
'nav.guideAria': 'Открыть руководство пользователя',
'nav.bugReport': 'Сообщить об ошибке',
'bugReport.pageTitle': 'Сообщить об ошибке',
'bugReport.heading': 'Сообщить об ошибке',
'bugReport.intro': 'Нашли проблему? Опишите её ниже — сообщение сразу попадёт в панель администратора.',
'bugReport.englishNotice': 'Пожалуйста, опишите ошибку на английском языке, независимо от языка интерфейса — это поможет нам обработать её быстрее.',
'bugReport.descriptionLabel': 'Что произошло?',
'bugReport.descriptionPlaceholder': 'Опишите ошибку: что вы делали, что ожидали и что произошло вместо этого.',
'bugReport.contactLabel': 'Контакт (необязательно)',
'bugReport.contactPlaceholder': 'Email или другой контакт, если хотите получить ответ',
'bugReport.submitBtn': 'Отправить сообщение',
'bugReport.submitting': 'Отправка…',
'bugReport.blankError': 'Опишите ошибку перед отправкой.',
'bugReport.successToast': 'Спасибо! Сообщение отправлено.',
'bugReport.errorPrefix': 'Ошибка отправки: ',
'bugReport.myReportsTitle': 'Ваши сообщения',
'bugReport.myReportsHint': 'Только сообщения, отправленные с этого аккаунта, со статусом, обновлённым администрацией.',
'bugReport.myReportsEmpty': 'Вы ещё не отправляли сообщений.',
'bugReport.statusOpen': 'Не прочитано',
'bugReport.statusRead': 'В обработке',
'bugReport.statusResolved': 'Решено',
'bugReport.backLink': 'Назад на главную',
'nav.logoutTitle': 'Выйти',
'nav.logoutAria': 'Выйти из аккаунта',
'nav.deposit': 'Депозит',
@@ -814,6 +944,7 @@ const TRANSLATIONS = {
'error.network_unavailable': 'Нет соединения с сетью, повторите попытку чуть позже.',
'error.no_round_open': 'Сейчас нет открытого раунда, повторите попытку чуть позже.',
'error.round_closing': 'Текущий раунд закрывается, повторите попытку чуть позже.',
'error.round_full': 'В этом раунде достигнут максимум участников ({max_participants}) — дождитесь следующего, он начнётся совсем скоро.',
'error.already_betting': 'У вас уже есть активная ставка в текущем раунде.',
'error.insufficient_balance': 'Недостаточно средств.',
'error.balance_pending_confirmation': 'У вас есть {pending_plm} PLM, ожидающих подтверждения — они пока недоступны для расходования.',
@@ -830,6 +961,7 @@ const TRANSLATIONS = {
'error.invalid_amount': 'Введите сумму больше нуля.',
'error.broadcast_failed': 'Сеть отклонила транзакцию. Попробуйте ещё раз через минуту.',
'error.amount_below_dust_limit': 'Сумма слишком мала для отправки.',
'error.too_many_inputs': 'Ваш баланс разбит на слишком много мелких депозитов, чтобы потратить его одной транзакцией (максимум {max_inputs}). Обратитесь в поддержку для консолидации.',
'error.withdrawal_to_own_address': 'Это ваш собственный адрес для депозита — выводите на внешний кошелёк.',
'error.internal_error': 'Непредвиденная ошибка сервера. Попробуйте ещё раз через минуту.',
'error.guide_unavailable': 'Руководство сейчас недоступно.',
@@ -847,6 +979,26 @@ const TRANSLATIONS = {
'nav.guideTitle': '指南',
'nav.guideAria': '打开用户指南',
'nav.bugReport': '报告问题',
'bugReport.pageTitle': '报告问题',
'bugReport.heading': '报告问题',
'bugReport.intro': '发现问题了吗?请在下面描述——您的反馈会直接发送到管理员面板。',
'bugReport.englishNotice': '请用英文描述问题,无论您当前使用的是哪种语言界面——这有助于我们更快处理。',
'bugReport.descriptionLabel': '发生了什么?',
'bugReport.descriptionPlaceholder': '描述问题:您当时在做什么、期望的结果是什么,以及实际发生了什么。',
'bugReport.contactLabel': '联系方式(可选)',
'bugReport.contactPlaceholder': '如果希望得到回复,请留下邮箱或其他联系方式',
'bugReport.submitBtn': '发送反馈',
'bugReport.submitting': '发送中…',
'bugReport.blankError': '请先描述问题再发送。',
'bugReport.successToast': '谢谢!反馈已发送。',
'bugReport.errorPrefix': '发送出错:',
'bugReport.myReportsTitle': '您的反馈',
'bugReport.myReportsHint': '仅显示此账户发送的反馈,状态由管理团队更新。',
'bugReport.myReportsEmpty': '您还没有发送过反馈。',
'bugReport.statusOpen': '待处理',
'bugReport.statusRead': '处理中',
'bugReport.statusResolved': '已解决',
'bugReport.backLink': '返回首页',
'nav.logoutTitle': '退出登录',
'nav.logoutAria': '退出账户',
'nav.deposit': '存款',
@@ -953,6 +1105,7 @@ const TRANSLATIONS = {
'error.network_unavailable': '未连接到网络,请稍后重试。',
'error.no_round_open': '当前没有开放的回合,请稍后重试。',
'error.round_closing': '当前回合正在结束,请稍后重试。',
'error.round_full': '本轮已达到 {max_participants} 名玩家的上限 —— 请等待下一轮,很快就会开始。',
'error.already_betting': '你在当前回合已有一笔有效下注。',
'error.insufficient_balance': '余额不足。',
'error.balance_pending_confirmation': '您有 {pending_plm} PLM 待确认 —— 尚不可用于支出。',
@@ -969,6 +1122,7 @@ const TRANSLATIONS = {
'error.invalid_amount': '请输入大于零的金额。',
'error.broadcast_failed': '网络拒绝了该交易,请稍后重试。',
'error.amount_below_dust_limit': '金额过小,无法发送。',
'error.too_many_inputs': '您的余额分散在过多的小额存款中,无法在一笔交易中花费(最多 {max_inputs} 笔)。请联系客服进行归集。',
'error.withdrawal_to_own_address': '这是你自己的充值地址 — 请提现到外部钱包。',
'error.internal_error': '服务器发生意外错误,请稍后重试。',
'error.guide_unavailable': '指南当前不可用。',
+159 -6
View File
@@ -1,16 +1,169 @@
<!DOCTYPE html>
<html lang="it">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Segnala un bug — PLM Lottery</title>
<title data-i18n="bugReport.pageTitle">Report a bug</title>
<link rel="icon" type="image/svg+xml" href="/logo.svg">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="app-shell">
<h1>Segnala un bug</h1>
<p>Questa pagina è un placeholder. Il modulo per la segnalazione dei bug sarà disponibile qui a breve.</p>
<p><a class="link" href="/">&larr; Torna alla home</a></p>
<div class="app-shell app-shell-bugreport">
<div class="bugreport-topbar">
<a class="brand" href="/">
<img class="brand-mark" src="/logo.svg" alt="">
PLM Lottery
</a>
<div class="bugreport-topbar-right">
<a class="back-home-btn" href="/">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
<span data-i18n="bugReport.backLink">Back to home</span>
</a>
<select id="lang-switcher" class="lang-switcher" onchange="setLanguage(this.value)" aria-label="Language">
<option value="en">English</option>
<option value="it">Italiano</option>
<option value="es">Español</option>
<option value="fr">Français</option>
<option value="de">Deutsch</option>
<option value="ru">Русский</option>
<option value="zh">中文</option>
</select>
</div>
</div>
<div class="bugreport-hero">
<div class="bugreport-hero-icon">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v5"/><path d="M12 16h.01"/></svg>
</div>
<div>
<h1 data-i18n="bugReport.heading">Report a bug</h1>
<p data-i18n="bugReport.intro">Found a problem? Describe it below — your report goes straight to the admin panel.</p>
</div>
</div>
<div class="card" id="report-form">
<div class="field-note" id="english-notice">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
<span data-i18n="bugReport.englishNotice">Please write your bug report in English, regardless of the language you're browsing in — this helps us handle it faster.</span>
</div>
<label for="bug-description" data-i18n="bugReport.descriptionLabel">What happened?</label>
<textarea id="bug-description" rows="6" maxlength="2000" data-i18n-placeholder="bugReport.descriptionPlaceholder" oninput="updateCharCount()"></textarea>
<div class="char-count" id="char-count">0 / 2000</div>
<label for="bug-contact" data-i18n="bugReport.contactLabel">Contact (optional)</label>
<input id="bug-contact" type="text" maxlength="256" data-i18n-placeholder="bugReport.contactPlaceholder">
<button onclick="submitBugReport()" id="bug-submit-btn" data-i18n="bugReport.submitBtn">Send report</button>
</div>
<div class="hidden" id="my-reports-section">
<p class="section-label" data-i18n="bugReport.myReportsTitle">Your reports</p>
<div class="card">
<p class="hint" data-i18n="bugReport.myReportsHint">Only reports sent from this account, with the status set by the admin team.</p>
<div id="my-reports-list"></div>
</div>
</div>
</div>
<div id="toast-container" aria-live="polite"></div>
<script src="/i18n.js"></script>
<script>
function toast(message, type) {
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = 'toast ' + type;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), 4000);
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function updateCharCount() {
const field = document.getElementById('bug-description');
document.getElementById('char-count').textContent = field.value.length + ' / ' + field.maxLength;
}
async function submitBugReport() {
const btn = document.getElementById('bug-submit-btn');
const description = document.getElementById('bug-description').value.trim();
const contact = document.getElementById('bug-contact').value.trim();
if (!description) {
toast(t('bugReport.blankError'), 'error');
return;
}
const headers = { 'Content-Type': 'application/json' };
const token = localStorage.getItem('plm_token');
if (token) headers['Authorization'] = 'Bearer ' + token;
btn.disabled = true;
const original = btn.textContent;
btn.textContent = t('bugReport.submitting');
try {
const res = await fetch('/bug-reports', {
method: 'POST',
headers,
body: JSON.stringify({ description, contact: contact || null }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail?.message || data.detail || res.statusText);
document.getElementById('bug-description').value = '';
document.getElementById('bug-contact').value = '';
updateCharCount();
toast(t('bugReport.successToast'), 'success');
loadMyBugReports();
} catch (e) {
toast(t('bugReport.errorPrefix') + e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = original;
applyStaticTranslations(btn);
}
}
async function loadMyBugReports() {
const token = localStorage.getItem('plm_token');
const section = document.getElementById('my-reports-section');
if (!token) {
section.classList.add('hidden');
return;
}
try {
const res = await fetch('/bug-reports/mine', { headers: { Authorization: 'Bearer ' + token } });
if (!res.ok) {
section.classList.add('hidden');
return;
}
const reports = await res.json();
section.classList.remove('hidden');
const list = document.getElementById('my-reports-list');
list.innerHTML = reports.map((r) => `
<div class="report-row">
<span class="badge bug-status-${escapeHtml(r.status)}">${escapeHtml(t('bugReport.status' + r.status.charAt(0).toUpperCase() + r.status.slice(1)))}</span>
<span class="report-row-desc" title="${escapeHtml(r.description)}">${escapeHtml(r.description)}</span>
<span class="report-row-date">${new Date(r.created_at).toLocaleDateString(currentDateLocale(), { day: 'numeric', month: 'short', year: 'numeric' })}</span>
</div>
`).join('') || `<p class="hint report-empty">${escapeHtml(t('bugReport.myReportsEmpty'))}</p>`;
} catch (e) {
section.classList.add('hidden');
}
}
// Re-renders server-rendered content (my reports list) on a language switch,
// the same split app.js uses between data-i18n (static markup) and t() (data).
function onLanguageChange() {
loadMyBugReports();
}
updateCharCount();
loadMyBugReports();
</script>
</body>
</html>
+91 -3
View File
@@ -74,16 +74,17 @@ h1, h2, h3 { font-family: inherit; letter-spacing: -0.01em; }
label { display: block; font-size: 0.85rem; font-weight: 500; color: var(--color-muted-foreground); margin-top: 14px; margin-bottom: 6px; }
label:first-child { margin-top: 0; }
input {
input, textarea {
width: 100%; min-height: 44px; padding: 10px 12px; font-size: 0.95rem; font-family: inherit;
border: 1px solid var(--color-border); border-radius: var(--radius-sm); background: var(--color-surface);
color: var(--color-foreground); transition: border-color 150ms, box-shadow 150ms;
}
input:focus {
textarea { resize: vertical; }
input:focus, textarea:focus {
outline: none; border-color: var(--color-ring);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-ring) 25%, transparent);
}
input:disabled { background: var(--color-surface-inset); color: var(--color-muted-foreground); }
input:disabled, textarea:disabled { background: var(--color-surface-inset); color: var(--color-muted-foreground); }
button {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
@@ -253,6 +254,93 @@ button.link:hover, a.link:hover { filter: none; color: var(--color-foreground);
.toast.error { background: var(--color-destructive-bg); color: var(--color-destructive); }
@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
/* --- /report-bug: a standalone page (no logged-in navbar), so it gets its
own slim top bar rather than the app's bottom tab bar / sticky header. --- */
.app-shell-bugreport { padding-bottom: 32px; }
.bugreport-topbar {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 4px 0 20px; margin-bottom: 20px; border-bottom: 1px solid var(--color-border);
}
.bugreport-topbar .brand {
display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 1rem;
letter-spacing: -0.01em; color: var(--color-foreground); text-decoration: none;
}
.bugreport-topbar .brand-mark { width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0; display: block; }
.bugreport-topbar-right { display: flex; align-items: center; gap: 12px; }
/* Pill button, same idiom as .trust-pill / .chain-status-pill elsewhere on the
site: a bordered chip rather than a bare text link, so "go back" reads as an
actual control instead of fading into the surrounding copy. */
.back-home-btn {
display: inline-flex; align-items: center; gap: 6px;
font-size: 0.8rem; font-weight: 500; color: var(--color-muted-foreground);
background: var(--color-surface); border: 1px solid var(--color-border);
padding: 6px 12px 6px 10px; border-radius: 999px; text-decoration: none;
transition: color 150ms, border-color 150ms, background 150ms;
}
.back-home-btn .icon { width: 15px; height: 15px; }
.back-home-btn:hover {
color: var(--color-foreground); background: var(--color-surface-inset);
border-color: color-mix(in srgb, var(--color-ring) 40%, var(--color-border));
}
.back-home-btn:focus-visible { outline: 2px solid var(--color-ring); outline-offset: 2px; }
.bugreport-hero { display: flex; align-items: flex-start; gap: 14px; margin-bottom: 20px; }
.bugreport-hero-icon {
width: 44px; height: 44px; flex-shrink: 0; border-radius: 999px;
background: color-mix(in srgb, var(--color-primary) 14%, transparent);
color: var(--color-primary);
display: flex; align-items: center; justify-content: center;
}
.bugreport-hero-icon .icon { width: 22px; height: 22px; }
.bugreport-hero h1 { font-size: 1.3rem; font-weight: 700; margin: 2px 0 4px; text-wrap: balance; }
.bugreport-hero p { color: var(--color-muted-foreground); font-size: 0.9rem; margin: 0; max-width: 46ch; }
/* Info callout, anchored inside the form card right above the field it
applies to — not a warning (that's what the amber status badges below are
for), so it gets the accent hue instead, keeping the two meanings visually
distinct. */
.field-note {
display: flex; align-items: flex-start; gap: 10px;
background: color-mix(in srgb, var(--color-accent) 10%, transparent);
border: 1px solid color-mix(in srgb, var(--color-accent) 28%, transparent);
color: color-mix(in srgb, var(--color-accent) 75%, var(--color-foreground));
border-radius: var(--radius-sm); padding: 10px 12px; font-size: 0.82rem; line-height: 1.4;
margin-bottom: 16px;
}
.field-note .icon { width: 16px; height: 16px; margin-top: 1px; flex-shrink: 0; }
.char-count {
font-variant-numeric: tabular-nums; text-align: right;
font-size: 0.75rem; color: var(--color-muted-foreground); margin-top: 4px;
}
.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);
flex-shrink: 0;
}
.badge.bug-status-open { background: color-mix(in srgb, var(--color-primary) 16%, transparent); color: #92400E; border-color: color-mix(in srgb, var(--color-primary) 55%, transparent); }
.badge.bug-status-read { background: var(--color-background); color: var(--color-muted-foreground); }
.badge.bug-status-resolved { background: var(--color-success-bg); color: var(--color-success); border-color: var(--color-success); }
.report-row {
display: flex; flex-wrap: wrap; align-items: center; gap: 10px;
padding: 12px 0; border-bottom: 1px solid var(--color-border);
}
.report-row:first-child { padding-top: 0; }
.report-row:last-child { padding-bottom: 0; border-bottom: none; }
.report-row-desc {
flex: 1 1 200px; font-size: 0.88rem;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.report-row-date {
font-size: 0.78rem; color: var(--color-muted-foreground); white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.report-empty { margin: 0; }
/* --- landing hero (shown only when logged out) --- */
body {
position: relative;
+19 -1
View File
@@ -38,6 +38,15 @@ async def compute_pending_balance(session: AsyncSession, user: User) -> tuple[in
user's own address. Adding that to cached_balance_sats gives the balance the
user will end up with once everything currently in flight confirms.
The change output's own confirmation is credited by two independent, unordered
paths: the Electrum listener (event-driven, near-instant — app/deposits/service.py
turns it into a UtxoEvent and folds it into cached_balance_sats via
recompute_balance) and this module's PendingTransaction.status flip
(app/tx/confirmation.py, polled every 10s). The listener usually wins that race,
so for the gap until the poller catches up the row is still "pending" here while
the same sats are already inside cached_balance_sats — double-counting the
change unless excluded below.
Returns (pending_inclusive_balance_sats, has_pending) — has_pending tells the
caller whether this differs from the confirmed-only balance at all.
"""
@@ -54,10 +63,19 @@ async def compute_pending_balance(session: AsyncSession, user: User) -> tuple[in
)
).all()
already_credited = {
(txid, vout)
for txid, vout in (
await session.execute(select(UtxoEvent.txid, UtxoEvent.vout).where(UtxoEvent.user_id == user.id))
).all()
}
pending_change_sats = 0
for row in pending:
tx = Transaction.parse(bytes.fromhex(row.raw_tx_hex))
for out in tx.vout:
for vout, out in enumerate(tx.vout):
if (row.current_txid, vout) in already_credited:
continue
if out.script_pubkey.address(network=PLM_MAINNET) == user.address:
pending_change_sats += out.value
+67 -6
View File
@@ -33,15 +33,53 @@ DUST_LIMIT_SATS = 294
# eating further and further into the sender's change with no limit.
MAX_FEE_RATE_SAT_VB = 10_000
# Ceiling on how many UTXOs one *user* transaction (bet, withdrawal) may spend (B-48).
# Every extra input costs ~68 vbytes of fee, and that fee comes out of the amount being
# moved — so an address fragmented into hundreds of small deposits would silently erode
# its own bet (shrinking the user's share of the pool) or withdrawal. Failing the build
# with a translatable error is the honest outcome; consolidating the address is the way
# out. This is a *user-protection* limit, which is why the payout gets its own, far
# higher one below.
MAX_TX_INPUTS = 50
# Ceiling on the payout's inputs (B-52). The payout is not a user spending their own
# fragmented balance: it drains the pool, whose UTXO count is simply the number of bets
# in the round, and its fee comes out of a 70% share of that whole pool. So the erosion
# argument behind MAX_TX_INPUTS doesn't apply here — 400 inputs at 1 sat/vB cost ~27_300
# sat, i.e. ~0.00027 PLM out of the winner's share — and reusing that limit was what made
# any round past ~50 participants unpayable: select_utxos raised too_many_inputs, the
# round stayed "paying_out" retrying forever, and since no new round may open while one
# is active, the whole lottery stopped with the pool stuck (B-52).
#
# What actually bounds this is relay policy: a non-standard transaction is refused at
# broadcast past 100 kvB, which at ~68 vbytes per input is ~1470 inputs. 500 stays at
# roughly a third of that budget, and signing that many inputs costs ~0.4s of event loop
# (measured), once per round, inside a background task.
MAX_PAYOUT_TX_INPUTS = 500
# The most participants one round may hold (B-52). Enforced where the money is not yet
# committed — app/bets/service.py refuses the bet — instead of being discovered at payout
# time, when the bets are already in the pool and there is no way back. Deliberately below
# MAX_PAYOUT_TX_INPUTS: the payout also has to be able to spend whatever change UTXOs
# earlier rounds left in the pool, so the gap is the headroom for those.
MAX_PARTICIPANTS_PER_ROUND = 400
class InsufficientFundsError(Exception):
"""`code` is the machine-readable identifier the API layer forwards to the
client so it can translate the failure (see app/api/errors.py); the message
itself stays English."""
itself stays English, and `params` carries the values it interpolates so the
translation can place them wherever its own grammar needs them."""
def __init__(self, message: str, code: str = "insufficient_balance") -> None:
def __init__(
self,
message: str,
code: str = "insufficient_balance",
**params: int | str,
) -> None:
super().__init__(message)
self.code = code
self.params = params
@dataclass
@@ -65,14 +103,33 @@ def estimate_vsize(n_inputs: int, n_outputs: int) -> int:
return _TX_OVERHEAD_VBYTES + n_inputs * _P2WPKH_INPUT_VBYTES + n_outputs * _P2WPKH_OUTPUT_VBYTES
def select_utxos(utxos: list[Utxo], target_sats: int) -> tuple[list[Utxo], int]:
def select_utxos(
utxos: list[Utxo], target_sats: int, max_inputs: int = MAX_TX_INPUTS
) -> tuple[list[Utxo], int]:
"""Greedily select UTXOs (largest first, to minimize input count) covering
target_sats — the amount deducted from the sender's balance. The fee is paid
out of target_sats (see build_signed_transaction), not added on top of it."""
out of target_sats (see build_signed_transaction), not added on top of it.
At most `max_inputs` are ever selected (B-48): if the largest `max_inputs`
UTXOs don't cover the target, the balance is there but too fragmented to spend
in one transaction, which is a different failure from having no funds at all
and gets its own code.
The cap is a parameter, not the constant it used to be, because the two callers
want different ones (B-52): MAX_TX_INPUTS protects a user from a fee that would
eat into their own bet/withdrawal, while the payout drains a pool holding one
UTXO per bet and needs MAX_PAYOUT_TX_INPUTS to be able to pay a full round at
all."""
ordered = sorted(utxos, key=lambda u: u.amount_sats, reverse=True)
selected: list[Utxo] = []
total = 0
for utxo in ordered:
if len(selected) == max_inputs:
raise InsufficientFundsError(
f"balance too fragmented: more than {max_inputs} inputs would be needed",
code="too_many_inputs",
max_inputs=max_inputs,
)
selected.append(utxo)
total += utxo.amount_sats
if total >= target_sats:
@@ -177,9 +234,13 @@ def build_payout_transaction(
absorbs the tx fee — the commission (fee_address) output is untouched.
As in build_signed_transaction, dust-sized pool change is left to the fee
rather than creating an unrelayable output (B-06)."""
rather than creating an unrelayable output (B-06).
Selection uses MAX_PAYOUT_TX_INPUTS, not the much stricter user-facing
MAX_TX_INPUTS (B-52) — the pool holds one UTXO per bet, so the user-protection
cap made every round past ~50 participants impossible to pay."""
target = winner_share_sats + commission_sats
selected, total_in = select_utxos(utxos, target)
selected, total_in = select_utxos(utxos, target, max_inputs=MAX_PAYOUT_TX_INPUTS)
fee = estimate_vsize(len(selected), 3) * fee_rate_sat_vb # winner + commission + pool change
winner_amount = winner_share_sats - fee
if winner_amount < DUST_LIMIT_SATS:
+2 -1
View File
@@ -89,7 +89,7 @@ async def request_withdrawal(
fee_rate_sat_vb=config.fee_rate_sat_vb,
)
except InsufficientFundsError as exc:
raise WithdrawalError(exc.code, str(exc)) from exc
raise WithdrawalError(exc.code, str(exc), **exc.params) from exc
# Persist the intent before broadcasting, and only promote the rows once the
# network has accepted the tx — same two-phase shape as place_bet (B-08).
@@ -173,3 +173,4 @@ async def _release_failed_withdrawal(
user_id=user_id,
)
await session.commit()
broadcaster.publish() # the reserved UTXOs are spendable again — refetch the balance (B-49)
@@ -0,0 +1,41 @@
"""replace bug_reports.resolved with a three-state status
Revision ID: be71fdac734e
Revises: ee8508d98d34
Create Date: 2026-07-31 15:33:51.780062
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'be71fdac734e'
down_revision: Union[str, Sequence[str], None] = 'ee8508d98d34'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema, preserving existing rows: resolved=True -> 'resolved', else 'open'.
'read' has no equivalent in the old boolean, so nothing backfills into it —
every previously-open report starts the new lifecycle at 'open', which is
correct (nobody had acknowledged it yet)."""
op.add_column('bug_reports', sa.Column('status', sa.String(length=16), nullable=True))
op.execute("UPDATE bug_reports SET status = CASE WHEN resolved THEN 'resolved' ELSE 'open' END")
with op.batch_alter_table('bug_reports') as batch_op:
batch_op.alter_column('status', nullable=False)
batch_op.drop_column('resolved')
def downgrade() -> None:
"""Downgrade schema. 'read' collapses back into resolved=False — the same loss
of information any boolean-from-enum downgrade has."""
op.add_column('bug_reports', sa.Column('resolved', sa.BOOLEAN(), nullable=True))
op.execute("UPDATE bug_reports SET resolved = (status = 'resolved')")
with op.batch_alter_table('bug_reports') as batch_op:
batch_op.alter_column('resolved', nullable=False)
batch_op.drop_column('status')
@@ -0,0 +1,41 @@
"""add bug_reports table
Revision ID: ee8508d98d34
Revises: 87a0c640355c
Create Date: 2026-07-31 15:14:14.288552
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'ee8508d98d34'
down_revision: Union[str, Sequence[str], None] = '87a0c640355c'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('bug_reports',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('contact', sa.String(length=256), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('resolved', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('bug_reports')
# ### end Alembic commands ###
+48
View File
@@ -91,6 +91,54 @@ async def test_pending_balance_matches_confirmed_when_nothing_in_flight(session_
assert pending_balance == 2_000_000_000
async def test_pending_balance_does_not_double_count_change_already_credited(session_factory):
"""The Electrum listener (event-driven) and the confirmation poller (10s
cadence) independently react to the same change output confirming. When the
listener wins that race — the common case — the change is already a
UtxoEvent inside cached_balance_sats while the PendingTransaction row is
still "pending". compute_pending_balance must not add the change a second
time in that window."""
user_id = await _make_funded_user(session_factory, 4, 1_500_000_000)
client = FakeElectrumClient()
async with session_factory() as session:
user = await session.get(User, user_id)
await place_bet(session, client, user)
async with session_factory() as session:
pending = (await session.scalars(select(PendingTransaction))).one()
from embit.transaction import Transaction
from app.wallet.plm_network import PLM_MAINNET
tx = Transaction.parse(bytes.fromhex(pending.raw_tx_hex))
change_vout, change_out = next(
(i, out) for i, out in enumerate(tx.vout) if out.script_pubkey.address(network=PLM_MAINNET) == user.address
)
user = await session.get(User, user_id)
# Simulate the listener having already credited the change output as
# confirmed, before the poller has flipped `pending.status`.
session.add(
UtxoEvent(
user_id=user_id,
txid=pending.current_txid,
vout=change_vout,
amount_sats=change_out.value,
confirmed_height=101,
)
)
await recompute_balance(session, user_id)
await session.commit()
async with session_factory() as session:
user = await session.get(User, user_id)
pending_balance, has_pending = await compute_pending_balance(session, user)
assert has_pending is True # the PendingTransaction row is still "pending"
assert pending_balance == user.cached_balance_sats # already-credited change isn't added again
async def test_pending_balance_ignores_other_users_pending_transactions(session_factory):
user_id = await _make_funded_user(session_factory, 2, 2_000_000_000)
other_user_id = await _make_funded_user(session_factory, 3, 1_500_000_000)
+127 -1
View File
@@ -1,15 +1,17 @@
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import select
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.bets.service import BetError, place_bet
from app.config import settings
from app.db.base import Base
from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, RoundParticipant, User, UtxoEvent
from app.rounds.events import broadcaster
from app.rounds.service import open_new_round_if_needed
from app.wallet.hd import derive_user_address
from app.wallet.psbt_builder import MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS
class FakeElectrumClient:
@@ -91,6 +93,103 @@ async def test_place_bet_rejects_insufficient_balance(session_factory):
await place_bet(session, client, user)
async def test_place_bet_reports_a_too_fragmented_balance_distinctly(session_factory): # B-48
# 100 x 0.15 PLM = 15 PLM, plenty for a 10 PLM bet, but the 50 largest inputs
# only add up to 7.5 PLM — so the build must fail with its own code, not with
# the "you have no funds" one, and must carry the cap for the translation.
user_id = await _make_funded_user(session_factory, 20, 15_000_000)
async with session_factory() as session:
for i in range(99):
session.add(
UtxoEvent(
user_id=user_id,
txid=f"{i:064x}",
vout=0,
amount_sats=15_000_000,
confirmed_height=100,
)
)
await session.commit()
client = FakeElectrumClient()
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(BetError) as excinfo:
await place_bet(session, client, user)
assert excinfo.value.code == "too_many_inputs"
assert excinfo.value.params == {"max_inputs": MAX_TX_INPUTS}
assert not client.broadcasted
async def _fill_round_with_participants(session_factory, round_id: int, count: int) -> None:
"""Participant rows only, no real bets: what the cap counts is rows, and building
`count` genuine transactions would just make the test slow without exercising
anything the other tests don't already cover."""
async with session_factory() as session:
for i in range(count):
session.add(
RoundParticipant(
round_id=round_id,
user_id=10_000 + i, # placeholder ids; the cap check never joins users
bet_amount_sats=1_000_000_000,
bet_txid=f"{i:064x}",
status="confirmed",
)
)
await session.commit()
async def test_place_bet_rejects_the_bet_past_the_participant_cap(session_factory): # B-52
"""The payout has to spend one pool UTXO per bet, so a round is only ever allowed
to grow to what a single payout transaction can drain. Enforced here, before the
player's money moves — not discovered at payout time, when the bets are already in
the pool and the round can no longer be paid at all."""
user_id = await _make_funded_user(session_factory, 30, 3_000_000_000)
client = FakeElectrumClient()
async with session_factory() as session:
round_ = await open_new_round_if_needed(session)
await session.commit()
round_id = round_.id
await _fill_round_with_participants(session_factory, round_id, MAX_PARTICIPANTS_PER_ROUND)
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(BetError) as excinfo:
await place_bet(session, client, user)
assert excinfo.value.code == "round_full"
assert excinfo.value.params == {"max_participants": MAX_PARTICIPANTS_PER_ROUND}
assert not client.broadcasted
# Refused cleanly: no participant row, and the user's UTXO is still spendable.
async with session_factory() as session:
assert await session.scalar(
select(func.count()).select_from(RoundParticipant).where(RoundParticipant.round_id == round_id)
) == MAX_PARTICIPANTS_PER_ROUND
utxo = (await session.scalars(select(UtxoEvent).where(UtxoEvent.user_id == user_id))).one()
assert utxo.spent_txid is None
async def test_place_bet_still_accepts_the_last_slot_under_the_cap(session_factory): # B-52
user_id = await _make_funded_user(session_factory, 31, 3_000_000_000)
client = FakeElectrumClient()
async with session_factory() as session:
round_ = await open_new_round_if_needed(session)
await session.commit()
round_id = round_.id
await _fill_round_with_participants(session_factory, round_id, MAX_PARTICIPANTS_PER_ROUND - 1)
async with session_factory() as session:
user = await session.get(User, user_id)
participant = await place_bet(session, client, user)
assert participant.status == "broadcast"
assert client.broadcasted
async def test_place_bet_rejects_second_bet_same_round(session_factory):
user_id = await _make_funded_user(session_factory, 2, 3_000_000_000)
client = FakeElectrumClient()
@@ -166,6 +265,33 @@ async def test_failed_broadcast_leaves_nothing_behind(session_factory):
assert "bet_placed" not in events
async def test_failed_broadcast_publishes_an_sse_update(session_factory): # B-49
"""The rollback moves as much state as the successful path does, so it must ping
the dashboards the same way — otherwise the phantom bet stays on screen until the
next poll."""
user_id = await _make_funded_user(session_factory, 21, 3_000_000_000)
async with session_factory() as session:
# Open the round up front: place_bet would otherwise open it itself, and that
# publish() would satisfy the assertion below whether or not the rollback ever
# published one of its own.
await open_new_round_if_needed(session)
await session.commit()
queue = broadcaster.subscribe()
try:
while not queue.empty():
queue.get_nowait()
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(BetError, match="refused"):
await place_bet(session, RejectingElectrumClient(), user)
assert not queue.empty()
finally:
broadcaster.unsubscribe(queue)
async def test_failed_broadcast_reports_the_broadcast_failed_code(session_factory):
user_id = await _make_funded_user(session_factory, 5, 3_000_000_000)
+181
View File
@@ -0,0 +1,181 @@
import pytest
from cryptography.fernet import Fernet
from httpx import ASGITransport, AsyncClient
from app.config import settings
@pytest.fixture
async def client(monkeypatch, tmp_path):
monkeypatch.setattr(settings, "database_url", f"sqlite+aiosqlite:///{tmp_path}/test.db")
monkeypatch.setattr(settings, "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 async_sessionmaker, create_async_engine
from app.db import base as db_base
import app.db.models # noqa: F401
db_base.engine = create_async_engine(settings.database_url)
db_base.AsyncSessionLocal = async_sessionmaker(db_base.engine, expire_on_commit=False)
from app.db import session as db_session
db_session.AsyncSessionLocal = db_base.AsyncSessionLocal
async with db_base.engine.begin() as conn:
await conn.run_sync(db_base.Base.metadata.create_all)
from fastapi import FastAPI
from app.api.routes.admin import router as admin_router
from app.api.routes.bug_reports import router as bug_reports_router
from app.auth.routes import router as auth_router
from app.electrum.listener import ElectrumListener
app = FastAPI()
app.include_router(auth_router)
app.include_router(bug_reports_router)
app.include_router(admin_router)
app.state.electrum_listener = ElectrumListener(lambda endpoint: None, db_base.AsyncSessionLocal)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
yield ac
await db_base.engine.dispose()
_ADMIN_HEADERS = {"X-Admin-Token": "test-admin-token"}
async def _register(client, username="alice", password="original-password"):
resp = await client.post("/auth/register", json={"username": username, "password": password})
assert resp.status_code == 201
return resp.json()["access_token"]
async def test_anonymous_bug_report_has_no_user(client):
resp = await client.post("/bug-reports", json={"description": "the bet button does nothing"})
assert resp.status_code == 201
resp = await client.get("/admin/bug-reports", headers=_ADMIN_HEADERS)
assert resp.status_code == 200
reports = resp.json()
assert len(reports) == 1
assert reports[0]["description"] == "the bet button does nothing"
assert reports[0]["user_id"] is None
assert reports[0]["username"] is None
assert reports[0]["status"] == "open"
async def test_logged_in_bug_report_is_attributed_to_the_user(client):
token = await _register(client)
resp = await client.post(
"/bug-reports",
headers={"Authorization": f"Bearer {token}"},
json={"description": "withdrawal amount looks wrong", "contact": "alice@example.com"},
)
assert resp.status_code == 201
resp = await client.get("/admin/bug-reports", headers=_ADMIN_HEADERS)
reports = resp.json()
assert reports[0]["username"] == "alice"
assert reports[0]["contact"] == "alice@example.com"
async def test_user_can_see_own_report_status(client):
token = await _register(client)
headers = {"Authorization": f"Bearer {token}"}
resp = await client.post("/bug-reports", headers=headers, json={"description": "some bug"})
report_id = resp.json()["id"]
resp = await client.get("/bug-reports/mine", headers=headers)
assert resp.status_code == 200
reports = resp.json()
assert len(reports) == 1
assert reports[0]["id"] == report_id
assert reports[0]["status"] == "open"
await client.post(
f"/admin/bug-reports/{report_id}/status", headers=_ADMIN_HEADERS, json={"status": "read"}
)
resp = await client.get("/bug-reports/mine", headers=headers)
assert resp.json()[0]["status"] == "read"
async def test_bug_reports_mine_requires_auth(client):
resp = await client.get("/bug-reports/mine")
assert resp.status_code == 401
async def test_bug_reports_mine_only_returns_own_reports(client):
alice_token = await _register(client, username="alice")
bob_token = await _register(client, username="bob", password="bob-password")
await client.post(
"/bug-reports", headers={"Authorization": f"Bearer {alice_token}"}, json={"description": "alice's bug"}
)
resp = await client.get("/bug-reports/mine", headers={"Authorization": f"Bearer {bob_token}"})
assert resp.json() == []
async def test_blank_description_is_rejected(client):
resp = await client.post("/bug-reports", json={"description": " "})
assert resp.status_code == 422
async def test_admin_bug_reports_requires_token(client):
resp = await client.get("/admin/bug-reports")
assert resp.status_code == 403
async def test_admin_can_move_through_open_read_resolved(client):
resp = await client.post("/bug-reports", json={"description": "some bug"})
report_id = resp.json()["id"]
resp = await client.post(
f"/admin/bug-reports/{report_id}/status", headers=_ADMIN_HEADERS, json={"status": "read"}
)
assert resp.status_code == 200
assert resp.json()["status"] == "read"
resp = await client.post(
f"/admin/bug-reports/{report_id}/status", headers=_ADMIN_HEADERS, json={"status": "resolved"}
)
assert resp.status_code == 200
assert resp.json()["status"] == "resolved"
resp = await client.post(
f"/admin/bug-reports/{report_id}/status", headers=_ADMIN_HEADERS, json={"status": "open"}
)
assert resp.status_code == 200
assert resp.json()["status"] == "open"
async def test_update_status_rejects_unknown_value(client):
resp = await client.post("/bug-reports", json={"description": "some bug"})
report_id = resp.json()["id"]
resp = await client.post(
f"/admin/bug-reports/{report_id}/status", headers=_ADMIN_HEADERS, json={"status": "bogus"}
)
assert resp.status_code == 422
async def test_update_status_unknown_report_is_404(client):
resp = await client.post(
"/admin/bug-reports/999/status", headers=_ADMIN_HEADERS, json={"status": "read"}
)
assert resp.status_code == 404
+58 -1
View File
@@ -4,7 +4,15 @@ from embit.bip32 import HDKey
from embit.transaction import Transaction
from app.wallet.plm_network import PLM_MAINNET
from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_payout_transaction, estimate_vsize
from app.wallet.psbt_builder import (
MAX_PARTICIPANTS_PER_ROUND,
MAX_PAYOUT_TX_INPUTS,
MAX_TX_INPUTS,
InsufficientFundsError,
Utxo,
build_payout_transaction,
estimate_vsize,
)
def _key(seed_byte: int) -> HDKey:
@@ -75,6 +83,55 @@ def test_payout_adds_change_output_when_pool_utxos_exceed_target():
assert len(parsed.vout) == 3
def test_payout_spends_more_utxos_than_a_user_transaction_may(): # B-52
"""The pool holds one UTXO per bet, so a round with more participants than
MAX_TX_INPUTS used to be impossible to pay out: select_utxos raised
too_many_inputs, the round stayed "paying_out" retrying every 60s forever, and
since no new round may open while one is active, the lottery stopped for good.
The payout gets its own, far higher cap for exactly this reason."""
pool_key = _key(40)
pool_script = script.p2wpkh(pool_key.to_public())
pool_address = pool_script.address(network=PLM_MAINNET)
winner_address = script.p2wpkh(_key(41).to_public()).address(network=PLM_MAINNET)
fee_address = script.p2wpkh(_key(42).to_public()).address(network=PLM_MAINNET)
# One 10 PLM bet per participant, one UTXO each, just past the user-facing cap.
participants = MAX_TX_INPUTS + 1
bet_sats = 1_000_000_000
pool_amount = bet_sats * participants
winner_share = pool_amount * 70 // 100
commission = pool_amount - winner_share
utxos = [Utxo(f"{i:064x}", 0, bet_sats) for i in range(participants)]
built = build_payout_transaction(
signing_key=pool_key,
from_script=pool_script,
utxos=utxos,
winner_address=winner_address,
winner_share_sats=winner_share,
fee_address=fee_address,
commission_sats=commission,
change_address=pool_address,
fee_rate_sat_vb=1,
)
assert len(built.spent_utxos) == participants # every bet had to be spent
parsed = Transaction.parse(bytes.fromhex(built.raw_hex))
assert len(parsed.vin) == participants
assert built.fee_sats == estimate_vsize(participants, 3)
assert built.winner_sats == winner_share - built.fee_sats
assert built.commission_sats == commission # still untouched by the fee
def test_payout_at_the_participant_cap_stays_well_inside_relay_limits(): # B-52
"""MAX_PARTICIPANTS_PER_ROUND is only safe if the payout it implies is still a
standard transaction. A full round is one input per bet plus the pool's own
change, and relay policy refuses anything past 100 kvB."""
inputs_needed = MAX_PARTICIPANTS_PER_ROUND + 1 # + one accumulated pool change UTXO
assert inputs_needed <= MAX_PAYOUT_TX_INPUTS # headroom for pool change exists
assert estimate_vsize(MAX_PAYOUT_TX_INPUTS, 3) < 100_000
def test_payout_raises_when_winner_share_too_small():
pool_key = _key(30)
pool_script = script.p2wpkh(pool_key.to_public())
+45
View File
@@ -5,6 +5,8 @@ from embit.transaction import Transaction
from app.wallet.plm_network import PLM_MAINNET
from app.wallet.psbt_builder import (
MAX_PAYOUT_TX_INPUTS,
MAX_TX_INPUTS,
InsufficientFundsError,
Utxo,
build_signed_transaction,
@@ -36,6 +38,49 @@ def test_select_utxos_raises_when_insufficient():
select_utxos(utxos, target_sats=10_000_000)
def test_select_utxos_never_exceeds_the_input_cap(): # B-48
# 200 dust-ish UTXOs that together cover the target, but only past the cap.
utxos = [Utxo(f"{i:064x}", 0, 100_000) for i in range(200)]
with pytest.raises(InsufficientFundsError) as excinfo:
select_utxos(utxos, target_sats=100_000 * MAX_TX_INPUTS + 1)
assert excinfo.value.code == "too_many_inputs"
assert excinfo.value.params == {"max_inputs": MAX_TX_INPUTS}
def test_select_utxos_allows_exactly_the_input_cap():
utxos = [Utxo(f"{i:064x}", 0, 100_000) for i in range(200)]
selected, total = select_utxos(utxos, target_sats=100_000 * MAX_TX_INPUTS)
assert len(selected) == MAX_TX_INPUTS
assert total == 100_000 * MAX_TX_INPUTS
def test_select_utxos_honours_a_caller_supplied_cap(): # B-52
"""The cap is per-caller: MAX_TX_INPUTS protects a user from a fee eating into
their own bet/withdrawal, while the payout needs MAX_PAYOUT_TX_INPUTS to be able
to drain a pool holding one UTXO per bet at all."""
utxos = [Utxo(f"{i:064x}", 0, 100_000) for i in range(MAX_TX_INPUTS + 10)]
target = 100_000 * (MAX_TX_INPUTS + 10)
with pytest.raises(InsufficientFundsError):
select_utxos(utxos, target_sats=target) # default cap: too fragmented
selected, total = select_utxos(utxos, target_sats=target, max_inputs=MAX_PAYOUT_TX_INPUTS)
assert len(selected) == MAX_TX_INPUTS + 10
assert total == target
def test_select_utxos_still_caps_at_the_payout_limit(): # B-52
utxos = [Utxo(f"{i:064x}", 0, 100_000) for i in range(MAX_PAYOUT_TX_INPUTS + 5)]
with pytest.raises(InsufficientFundsError) as excinfo:
select_utxos(
utxos,
target_sats=100_000 * (MAX_PAYOUT_TX_INPUTS + 1),
max_inputs=MAX_PAYOUT_TX_INPUTS,
)
assert excinfo.value.code == "too_many_inputs"
assert excinfo.value.params == {"max_inputs": MAX_PAYOUT_TX_INPUTS}
def test_build_signed_transaction_deducts_fee_from_amount_not_change():
signer = _key(1)
from_script = script.p2wpkh(signer.to_public())
+36
View File
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta, timezone
import pytest
from embit.transaction import Transaction
from sqlalchemy import select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
@@ -8,6 +9,7 @@ from app.config import settings
from app.db.base import Base
from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, User
from app.rounds.scheduler import RoundScheduler, _reserved_payout_outpoints
from app.wallet.psbt_builder import MAX_TX_INPUTS
class FakeListener:
@@ -155,6 +157,40 @@ async def test_trigger_payout_persists_before_broadcasting(payout_session_factor
assert "payout_sent" in events
async def test_trigger_payout_pays_a_round_with_more_participants_than_max_tx_inputs(
payout_session_factory,
): # B-52
"""End-to-end shape of the deadlock this fixes: the pool holds one UTXO per bet,
so a round past MAX_TX_INPUTS participants could not be paid at all — the build
failed with too_many_inputs, the round stayed "paying_out" retrying every 60s,
and no new round could ever open behind it. It must now broadcast normally."""
await _seed_paying_out_round(payout_session_factory)
participants = MAX_TX_INPUTS + 1
bet_sats = _POOL_AMOUNT_SATS // participants
entries = [
{"tx_hash": f"{i:064x}", "tx_pos": 0, "height": 10, "value": bet_sats}
for i in range(participants)
]
# The pool's total must cover the round's recorded pool_amount_sats, exactly as
# on-chain: integer division above leaves a remainder, so top the last one up.
entries[-1]["value"] += _POOL_AMOUNT_SATS - bet_sats * participants
client = FakePayoutClient(entries)
scheduler = RoundScheduler(payout_session_factory, FakePayoutListener(client))
await scheduler._trigger_payout(1)
assert client.broadcasted
async with payout_session_factory() as session:
pending = (await session.scalars(select(PendingTransaction))).one()
assert pending.status == "pending"
assert len(Transaction.parse(bytes.fromhex(pending.raw_tx_hex)).vin) == participants
events = [e.event_type for e in (await session.scalars(select(AuditLog))).all()]
assert "payout_sent" in events
assert "payout_failed" not in events
async def test_trigger_payout_broadcast_failure_leaves_a_recoverable_row(payout_session_factory):
"""Before B-25, a broadcast rejection here left nothing behind — no payout_txid,
no PendingTransaction — because everything was persisted only after the
+26
View File
@@ -6,6 +6,7 @@ from app.bets.service import place_bet
from app.config import settings
from app.db.base import Base
from app.db.models import PendingTransaction, User, UtxoEvent, Withdrawal
from app.rounds.events import broadcaster
from app.wallet.hd import derive_user_address
from app.withdrawals.service import WithdrawalError, request_withdrawal
@@ -171,6 +172,31 @@ async def test_withdrawal_to_own_address_is_rejected(session_factory):
assert (await session.scalars(select(UtxoEvent).where(UtxoEvent.user_id == user_id))).one().spent_txid is None
async def test_failed_broadcast_publishes_an_sse_update(session_factory): # B-49
"""The released UTXOs are spendable again and the balance changed back, so the
rollback must nudge the dashboard to refetch instead of leaving it stale until
its next poll."""
user_id = await _make_funded_user(session_factory, 10, 3_000_000_000)
class RejectingClient:
async def broadcast(self, raw_tx_hex: str) -> str:
raise RuntimeError("min relay fee not met")
queue = broadcaster.subscribe()
try:
while not queue.empty():
queue.get_nowait()
async with session_factory() as session:
user = await session.get(User, user_id)
with pytest.raises(WithdrawalError, match="refused"):
await request_withdrawal(session, RejectingClient(), user, derive_user_address(98), 1_000_000_000)
assert not queue.empty()
finally:
broadcaster.unsubscribe(queue)
async def test_failed_broadcast_marks_the_withdrawal_failed_and_frees_the_coins(session_factory):
"""B-07/B-08: the Withdrawal row is kept (unlike a bet) so the user can see the
instruction didn't go through, but the coins must come back."""