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

+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()