2026-07-21 10:26:42 +02:00
|
|
|
import asyncio
|
2026-07-21 10:46:47 +02:00
|
|
|
import logging
|
2026-07-21 10:26:42 +02:00
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
|
|
2026-07-27 00:34:33 +02:00
|
|
|
from fastapi import FastAPI, Request, status
|
2026-07-21 10:46:47 +02:00
|
|
|
from fastapi.responses import FileResponse, JSONResponse
|
2026-07-21 10:27:05 +02:00
|
|
|
from fastapi.staticfiles import StaticFiles
|
2026-07-21 10:26:42 +02:00
|
|
|
|
2026-07-21 10:46:47 +02:00
|
|
|
from app.logging_config import setup_logging
|
|
|
|
|
|
|
|
|
|
setup_logging()
|
|
|
|
|
|
2026-07-21 10:26:42 +02:00
|
|
|
import app.bets.confirmation # noqa: F401 (registers the "bet" confirmation handler)
|
|
|
|
|
import app.rounds.confirmation # noqa: F401 (registers the "payout" confirmation handler)
|
|
|
|
|
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
|
2026-07-21 10:51:56 +02:00
|
|
|
from app.api.routes.qr import router as qr_router
|
2026-07-21 10:57:31 +02:00
|
|
|
from app.api.routes.rounds import router as rounds_router
|
2026-07-21 10:26:42 +02:00
|
|
|
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
|
2026-07-27 08:35:47 +02:00
|
|
|
from app.api.errors import ApiError
|
2026-07-27 00:34:33 +02:00
|
|
|
from app.config import settings, validate_runtime_secrets
|
2026-07-21 10:26:42 +02:00
|
|
|
from app.db.base import AsyncSessionLocal
|
2026-07-27 10:35:23 +02:00
|
|
|
from app.deposits.reconcile import DepositReconciler
|
2026-07-27 00:34:59 +02:00
|
|
|
from app.electrum.client import ElectrumClient, ElectrumEndpoint, parse_endpoints
|
2026-07-21 10:26:42 +02:00
|
|
|
from app.electrum.listener import ElectrumListener
|
|
|
|
|
from app.rounds.scheduler import RoundScheduler
|
|
|
|
|
from app.tx.broadcast import RbfBumper
|
|
|
|
|
from app.tx.confirmation import ConfirmationPoller
|
|
|
|
|
from app.tx.locks import UserLocks
|
2026-07-27 00:34:59 +02:00
|
|
|
from app.tx.reconcile import PendingTransactionReconciler
|
2026-07-21 10:26:42 +02:00
|
|
|
|
2026-07-21 10:46:47 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-07-21 10:26:42 +02:00
|
|
|
|
2026-07-27 00:34:59 +02:00
|
|
|
def _make_electrum_client(endpoint: ElectrumEndpoint) -> ElectrumClient:
|
|
|
|
|
return ElectrumClient(endpoint.host, endpoint.port, endpoint.use_ssl)
|
2026-07-21 10:26:42 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(app: FastAPI):
|
2026-07-27 00:34:59 +02:00
|
|
|
# Refuses to serve rather than starting up half-configured — see B-15 in BUGS.md.
|
|
|
|
|
validate_runtime_secrets()
|
|
|
|
|
|
|
|
|
|
endpoints = parse_endpoints(
|
|
|
|
|
settings.electrum_host,
|
|
|
|
|
settings.electrum_port,
|
|
|
|
|
settings.electrum_use_ssl,
|
|
|
|
|
settings.electrum_fallback_servers,
|
|
|
|
|
)
|
|
|
|
|
logger.info("Electrum endpoints (in rotation order): %s", ", ".join(str(e) for e in endpoints))
|
|
|
|
|
|
|
|
|
|
listener = ElectrumListener(_make_electrum_client, AsyncSessionLocal, endpoints)
|
2026-07-21 10:26:42 +02:00
|
|
|
app.state.electrum_listener = listener
|
|
|
|
|
app.state.user_locks = UserLocks()
|
|
|
|
|
|
|
|
|
|
scheduler = RoundScheduler(AsyncSessionLocal, listener)
|
|
|
|
|
poller = ConfirmationPoller(AsyncSessionLocal, lambda: listener.client)
|
|
|
|
|
bumper = RbfBumper(AsyncSessionLocal, lambda: listener.client)
|
2026-07-27 00:34:59 +02:00
|
|
|
# Resolves in-flight transactions against the chain — the piece that lets the
|
|
|
|
|
# system recover on its own from a broadcast that never confirmed (B-04/B-08).
|
|
|
|
|
reconciler = PendingTransactionReconciler(AsyncSessionLocal, lambda: listener.client)
|
2026-07-27 10:35:23 +02:00
|
|
|
# Periodic safety net for deposit crediting/external-spend detection,
|
|
|
|
|
# independent of scripthash-change notifications — catches a subscription
|
|
|
|
|
# silently lost on an otherwise healthy connection (B-30).
|
|
|
|
|
deposit_reconciler = DepositReconciler(AsyncSessionLocal, listener)
|
2026-07-21 10:26:42 +02:00
|
|
|
|
|
|
|
|
tasks = [
|
|
|
|
|
asyncio.create_task(listener.run()),
|
|
|
|
|
asyncio.create_task(scheduler.run()),
|
|
|
|
|
asyncio.create_task(poller.run()),
|
|
|
|
|
asyncio.create_task(bumper.run()),
|
2026-07-27 00:34:59 +02:00
|
|
|
asyncio.create_task(reconciler.run()),
|
2026-07-27 10:35:23 +02:00
|
|
|
asyncio.create_task(deposit_reconciler.run()),
|
2026-07-21 10:26:42 +02:00
|
|
|
]
|
|
|
|
|
try:
|
|
|
|
|
yield
|
|
|
|
|
finally:
|
|
|
|
|
for task in tasks:
|
|
|
|
|
task.cancel()
|
|
|
|
|
if listener.client is not None:
|
|
|
|
|
await listener.client.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app = FastAPI(title="PLM Lottery", lifespan=lifespan)
|
|
|
|
|
app.include_router(auth_router)
|
|
|
|
|
app.include_router(users_router)
|
|
|
|
|
app.include_router(bets_router)
|
|
|
|
|
app.include_router(withdrawals_router)
|
|
|
|
|
app.include_router(admin_router)
|
2026-07-21 10:51:56 +02:00
|
|
|
app.include_router(qr_router)
|
2026-07-21 10:57:31 +02:00
|
|
|
app.include_router(rounds_router)
|
2026-07-21 10:26:42 +02:00
|
|
|
|
|
|
|
|
|
2026-07-21 10:46:47 +02:00
|
|
|
@app.exception_handler(Exception)
|
|
|
|
|
async def log_unhandled_exception(request: Request, exc: Exception) -> JSONResponse:
|
2026-07-27 00:34:59 +02:00
|
|
|
"""Answers with the same structured `detail` shape as every deliberate failure
|
|
|
|
|
(app/api/errors.py) so clients never have to special-case unexpected errors.
|
|
|
|
|
The exception itself stays in logs/app.log only — never in the response body."""
|
2026-07-21 10:46:47 +02:00
|
|
|
logger.exception("Unhandled error on %s %s", request.method, request.url.path)
|
2026-07-27 00:34:33 +02:00
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=500,
|
|
|
|
|
content={"detail": ApiError("internal_error", "internal server error").as_detail()},
|
|
|
|
|
)
|
2026-07-21 10:46:47 +02:00
|
|
|
|
|
|
|
|
|
2026-07-21 10:26:42 +02:00
|
|
|
@app.get("/health")
|
|
|
|
|
async def health() -> dict[str, str]:
|
|
|
|
|
return {"status": "ok"}
|
2026-07-21 10:27:05 +02:00
|
|
|
|
|
|
|
|
|
2026-07-22 12:00:09 +02:00
|
|
|
_NO_STORE_HEADERS = {"Cache-Control": "no-store"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/", include_in_schema=False)
|
|
|
|
|
async def index_page() -> FileResponse:
|
|
|
|
|
return FileResponse("app/static/index.html", headers=_NO_STORE_HEADERS)
|
|
|
|
|
|
|
|
|
|
|
2026-07-21 10:36:55 +02:00
|
|
|
@app.get("/admin", include_in_schema=False)
|
|
|
|
|
async def admin_panel() -> FileResponse:
|
2026-07-22 12:00:09 +02:00
|
|
|
return FileResponse("app/static/admin.html", headers=_NO_STORE_HEADERS)
|
2026-07-21 10:36:55 +02:00
|
|
|
|
|
|
|
|
|
2026-07-22 14:34:03 +02:00
|
|
|
@app.get("/guida", include_in_schema=False)
|
|
|
|
|
async def user_guide() -> FileResponse:
|
2026-07-27 08:35:47 +02:00
|
|
|
return FileResponse("app/static/guida.html", headers=_NO_STORE_HEADERS)
|
2026-07-27 00:34:33 +02:00
|
|
|
|
2026-07-27 08:35:47 +02:00
|
|
|
|
|
|
|
|
@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)
|
2026-07-22 14:34:03 +02:00
|
|
|
|
|
|
|
|
|
2026-07-21 10:27:05 +02:00
|
|
|
app.mount("/", StaticFiles(directory="app/static", html=True), name="static")
|