Files
plm-lottery/apps/lottery/reservation.py
T

56 lines
2.9 KiB
Python

"""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"]