"""Confirmations of the platform's own transactions (roadmap B7, TX-30, TX-31, TX-26). Three phases like the deposit scan: read the pending transactions and every txid each has had; ask the servers with no database open (a version in a block, with a merkle proof the others back); write the outcome, only for rows still `pending`. The version that confirms is adopted even when it is not `current_txid`: an RBF replacement may not have won. """ import asyncio import logging from datetime import datetime from django.db import transaction from django.utils import timezone from . import audit from .models import ChainTransaction, DepositAddress, Movement, Participation, Utxo logger = logging.getLogger(__name__) WORKER = "worker" def spending_address(tx: ChainTransaction) -> str | None: """The address whose history shows the transaction: the player's for a bet or a withdrawal, the round's pool for a payout (B8).""" if tx.kind == ChainTransaction.Kind.PAYOUT: return tx.round.pool_address if tx.round_id else None owner = DepositAddress.objects.filter(user_id=tx.user_id).first() return owner.address if owner else None def plan() -> list[tuple[int, str, frozenset[str]]]: wanted = [] for tx in ChainTransaction.objects.filter(status=ChainTransaction.Status.PENDING).select_related("round").order_by("id"): address = spending_address(tx) txids = frozenset(tx.versions.values_list("txid", flat=True)) if address and txids: wanted.append((tx.pk, address, txids)) return wanted def apply_confirmations(confirmed: dict[int, tuple[str, int]], now: datetime | None = None) -> int: now = now or timezone.now() done = 0 for tx_id, (txid, height) in confirmed.items(): with transaction.atomic(): fresh = ChainTransaction.objects.select_for_update().get(pk=tx_id) if fresh.status != ChainTransaction.Status.PENDING: continue # TX-26: confirmed, abandoned or settled by someone else while the network was asked version = fresh.versions.filter(txid=txid).first() if version is None: logger.error("transaction %s: confirmed txid %s is none of its versions", tx_id, txid) continue adopted = fresh.current_txid != txid if adopted: # TX-31 fresh.current_txid = txid if version.raw_hex: fresh.raw_hex = version.raw_hex fresh.status, fresh.confirmed_at = ChainTransaction.Status.CONFIRMED, now fresh.save(update_fields=["status", "confirmed_at", "current_txid", "raw_hex"]) Utxo.objects.filter(reserved_by=fresh).update(spent_txid=txid) if fresh.kind == ChainTransaction.Kind.BET: _bet_confirmed(fresh, txid, now) audit.record("tx_confirmed", actor_label=WORKER, subject_type="chain_transaction", subject_id=fresh.pk, payload={"txid": txid, "height": height, "adopted": adopted, "kind": fresh.kind}) done += 1 return done def _bet_confirmed(tx: ChainTransaction, txid: str, now: datetime) -> None: """The bet takes part in the draw (BET, TX-07): found through its fixed links, never through the txid (TX-08).""" movement = Movement.objects.filter(chain_transaction=tx, kind=Movement.Kind.BET).select_related("participation").first() if movement is None or movement.participation is None: return bet = movement.participation if bet.status == Participation.Status.PENDING: bet.status, bet.confirmed_at, bet.bet_txid = Participation.Status.CONFIRMED, now, txid bet.save(update_fields=["status", "confirmed_at", "bet_txid"]) if movement.status == Movement.Status.PENDING: movement.status, movement.confirmed_at = Movement.Status.CONFIRMED, now movement.save(update_fields=["status", "confirmed_at"]) def poll_confirmations(chain, now: datetime | None = None) -> int: wanted = plan() if not wanted: return 0 confirmed = asyncio.run(chain.observe_confirmations(wanted)) return apply_confirmations(confirmed, now) if confirmed else 0