B6: atomic UTXO reservation, bet signed by the worker and saved before broadcast, broadcast verdicts (BET-30..33)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 16:18:34 +01:00
1 parent 2acd4ccd1c
commit feff993584
25 files changed
+995 -53

No files matched your search

+1 -1
View File
@@ -83,7 +83,7 @@ class LotteryConfigAdmin(admin.ModelAdmin):
commands, which ask for a reason (WEB-43). A change is audited with what changed."""
fields = ("fee_address", "bet_amount_sats", "round_duration_seconds", "round_cooldown_seconds",
"draw_confirmations", "deposit_confirmations", "max_round_pool_sats")
"draw_confirmations", "deposit_confirmations", "max_round_pool_sats", "fee_rate_sat_vb")
def has_add_permission(self, request):
return False
+149
View File
@@ -0,0 +1,149 @@
"""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)
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) -> None:
"""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
fresh.status, fresh.failed_at, fresh.failure_reason = ChainTransaction.Status.FAILED, timezone.now(), reason[:500]
fresh.save(update_fields=["status", "failed_at", "failure_reason"])
if release:
reservation.release(fresh)
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("bet_refused", actor_label=WORKER, subject_type="chain_transaction", subject_id=fresh.pk,
outcome="error", payload={"reason": reason[:500]})
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 = ChainTransaction.Status.PENDING, now
fresh.save(update_fields=["status", "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}
+5
View File
@@ -21,6 +21,11 @@ def derive_deposit_address(index: int) -> str:
return hd.user_address(keys.public_account_key(), index, settings.PLM_PROFILE)
def derive_pool_address(round_id: int) -> str:
"""The round's own pool address, `…/2/<round_id>` under the account (DAT-60, RND-35): public key only."""
return hd.pool_address(keys.public_account_key(), round_id, settings.PLM_PROFILE)
def assign_deposit_address(user) -> DepositAddress:
"""The player's deposit address; created on first use, the same one ever after (DAT-81). The index is the
next after the highest assigned; if a concurrent assignment takes it first the unique index refuses ours
+10 -2
View File
@@ -18,6 +18,7 @@ from .models import Deposit, DepositAddress, LotteryConfig, Movement, Transactio
logger = logging.getLogger(__name__)
WAITING = ("detected", "orphaned") # deposit statuses that are still being watched
COINBASE_MATURITY = 120 # DEP-21: PLM coinbase maturity (palladiumcore consensus.h)
@@ -75,14 +76,14 @@ def plan() -> Policy:
addresses=tuple(DepositAddress.objects.order_by("derivation_index").values_list("address", flat=True)),
own_txids=frozenset(TransactionVersion.objects.values_list("txid", flat=True)),
deposit_confirmations=LotteryConfig.get().deposit_confirmations,
credited=frozenset(Utxo.objects.filter(deposit__status=Deposit.Status.CREDITED).values_list("txid", "vout")),
credited=frozenset(Utxo.objects.exclude(deposit__status__in=WAITING).values_list("txid", "vout")),
waiting=_waiting_by_address(),
)
def _waiting_by_address() -> dict[str, frozenset[tuple[str, int]]]:
grouped: dict[str, set[tuple[str, int]]] = {}
rows = Utxo.objects.filter(deposit__status__in=[Deposit.Status.DETECTED, Deposit.Status.ORPHANED])
rows = Utxo.objects.filter(deposit__status__in=WAITING)
for address, txid, vout in rows.values_list("address", "txid", "vout"):
grouped.setdefault(address, set()).add((txid, vout))
return {address: frozenset(outpoints) for address, outpoints in grouped.items()}
@@ -119,6 +120,13 @@ def apply_observations(result: ScanResult, policy: Policy, now: datetime | None
def _apply_entry(owner, entry: Seen, tip: int, policy: Policy, observation: Observation, now, done) -> None:
outpoint = (entry.txid, entry.vout)
if entry.txid in policy.own_txids:
# The change of one of our own transactions is spendable money, not a deposit: it was already taken
# from the player's balance when the transaction was placed (BET-30), so no movement is written.
with transaction.atomic():
Utxo.objects.get_or_create(txid=entry.txid, vout=entry.vout, defaults=dict(
amount_sats=entry.value, address=owner.address, user=owner.user, confirmed_height=entry.height, created_at=now))
return
have = confirmations(tip, entry.height)
need = threshold_for(entry.txid, policy, observation.coinbase)
ready = have >= need and outpoint in observation.verified
+86 -1
View File
@@ -12,7 +12,10 @@ import logging
from collections.abc import Awaitable, Callable
from embit.transaction import Transaction
from plm_engine.electrum.client import ElectrumClient, ElectrumEndpoint
from enum import Enum
from typing import NamedTuple
from plm_engine.electrum.client import ElectrumClient, ElectrumEndpoint, ElectrumRpcError
from plm_engine.electrum.merkle import proof_matches_header
from plm_engine.electrum.scripthash import address_to_scripthash
from plm_engine.headers import header_meets_its_own_target
@@ -27,6 +30,23 @@ CONNECT_TIMEOUT = 10.0
ANSWER_TIMEOUT = 10.0
class Outcome(Enum):
ACCEPTED = "accepted"
REFUSED = "refused"
UNCERTAIN = "uncertain"
class Verdict(NamedTuple):
outcome: Outcome
reason: str
# Wordings by which a node says it already has the transaction. Recognising one skips the verification; not
# recognising one never releases anything, it only costs one more round of questions (BET-32, TX-04).
_ALREADY_KNOWN = ("already known", "already in mempool", "already in the mempool", "txn-already-known",
"txn-already-in-mempool", "already in block chain", "already in blockchain")
def _seen(raw: dict) -> Seen | None:
try:
return Seen(txid=str(raw["tx_hash"]), vout=int(raw["tx_pos"]), value=int(raw["value"]), height=int(raw["height"]))
@@ -177,6 +197,71 @@ class ElectrumChain:
return self.majority(await self._ask_others(lacks_it))
# -- broadcast (BET-32) -----------------------------------------------------------------------------------
async def transaction_known(self, active: ElectrumClient, txid: str) -> bool | None:
"""True if any server returns the transaction; False only if the active server and the quorum of the
others all say they do not know it; None if there were not enough answers to say."""
not_found = ("no such mempool", "no such blockchain", "not found", "unknown transaction")
async def ask(client: ElectrumClient):
try:
await asyncio.wait_for(client.get_transaction(txid), ANSWER_TIMEOUT)
return True
except ElectrumRpcError as error: # the server answered: it does not know it
return False if any(m in error.message.lower() for m in not_found) else None
except Exception:
return None
mine = await ask(active)
others = await self._ask_others(ask)
if mine is True or any(a is True for a in others):
return True
if mine is False and self.majority([a is False if a is not None else None for a in others]):
return False
return None
async def broadcast(self, raw_tx_hex: str, txid: str) -> Verdict:
"""Send `raw_tx_hex` through the active server and say what happened (BET-32). Only a proven refusal frees coins."""
active = await self._connect_active()
if active is None:
return Verdict(Outcome.UNCERTAIN, "no Electrum server is reachable")
try:
try:
await asyncio.wait_for(active.broadcast(raw_tx_hex), ANSWER_TIMEOUT)
except ElectrumRpcError as error:
reason = error.message
known = True if any(m in reason.lower() for m in _ALREADY_KNOWN) else await self.transaction_known(active, txid)
if known is True:
await self._fan_out(raw_tx_hex)
return Verdict(Outcome.ACCEPTED, reason)
if known is False:
return Verdict(Outcome.REFUSED, reason)
logger.warning("broadcast of %s was refused (%s) but the refusal could not be verified", txid, reason)
return Verdict(Outcome.UNCERTAIN, reason)
except Exception as error: # timeout, dropped connection: the server may have relayed it
logger.warning("broadcast of %s ended without an answer (%r): uncertain", txid, error)
return Verdict(Outcome.UNCERTAIN, str(error) or type(error).__name__)
await self._fan_out(raw_tx_hex)
return Verdict(Outcome.ACCEPTED, "")
finally:
await active.close()
async def _fan_out(self, raw_tx_hex: str) -> None:
"""TX-21: after the active server accepted, tell the others too (best effort)."""
async def send(client: ElectrumClient):
try:
await client.broadcast(raw_tx_hex)
except ElectrumRpcError:
pass # "already known" and the like: that is what we wanted
return True
try:
await self._ask_others(send)
except Exception:
logger.exception("fan-out of an accepted transaction failed")
# -- the scan ----------------------------------------------------------------------------------------
async def observe(self, policy: Policy) -> ScanResult:
+93 -30
View File
@@ -67,6 +67,39 @@ def _simulated_txid(kind: str) -> str:
return hashlib.sha256(f"simulated:{kind}:{uuid.uuid4()}".encode()).hexdigest()
def _admit_bet(ledger: "Ledger", user, round_id: int, request_id: UUID):
"""The checks every bet passes, whatever the ledger (WEB-22, BET-07): a replay of the same request, an open
round, no suspension, no second bet, room in the round, and a balance that covers the quota. Returns a
`Result` for a replay, else `(round, amount)`. Call inside `transaction.atomic()`."""
if not isinstance(request_id, UUID):
raise LedgerError("missing_request_id", "a bet needs the idempotency key of its request")
round_ = Round.objects.filter(pk=round_id).first()
replay = ledger._replay(user, request_id, Movement.Kind.BET, None)
if replay is not None:
if replay.round_id != round_id:
raise LedgerError("idempotency_conflict", "this request key was used for another round")
return Result(replay.participation, replayed=True)
if round_ is None or round_.status == Round.Status.CLOSED:
raise LedgerError("no_round_open", "no round open right now, please try again shortly")
if LotteryConfig.get().new_bets_suspended:
raise LedgerError("bets_suspended", "new bets are suspended")
if not round_accepts_bets(round_):
raise LedgerError("round_closing", "the current round is closing, please try again shortly")
if Participation.objects.filter(round=round_, user=user).exists():
raise LedgerError("already_betting", "you already have an active bet in the current round")
SimulatedLedger._check_round_capacity(round_)
amount = round_.bet_amount_sats
balance = balance_of(user)
if balance.spendable_sats < amount:
# BET-07: a balance on screen that includes funds in confirmation must say "wait", not a flat "insufficient".
if balance.total_sats >= amount:
raise LedgerError("balance_pending_confirmation",
"the bet cost is covered by your pending balance, which has not confirmed yet",
pending_sats=balance.incoming_sats)
raise LedgerError("insufficient_balance", "insufficient balance", required_sats=amount)
return round_, amount
class SimulatedLedger(Ledger):
"""Funds that exist only in the database. Confirmation is a method call, not a block."""
@@ -108,36 +141,11 @@ class SimulatedLedger(Ledger):
def place_bet(self, user, round_id: int, *, request_id: UUID) -> Result:
"""WEB-22: the server decides — round, quota, limits and funds are all checked here."""
if not isinstance(request_id, UUID):
raise LedgerError("missing_request_id", "a bet needs the idempotency key of its request")
with transaction.atomic():
round_ = Round.objects.filter(pk=round_id).first()
replay = self._replay(user, request_id, Movement.Kind.BET, None)
if replay is not None:
if replay.round_id != round_id:
raise LedgerError("idempotency_conflict", "this request key was used for another round")
return Result(replay.participation, replayed=True)
if round_ is None or round_.status == Round.Status.CLOSED:
raise LedgerError("no_round_open", "no round open right now, please try again shortly")
if LotteryConfig.get().new_bets_suspended:
raise LedgerError("bets_suspended", "new bets are suspended")
if not round_accepts_bets(round_):
raise LedgerError("round_closing", "the current round is closing, please try again shortly")
if Participation.objects.filter(round=round_, user=user).exists():
raise LedgerError("already_betting", "you already have an active bet in the current round")
self._check_round_capacity(round_)
amount = round_.bet_amount_sats
balance = balance_of(user)
if balance.spendable_sats < amount:
# BET-07: a balance on screen that includes funds in confirmation must say "wait",
# not a flat "insufficient".
if balance.total_sats >= amount:
raise LedgerError("balance_pending_confirmation",
"the bet cost is covered by your pending balance, which has not confirmed yet",
pending_sats=balance.incoming_sats)
raise LedgerError("insufficient_balance", "insufficient balance", required_sats=amount)
admitted = _admit_bet(self, user, round_id, request_id)
if isinstance(admitted, Result):
return admitted
round_, amount = admitted
txid = _simulated_txid("bet")
chain_tx = ChainTransaction.objects.create(
@@ -301,7 +309,62 @@ class SimulatedLedger(Ledger):
return existing
class ChainLedger(SimulatedLedger):
"""Real coins (roadmap B6). The web process admits and *reserves*; it never signs (ARC-78) — the worker does,
from `apps/lottery/bets.py`. What belongs to later steps refuses loudly instead of pretending: confirmation,
refusal and exclusion of a bet and the payout are B7/B8, withdrawals B9. Deposits arrive from the chain
(`deposits.scan_deposits`), never by a call."""
def place_bet(self, user, round_id: int, *, request_id: UUID) -> Result:
from . import reservation
from plm_engine.psbt_builder import InsufficientFundsError
with transaction.atomic():
admitted = _admit_bet(self, user, round_id, request_id)
if isinstance(admitted, Result):
return admitted
round_, amount = admitted
chain_tx = ChainTransaction.objects.create(
kind=ChainTransaction.Kind.BET, status=ChainTransaction.Status.BUILDING, user=user, round=round_
)
try:
coins = reservation.reserve_for(user, amount, chain_tx)
except InsufficientFundsError as error:
raise LedgerError(error.code, str(error), **error.params) from error
except reservation.CoinsTaken as error:
raise LedgerError("busy", "please try again in a moment") from error
participation = Participation.objects.create(round=round_, user=user, bet_amount_sats=amount)
Movement.objects.create(
user=user, kind=Movement.Kind.BET, amount_sats=-amount, status=Movement.Status.PENDING,
round=round_, participation=participation, chain_transaction=chain_tx, request_id=request_id,
)
audit.record("bet_placed", actor=user, subject_type="participation", subject_id=participation.pk,
payload={"round_id": round_.pk, "amount_sats": amount, "coins": len(coins)})
return Result(participation)
def deposit(self, user, amount_sats: int, *, request_id: UUID | None = None, confirmed: bool = True) -> Result:
raise LedgerError("not_available", "deposits on a real ledger come from the chain, not from a call")
def confirm_deposit(self, movement: Movement) -> Movement:
raise LedgerError("not_available", "deposits on a real ledger come from the chain, not from a call")
def confirm_bet(self, participation: Participation) -> Participation:
raise NotImplementedError("the confirmation of a real bet arrives with roadmap B7")
def reject_bet(self, participation: Participation, reason: str) -> Participation:
raise NotImplementedError("the refusal of a real bet after the fact arrives with roadmap B7")
def exclude_bet(self, participation: Participation, reason: str) -> Participation:
raise NotImplementedError("the exclusion of a real bet arrives with roadmap B7")
def pay_winner(self, round_id: int) -> Result:
raise NotImplementedError("the real payout arrives with roadmap B8")
def confirm_payout(self, round_id: int) -> Round:
raise NotImplementedError("the real payout arrives with roadmap B8")
def get_ledger() -> Ledger:
if settings.LEDGER_BACKEND == "simulated":
return SimulatedLedger()
raise NotImplementedError("the chain ledger arrives with phase B (roadmap B6)")
return ChainLedger()
+5
View File
@@ -87,6 +87,11 @@ def open_new_round_if_needed(now: datetime | None = None) -> Round | None:
server_seed_hash=server_seed_commitment(seed), # public from now on (RND-34)
server_seed_enc=encrypt_seed(seed), # the secret itself stays hidden until the reveal
)
if settings.LEDGER_BACKEND == "chain": # DAT-60: this round's own address, from the public key
from .chain import derive_pool_address
round_.pool_address = derive_pool_address(round_.pk)
round_.save(update_fields=["pool_address"])
except IntegrityError: # another process opened one first (ADR-22): use theirs
return get_active_round()
audit.record("round_opened", actor_label=WORKER, subject_type="round", subject_id=round_.pk,
@@ -38,6 +38,19 @@ def scan_chain_deposits() -> None:
logger.info("deposit scan: %s", done)
def process_chain_bets() -> None:
"""BET-31/32: sign what the web admitted, send what was signed. On a real ledger only."""
from django.conf import settings
from apps.lottery import bets
from apps.lottery.electrum_chain import ElectrumChain
chain = ElectrumChain(settings.ELECTRUM_ENDPOINTS, settings.PLM_PROFILE, settings.ELECTRUM_ALLOW_NO_QUORUM)
done = bets.process_bets(chain)
if any(done.values()):
logger.info("bets: %s", done)
def tick() -> None:
"""One pass over everything the worker is responsible for."""
from django.conf import settings
@@ -49,6 +62,7 @@ def tick() -> None:
simulation.settle()
else:
scan_chain_deposits() # B5
process_chain_bets() # B6
lifecycle.tick()
+22
View File
@@ -0,0 +1,22 @@
# Generated by Django 5.2.19 on 2026-11-16 15:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lottery', '0006_deposit_confirmations'),
]
operations = [
migrations.AddField(
model_name='lotteryconfig',
name='fee_rate_sat_vb',
field=models.PositiveIntegerField(default=1),
),
migrations.AddConstraint(
model_name='lotteryconfig',
constraint=models.CheckConstraint(condition=models.Q(('fee_rate_sat_vb__gte', 1), ('fee_rate_sat_vb__lte', 5000)), name='lottery_config_fee_rate_range'),
),
]
+5
View File
@@ -35,6 +35,8 @@ class LotteryConfig(models.Model):
# applies at once to the credits that follow.
deposit_confirmations = models.PositiveSmallIntegerField(default=6)
max_round_pool_sats = models.BigIntegerField(default=0) # 0 = no cap
# Network fee of the transactions built from now on, sat/vB (BET-04); a transaction in flight keeps its own.
fee_rate_sat_vb = models.PositiveIntegerField(default=1)
# ADR-57: three distinct commands.
pause_after_round = models.BooleanField(default=False)
@@ -67,6 +69,9 @@ class LotteryConfig(models.Model):
condition=Q(deposit_confirmations__gte=1, deposit_confirmations__lte=100),
name="lottery_config_deposit_confirmations_range",
),
models.CheckConstraint(
condition=Q(fee_rate_sat_vb__gte=1, fee_rate_sat_vb__lte=5000), name="lottery_config_fee_rate_range"
),
]
@classmethod
+55
View File
@@ -0,0 +1,55 @@
"""Which coins a player may spend, and taking them without anyone else taking them too (BET-30, ARC-72).
A coin is spendable when it is confirmed, accredited (an own change output, or a deposit that reached its
threshold — never one still waiting, DEP-23), not spent and not reserved. Reserving is one conditional `UPDATE`
inside the caller's database transaction: it matches only coins whose `reserved_by` is still empty, and the
number of rows it touched must be the number asked for. Nothing in memory decides who gets a coin.
"""
from django.db import transaction
from django.db.models import Q
from plm_engine.psbt_builder import DUST_LIMIT_SATS, InsufficientFundsError, select_utxos
from plm_engine.psbt_builder import Utxo as EngineUtxo
from .models import ChainTransaction, Deposit, Utxo
class CoinsTaken(Exception):
"""Some of the chosen coins were reserved by someone else between the choice and the reservation."""
def spendable(user):
return Utxo.objects.filter(
Q(deposit__isnull=True) | Q(deposit__status=Deposit.Status.CREDITED),
user=user, confirmed_height__isnull=False, spent_txid__isnull=True, reserved_by__isnull=True,
).order_by("-amount_sats", "id")
def reserve_for(user, amount_sats: int, tx: ChainTransaction) -> list[Utxo]:
"""Choose coins covering `amount_sats` (fee comes out of the amount, change stays above dust) and reserve
them for `tx`. Raises `InsufficientFundsError` if they do not cover it, `CoinsTaken` if someone was faster."""
with transaction.atomic():
coins = list(spendable(user))
selected, total = select_utxos(
[EngineUtxo(c.txid, c.vout, c.amount_sats) for c in coins], amount_sats, min_change_sats=DUST_LIMIT_SATS
)
if total - amount_sats < DUST_LIMIT_SATS:
# B-62: the bet keeps a change output above dust so the transaction stays fee-bumpable; refused here, before
# anything is reserved, instead of when the worker comes to sign.
raise InsufficientFundsError(
f"the amount leaves no change output: {DUST_LIMIT_SATS - (total - amount_sats)} more sats are needed",
code="balance_leaves_no_change", required_extra_sats=DUST_LIMIT_SATS - (total - amount_sats))
by_outpoint = {(c.txid, c.vout): c for c in coins}
chosen = [by_outpoint[(u.txid, u.vout)] for u in selected]
taken = Utxo.objects.filter(pk__in=[c.pk for c in chosen], reserved_by__isnull=True).update(reserved_by=tx)
if taken != len(chosen):
raise CoinsTaken(f"{len(chosen) - taken} of {len(chosen)} coins were taken")
return chosen
def release(tx: ChainTransaction) -> int:
"""Give the coins of `tx` back. Only ever called on proof that the transaction never left (BET-32)."""
return Utxo.objects.filter(reserved_by=tx, spent_txid__isnull=True).update(reserved_by=None)
__all__ = ["CoinsTaken", "InsufficientFundsError", "release", "reserve_for", "spendable"]