Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1a1145cda | ||
|
|
447bbba83e | ||
|
|
f9f822f437 |
No files matched your search
+4
-1
@@ -9,7 +9,10 @@ ELECTRUM_USE_SSL=true
|
||||
# confirmation goes through this one connection, which makes a single server the
|
||||
# platform's biggest single point of failure. A typo here fails at startup rather
|
||||
# than during the outage when the fallback is what you need.
|
||||
# Example: ELECTRUM_FALLBACK_SERVERS=node2.example.net:50002,node3.example.net:50001:notls
|
||||
# These are the mainnet bootstrap servers from the PalladiumWallet repo
|
||||
# (src/Core/Chain/ChainProfiles.cs, ChainProfiles.Mainnet.BootstrapServers) — the
|
||||
# same ones the reference wallet falls back to:
|
||||
# Example: ELECTRUM_FALLBACK_SERVERS=173.212.224.67:50002,144.91.120.225:50002,66.94.115.80:50002,89.117.149.130:50002
|
||||
ELECTRUM_FALLBACK_SERVERS=
|
||||
|
||||
# Fernet key protecting the master xprv at rest. Generate with:
|
||||
|
||||
@@ -54,3 +54,49 @@ async def credit_confirmed_utxos(session: AsyncSession, user_id: int, entries: l
|
||||
broadcaster.publish() # nudges this user's dashboard to refetch its balance instantly
|
||||
|
||||
return newly_credited
|
||||
|
||||
|
||||
_EXTERNAL_SPEND_SENTINEL = "external-spend"
|
||||
|
||||
|
||||
async def detect_external_spends(session: AsyncSession, user_id: int, entries: list[dict]) -> int:
|
||||
"""Mirror of credit_confirmed_utxos: catches a UTXO leaving the address
|
||||
through a transaction this platform never built (e.g. someone spending it
|
||||
directly with the raw privkey, bypassing /withdrawals entirely).
|
||||
|
||||
Everything the platform itself spends (bets, withdrawals, payouts) sets
|
||||
spent_txid at broadcast time, before the tx ever reaches the chain — so by
|
||||
the time an Electrum refresh runs, an outpoint still marked unspent in our
|
||||
own DB that Electrum no longer reports as unspent was never on our radar.
|
||||
entries is this address's current `listunspent`; anything in our unspent
|
||||
set but missing from it left the address some other way. Returns the
|
||||
number of UTXOs newly marked spent.
|
||||
"""
|
||||
current_keys = {(entry["tx_hash"], entry["tx_pos"]) for entry in entries}
|
||||
|
||||
unspent_rows = (
|
||||
await session.scalars(
|
||||
select(UtxoEvent).where(UtxoEvent.user_id == user_id, UtxoEvent.spent_txid.is_(None))
|
||||
)
|
||||
).all()
|
||||
|
||||
newly_spent = 0
|
||||
for row in unspent_rows:
|
||||
if (row.txid, row.vout) in current_keys:
|
||||
continue
|
||||
row.spent_txid = _EXTERNAL_SPEND_SENTINEL
|
||||
await write_audit_log(
|
||||
session,
|
||||
"utxo_spent_externally",
|
||||
{"txid": row.txid, "vout": row.vout, "amount_sats": row.amount_sats},
|
||||
user_id=user_id,
|
||||
)
|
||||
newly_spent += 1
|
||||
|
||||
if newly_spent:
|
||||
await session.flush()
|
||||
await recompute_balance(session, user_id)
|
||||
await session.commit()
|
||||
broadcaster.publish()
|
||||
|
||||
return newly_spent
|
||||
@@ -6,7 +6,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from app.db.models import User
|
||||
from app.deposits.service import credit_confirmed_utxos
|
||||
from app.deposits.service import credit_confirmed_utxos, detect_external_spends
|
||||
from app.electrum.client import ElectrumClient, ElectrumEndpoint
|
||||
from app.electrum.scripthash import address_to_scripthash
|
||||
from app.rounds.events import broadcaster
|
||||
@@ -207,5 +207,8 @@ class ElectrumListener:
|
||||
entries = await self.client.listunspent(scripthash)
|
||||
async with self._session_factory() as session:
|
||||
credited = await credit_confirmed_utxos(session, user_id, entries)
|
||||
spent_externally = await detect_external_spends(session, user_id, entries)
|
||||
if credited:
|
||||
logger.info("credited %s new UTXO(s) for user_id=%s", credited, user_id)
|
||||
if spent_externally:
|
||||
logger.warning("%s UTXO(s) spent outside the platform for user_id=%s", spent_externally, user_id)
|
||||
+6
-15
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
@@ -21,7 +20,7 @@ from app.api.routes.rounds import router as rounds_router
|
||||
from app.api.routes.users import router as users_router
|
||||
from app.api.routes.withdrawals import router as withdrawals_router
|
||||
from app.auth.routes import router as auth_router
|
||||
from app.api.errors import ApiError, http_error
|
||||
from app.api.errors import ApiError
|
||||
from app.config import settings, validate_runtime_secrets
|
||||
from app.db.base import AsyncSessionLocal
|
||||
from app.electrum.client import ElectrumClient, ElectrumEndpoint, parse_endpoints
|
||||
@@ -119,22 +118,14 @@ async def admin_panel() -> FileResponse:
|
||||
return FileResponse("app/static/admin.html", headers=_NO_STORE_HEADERS)
|
||||
|
||||
|
||||
_USER_GUIDE_PATH = Path("docs/guida-utente.md")
|
||||
|
||||
|
||||
@app.get("/guida", include_in_schema=False)
|
||||
async def user_guide() -> FileResponse:
|
||||
"""Serves docs/guida-utente.md as plain text so it opens inline in the
|
||||
browser (no markdown rendering — keeps this simple), linked from the
|
||||
navbar's help button in app/static/index.html.
|
||||
return FileResponse("app/static/guida.html", headers=_NO_STORE_HEADERS)
|
||||
|
||||
The Dockerfile must COPY docs/ for this to exist inside the container (it
|
||||
didn't, which made this a guaranteed 500 in every real deployment — B-16).
|
||||
Answers a clean 404 if the file is missing rather than an unhandled error."""
|
||||
if not _USER_GUIDE_PATH.is_file():
|
||||
logger.error("user guide missing at %s (is docs/ shipped in the image?)", _USER_GUIDE_PATH)
|
||||
raise http_error(status.HTTP_404_NOT_FOUND, "guide_unavailable", "user guide not available")
|
||||
return FileResponse(_USER_GUIDE_PATH, media_type="text/plain; charset=utf-8")
|
||||
|
||||
@app.get("/report-bug", include_in_schema=False)
|
||||
async def report_bug_page() -> FileResponse:
|
||||
return FileResponse("app/static/report-bug.html", headers=_NO_STORE_HEADERS)
|
||||
|
||||
|
||||
app.mount("/", StaticFiles(directory="app/static", html=True), name="static")
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="it">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Guida — PLM Lottery</title>
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-shell">
|
||||
<h1>Guida utente</h1>
|
||||
<p>Questa pagina è un placeholder. La guida completa sarà pubblicata qui a breve.</p>
|
||||
<p><a class="link" href="/">← Torna alla home</a></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -25,8 +25,8 @@
|
||||
<a class="link icon-link" href="/guida" target="_blank" rel="noopener" data-i18n-title="nav.guideTitle" title="Guida" data-i18n-aria-label="nav.guideAria" aria-label="Apri la guida utente">
|
||||
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 2-3 4"/><path d="M12 17h.01"/></svg>
|
||||
</a>
|
||||
<a class="link icon-link" href="https://github.com/REPLACE_ME/plm-lottery/issues/new" target="_blank" rel="noopener" data-i18n-title="nav.bugReport" title="Segnala un bug" data-i18n-aria-label="nav.bugReport" aria-label="Segnala un bug su GitHub">
|
||||
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2v3M16 2v3M12 12v-2a2 2 0 1 1 2 2h-2Z"/><rect x="6" y="10" width="12" height="10" rx="4"/><path d="M6 15H3M21 15h-3M9 20v-3M15 20v-3"/></svg>
|
||||
<a class="link icon-link" href="/report-bug" target="_blank" rel="noopener" data-i18n-title="nav.bugReport" title="Segnala un bug" data-i18n-aria-label="nav.bugReport" aria-label="Segnala un bug">
|
||||
<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>
|
||||
</a>
|
||||
<button class="link icon-link" onclick="logout()" data-i18n-title="nav.logoutTitle" title="Esci" data-i18n-aria-label="nav.logoutAria" aria-label="Esci dall'account">
|
||||
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/></svg>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="it">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Segnala un bug — PLM Lottery</title>
|
||||
<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="/">← Torna alla home</a></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,9 +1,10 @@
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.db.base import Base
|
||||
from app.db.models import User
|
||||
from app.deposits.service import credit_confirmed_utxos
|
||||
from app.db.models import AuditLog, User, UtxoEvent
|
||||
from app.deposits.service import credit_confirmed_utxos, detect_external_spends
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -52,3 +53,33 @@ async def test_idempotent_on_repeated_notification(session_factory, user_id):
|
||||
assert first == 1
|
||||
assert second == 0
|
||||
assert user.cached_balance_sats == 7_000_000
|
||||
|
||||
|
||||
async def test_external_spend_marks_utxo_spent_and_corrects_balance(session_factory, user_id):
|
||||
entries = [{"tx_hash": "dd" * 32, "tx_pos": 0, "height": 100, "value": 20_000_000}]
|
||||
async with session_factory() as session:
|
||||
await credit_confirmed_utxos(session, user_id, entries)
|
||||
|
||||
async with session_factory() as session:
|
||||
spent = await detect_external_spends(session, user_id, [])
|
||||
assert spent == 1
|
||||
user = await session.get(User, user_id)
|
||||
assert user.cached_balance_sats == 0
|
||||
|
||||
utxo = (await session.scalars(select(UtxoEvent).where(UtxoEvent.user_id == user_id))).one()
|
||||
assert utxo.spent_txid == "external-spend"
|
||||
|
||||
audit_events = (await session.scalars(select(AuditLog))).all()
|
||||
assert any(e.event_type == "utxo_spent_externally" for e in audit_events)
|
||||
|
||||
|
||||
async def test_no_spend_detected_when_utxo_still_unspent(session_factory, user_id):
|
||||
entries = [{"tx_hash": "ee" * 32, "tx_pos": 0, "height": 100, "value": 3_000_000}]
|
||||
async with session_factory() as session:
|
||||
await credit_confirmed_utxos(session, user_id, entries)
|
||||
|
||||
async with session_factory() as session:
|
||||
spent = await detect_external_spends(session, user_id, entries)
|
||||
assert spent == 0
|
||||
user = await session.get(User, user_id)
|
||||
assert user.cached_balance_sats == 3_000_000
|
||||
Reference in new issue
Block a user