Detect UTXOs spent outside the platform and correct the cached balance

credit_confirmed_utxos only ever credited new UTXOs; a UTXO spent by
something other than the app's own bet/withdrawal/payout flow (e.g. someone
using the raw derived privkey directly) never got its spent_txid set, so
cached_balance_sats kept counting it forever. detect_external_spends mirrors
the same listunspent refresh in the other direction: anything still marked
unspent in our DB but missing from the address's current unspent set gets
spent_txid="external-spend", an audit_log entry, and an immediate balance
recompute — wired into the same ElectrumListener._refresh_user call that
already runs on every scripthash notification and on listener (re)connect.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5 committed 2026-07-27 08:45:09 +02:00
1 parent 447bbba83e
commit f1a1145cda
3 files changed
+83 -3

No files matched your search

+4 -1
View File
@@ -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)