152 lines
7.3 KiB
Python
152 lines
7.3 KiB
Python
"""The worker's half of a real bet (roadmap B6, BET-31..BET-33).
|
|
|
|
The web process admitted the bet and reserved its coins (`ChainLedger.place_bet`). Here, with the signing key
|
|
that only this process may hold (ARC-78):
|
|
|
|
* `sign_pending` builds and signs the transaction and — in one database transaction — saves its version and the
|
|
bet's real amount to the pool, *before anything is sent*;
|
|
* `broadcast_pending` sends what was saved and writes the outcome, only if the row is still as it was read (TX-26).
|
|
Only a proven refusal frees coins; an uncertain answer changes nothing and the same transaction is sent again.
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
from datetime import datetime
|
|
|
|
from django.conf import settings
|
|
from django.db import transaction
|
|
from django.utils import timezone
|
|
from embit import script
|
|
from plm_engine import hd
|
|
from plm_engine.psbt_builder import RECIPIENT_VOUT, InsufficientFundsError, Utxo as EngineUtxo, build_signed_transaction
|
|
|
|
from . import audit, keys, reservation
|
|
from .chain import register_version
|
|
from .electrum_chain import Outcome
|
|
from .models import ChainTransaction, DepositAddress, LotteryConfig, Movement, Participation
|
|
|
|
logger = logging.getLogger(__name__)
|
|
WORKER = "worker"
|
|
_BATCH = 20
|
|
|
|
|
|
def _bet_of(tx: ChainTransaction) -> Participation | None:
|
|
return Participation.objects.filter(movements__chain_transaction=tx, movements__kind=Movement.Kind.BET).first()
|
|
|
|
|
|
def sign_pending() -> int:
|
|
"""BET-31. Returns how many bets were signed and saved. Never sends anything."""
|
|
todo = list(ChainTransaction.objects.filter(
|
|
kind=ChainTransaction.Kind.BET, status=ChainTransaction.Status.BUILDING, current_txid__isnull=True,
|
|
).select_related("user", "round").order_by("id")[:_BATCH])
|
|
if not todo:
|
|
return 0
|
|
try:
|
|
account = keys.signing_account_key()
|
|
except keys.SigningKeyUnavailable as error:
|
|
logger.error("cannot sign %d pending bet(s): %s", len(todo), error)
|
|
return 0
|
|
fee_rate = LotteryConfig.get().fee_rate_sat_vb
|
|
signed = 0
|
|
for tx in todo:
|
|
try:
|
|
if _sign_one(tx, account, fee_rate):
|
|
signed += 1
|
|
except InsufficientFundsError as error:
|
|
_fail(tx, f"cannot build the transaction: {error}", release=True)
|
|
except Exception:
|
|
logger.exception("signing bet transaction %s failed; it stays building", tx.pk)
|
|
return signed
|
|
|
|
|
|
def _sign_one(tx: ChainTransaction, account, fee_rate: int) -> bool:
|
|
coins = list(tx.reserved_utxos.order_by("id"))
|
|
if not coins or not tx.round.pool_address:
|
|
return False
|
|
owner = DepositAddress.objects.get(user=tx.user)
|
|
key = hd.user_key(account, owner.derivation_index)
|
|
bet = _bet_of(tx)
|
|
built = build_signed_transaction(
|
|
signing_key=key, from_script=script.p2wpkh(key.to_public()),
|
|
utxos=[EngineUtxo(c.txid, c.vout, c.amount_sats) for c in coins],
|
|
to_address=tx.round.pool_address, amount_sats=-bet.movements.get(kind=Movement.Kind.BET).amount_sats,
|
|
change_address=owner.address, fee_rate_sat_vb=fee_rate,
|
|
)
|
|
with transaction.atomic():
|
|
fresh = ChainTransaction.objects.select_for_update().get(pk=tx.pk)
|
|
if fresh.status != ChainTransaction.Status.BUILDING or fresh.current_txid is not None:
|
|
return False # someone else got there first
|
|
register_version(fresh, built.txid, built.raw_hex)
|
|
fresh.fee_rate_sat_vb = fee_rate # DAT-85: what the next bump starts from
|
|
fresh.save(update_fields=["fee_rate_sat_vb"])
|
|
bet.bet_txid, bet.bet_vout, bet.bet_amount_sats = built.txid, RECIPIENT_VOUT, built.recipient_sats
|
|
bet.save(update_fields=["bet_txid", "bet_vout", "bet_amount_sats"])
|
|
audit.record("bet_signed", actor_label=WORKER, subject_type="chain_transaction", subject_id=fresh.pk,
|
|
payload={"txid": built.txid, "fee_sats": built.fee_sats, "recipient_sats": built.recipient_sats,
|
|
"inputs": len(coins)})
|
|
return True
|
|
|
|
|
|
def _fail(tx: ChainTransaction, reason: str, *, release: bool, action: str = "bet_refused") -> int:
|
|
"""Refused with proof (or unbuildable): the bet is rejected, the coins return, the movement stops counting."""
|
|
with transaction.atomic():
|
|
fresh = ChainTransaction.objects.select_for_update().get(pk=tx.pk)
|
|
if fresh.status not in (ChainTransaction.Status.BUILDING, ChainTransaction.Status.PENDING):
|
|
return 0
|
|
fresh.status, fresh.failed_at, fresh.failure_reason = ChainTransaction.Status.FAILED, timezone.now(), reason[:500]
|
|
fresh.save(update_fields=["status", "failed_at", "failure_reason"])
|
|
freed = reservation.release(fresh) if release else 0
|
|
bet = _bet_of(fresh)
|
|
if bet is not None:
|
|
bet.status = Participation.Status.REJECTED
|
|
bet.save(update_fields=["status"])
|
|
Movement.objects.filter(participation=bet, kind=Movement.Kind.BET).update(status=Movement.Status.FAILED)
|
|
audit.record(action, actor_label=WORKER, subject_type="chain_transaction", subject_id=fresh.pk,
|
|
outcome="error", payload={"reason": reason[:500], "coins_freed": freed})
|
|
return freed
|
|
|
|
|
|
def _settle(tx_id: int, txid: str, verdict, now: datetime) -> bool:
|
|
"""BET-33 / TX-26: write the outcome only if the row is as it was when the network was asked."""
|
|
with transaction.atomic():
|
|
fresh = ChainTransaction.objects.select_for_update().get(pk=tx_id)
|
|
if fresh.status != ChainTransaction.Status.BUILDING or fresh.current_txid != txid:
|
|
return False
|
|
if verdict.outcome is Outcome.ACCEPTED:
|
|
fresh.status, fresh.broadcast_at, fresh.last_broadcast_at = ChainTransaction.Status.PENDING, now, now
|
|
fresh.save(update_fields=["status", "broadcast_at", "last_broadcast_at"])
|
|
audit.record("bet_broadcast", actor_label=WORKER, subject_type="chain_transaction", subject_id=fresh.pk,
|
|
payload={"txid": txid, "note": verdict.reason})
|
|
return True
|
|
if verdict.outcome is Outcome.REFUSED:
|
|
_fail(ChainTransaction.objects.get(pk=tx_id), verdict.reason or "refused by the network", release=True)
|
|
return True
|
|
return False # UNCERTAIN: nothing changes, the same transaction is sent again at the next pass
|
|
|
|
|
|
async def _send(chain, items: list[tuple[int, str, str]]):
|
|
return [(tx_id, txid, await chain.broadcast(raw, txid)) for tx_id, txid, raw in items]
|
|
|
|
|
|
def broadcast_pending(chain, now: datetime | None = None) -> dict[str, int]:
|
|
"""BET-32: send every signed, unsent bet transaction and write what came of it. The database is not open while
|
|
the network is asked."""
|
|
now = now or timezone.now()
|
|
done = {"accepted": 0, "refused": 0, "uncertain": 0}
|
|
waiting = ChainTransaction.objects.filter(
|
|
kind=ChainTransaction.Kind.BET, status=ChainTransaction.Status.BUILDING, current_txid__isnull=False,
|
|
).order_by("id")[:_BATCH]
|
|
items = [(t.pk, t.current_txid, t.raw_hex) for t in waiting]
|
|
if not items:
|
|
return done
|
|
for tx_id, txid, verdict in asyncio.run(_send(chain, items)):
|
|
_settle(tx_id, txid, verdict, now)
|
|
done[verdict.outcome.value] += 1
|
|
return done
|
|
|
|
|
|
def process_bets(chain, now: datetime | None = None) -> dict[str, int]:
|
|
signed = sign_pending()
|
|
done = broadcast_pending(chain, now)
|
|
return {"signed": signed, **done}
|