Files
plm-lottery/apps/lottery/ledger.py
T
davideandClaude Sonnet 5.5 eded058dbb A3: simulated ledger with idempotency (WEB-22, WEB-23, ADR-59, ARC-75..77, DAT-80)
One Ledger interface (deposit, bet, confirm, reject, exclude, payout) with a
simulated implementation chosen by LEDGER_BACKEND, refused on mainnet. Every
operation is a single write-locked transaction with its audit row; the same
request key is the same operation, a key reused for something else is an
error. The server validates round, deadline, the round's own quota, limits and
funds. The balance is derived from the ledger. Tests include six processes
racing on one SQLite file; the idempotency tests were checked to fail when
the replay is removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 13:23:29 +01:00

308 lines
17 KiB
Python

"""How money moves: one interface, a simulated implementation (ADR-59, roadmap A3).
Views and the worker talk to `Ledger`. Phase A runs `SimulatedLedger`; phase B adds the
implementation that builds, signs and broadcasts real transactions behind the same methods, so
nothing above this module changes.
Every operation is one database transaction (`transaction.atomic()` takes the write lock up front,
ADR-55): the checks and the writes cannot be interleaved with another request's, and the audit row
commits or rolls back with the change (ADR-53). A request carries an idempotency key (WEB-23): the
same key from the same player is the same operation, and sending it again returns the first
outcome instead of doing it twice.
"""
import hashlib
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any
from uuid import UUID
from django.conf import settings
from django.db import IntegrityError, transaction
from django.utils import timezone
from . import audit
from .balances import balance_of
from .errors import LedgerError
from .models import ChainTransaction, LotteryConfig, Movement, Participation, Round
from .rules import MAX_PARTICIPANTS_PER_ROUND, round_accepts_bets, winner_share
@dataclass(frozen=True)
class Result:
"""What an operation produced, and whether it was a replay of an earlier identical request."""
obj: Any
replayed: bool = False
class Ledger(ABC):
@abstractmethod
def deposit(self, user, amount_sats: int, *, request_id: UUID | None = None, confirmed: bool = True) -> Result: ...
@abstractmethod
def confirm_deposit(self, movement: Movement) -> Movement: ...
@abstractmethod
def place_bet(self, user, round_id: int, *, request_id: UUID) -> Result: ...
@abstractmethod
def confirm_bet(self, participation: Participation) -> Participation: ...
@abstractmethod
def reject_bet(self, participation: Participation, reason: str) -> Participation: ...
@abstractmethod
def exclude_bet(self, participation: Participation, reason: str) -> Participation: ...
@abstractmethod
def pay_winner(self, round_id: int) -> Result: ...
@abstractmethod
def confirm_payout(self, round_id: int) -> Round: ...
def _simulated_txid(kind: str) -> str:
return hashlib.sha256(f"simulated:{kind}:{uuid.uuid4()}".encode()).hexdigest()
class SimulatedLedger(Ledger):
"""Funds that exist only in the database. Confirmation is a method call, not a block."""
# -- deposits ---------------------------------------------------------------------------
def deposit(self, user, amount_sats: int, *, request_id: UUID | None = None, confirmed: bool = True) -> Result:
if not isinstance(amount_sats, int) or isinstance(amount_sats, bool) or amount_sats <= 0:
raise LedgerError("invalid_amount", "the amount must be a positive whole number of satoshi")
with transaction.atomic():
replay = self._replay(user, request_id, Movement.Kind.DEPOSIT, amount_sats)
if replay is not None:
return Result(replay, replayed=True)
now = timezone.now()
movement = Movement.objects.create(
user=user, kind=Movement.Kind.DEPOSIT, amount_sats=amount_sats, request_id=request_id,
status=Movement.Status.CONFIRMED if confirmed else Movement.Status.PENDING,
confirmed_at=now if confirmed else None,
)
audit.record("deposit_credited" if confirmed else "deposit_pending", actor=user,
subject_type="movement", subject_id=movement.pk, payload={"amount_sats": amount_sats})
return Result(movement)
def confirm_deposit(self, movement: Movement) -> Movement:
with transaction.atomic():
movement = Movement.objects.get(pk=movement.pk)
if movement.kind != Movement.Kind.DEPOSIT:
raise LedgerError("not_a_deposit", "only a deposit can be confirmed here")
if movement.status == Movement.Status.CONFIRMED:
return movement
if movement.status != Movement.Status.PENDING:
raise LedgerError("invalid_state", f"a {movement.status} deposit cannot be confirmed")
movement.status, movement.confirmed_at = Movement.Status.CONFIRMED, timezone.now()
movement.save(update_fields=["status", "confirmed_at"])
audit.record("deposit_credited", subject_type="movement", subject_id=movement.pk,
payload={"amount_sats": movement.amount_sats})
return movement
# -- bets -------------------------------------------------------------------------------
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)
txid = _simulated_txid("bet")
chain_tx = ChainTransaction.objects.create(
kind=ChainTransaction.Kind.BET, status=ChainTransaction.Status.PENDING, user=user, round=round_,
current_txid=txid, broadcast_at=timezone.now(),
)
try:
with transaction.atomic():
participation = Participation.objects.create(
round=round_, user=user, bet_amount_sats=amount, bet_txid=txid
)
except IntegrityError: # unreachable under the write lock; the constraint is the backstop
raise LedgerError("already_betting", "you already have an active bet in the current round") from None
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})
return Result(participation)
@staticmethod
def _check_round_capacity(round_: Round) -> None:
participants = Participation.objects.filter(round=round_)
if participants.count() >= MAX_PARTICIPANTS_PER_ROUND:
raise LedgerError("round_full", f"this round already has its maximum of {MAX_PARTICIPANTS_PER_ROUND} players",
max_participants=MAX_PARTICIPANTS_PER_ROUND)
if round_.max_round_pool_sats:
# BET-20: refused once the sum has *reached* the cap; every row counts, in-flight included.
pool = sum(participants.values_list("bet_amount_sats", flat=True))
if pool >= round_.max_round_pool_sats:
raise LedgerError("round_full", "this round has reached its limit",
max_round_pool_sats=round_.max_round_pool_sats)
def confirm_bet(self, participation: Participation) -> Participation:
with transaction.atomic():
participation = Participation.objects.select_related("round").get(pk=participation.pk)
if participation.status == Participation.Status.CONFIRMED:
return participation
if participation.status != Participation.Status.PENDING:
raise LedgerError("invalid_state", f"a {participation.status} bet cannot be confirmed")
now = timezone.now()
participation.status, participation.confirmed_at = Participation.Status.CONFIRMED, now
participation.save(update_fields=["status", "confirmed_at"])
ChainTransaction.objects.filter(current_txid=participation.bet_txid).update(
status=ChainTransaction.Status.CONFIRMED, confirmed_at=now)
Movement.objects.filter(participation=participation, kind=Movement.Kind.BET).update(
status=Movement.Status.CONFIRMED, confirmed_at=now)
audit.record("bet_confirmed", subject_type="participation", subject_id=participation.pk)
return participation
def reject_bet(self, participation: Participation, reason: str) -> Participation:
"""A bet that never took part: it stops reserving funds and nothing else is owed."""
self._require_reason(reason)
with transaction.atomic():
participation = Participation.objects.get(pk=participation.pk)
if participation.status == Participation.Status.REJECTED:
return participation
if participation.status != Participation.Status.PENDING:
raise LedgerError("invalid_state", f"a {participation.status} bet cannot be rejected")
now = timezone.now()
participation.status = Participation.Status.REJECTED
participation.save(update_fields=["status"])
ChainTransaction.objects.filter(current_txid=participation.bet_txid).update(
status=ChainTransaction.Status.FAILED, failed_at=now, failure_reason=reason)
Movement.objects.filter(participation=participation, kind=Movement.Kind.BET).update(
status=Movement.Status.FAILED)
audit.record("bet_rejected", reason=reason, subject_type="participation", subject_id=participation.pk)
return participation
def exclude_bet(self, participation: Participation, reason: str) -> Participation:
"""A confirmed bet left out of the draw: its amount goes back as a refund line."""
self._require_reason(reason)
with transaction.atomic():
participation = Participation.objects.get(pk=participation.pk)
if participation.status == Participation.Status.EXCLUDED:
return participation
if participation.status != Participation.Status.CONFIRMED:
raise LedgerError("invalid_state", f"a {participation.status} bet cannot be excluded")
now = timezone.now()
participation.status, participation.draw_position = Participation.Status.EXCLUDED, None
participation.save(update_fields=["status", "draw_position"])
Movement.objects.create(
user=participation.user, kind=Movement.Kind.REFUND, amount_sats=participation.bet_amount_sats,
status=Movement.Status.CONFIRMED, confirmed_at=now, round=participation.round,
participation=participation,
)
audit.record("bet_excluded", reason=reason, subject_type="participation", subject_id=participation.pk,
payload={"refund_sats": participation.bet_amount_sats})
return participation
@staticmethod
def _require_reason(reason: str) -> None:
if not reason.strip():
raise LedgerError("reason_required", "a reason is required")
# -- payout -----------------------------------------------------------------------------
def pay_winner(self, round_id: int) -> Result:
"""Split the pool 70/30 and credit the winner (RND-21). The same round is paid once."""
with transaction.atomic():
round_ = Round.objects.get(pk=round_id)
if round_.payout_transaction_id is not None:
return Result(round_.payout_transaction, replayed=True)
if round_.status != Round.Status.PAYING_OUT:
raise LedgerError("round_not_paying_out", "only a round that is paying out can be paid")
confirmed = Participation.objects.filter(round=round_, status=Participation.Status.CONFIRMED)
winner_participation = confirmed.filter(user=round_.winner_id).first() if round_.winner_id else None
if winner_participation is None:
raise LedgerError("winner_not_a_participant", "the winner is not a confirmed participant of the round")
pool = sum(confirmed.values_list("bet_amount_sats", flat=True))
winner_amount = winner_share(pool)
fee_amount = pool - winner_amount # the rounding remainder goes to the platform
if winner_amount <= 0:
raise LedgerError("nothing_to_pay", "the pool is too small to pay a winner")
chain_tx = ChainTransaction.objects.create(
kind=ChainTransaction.Kind.PAYOUT, status=ChainTransaction.Status.PENDING, round=round_,
current_txid=_simulated_txid("payout"), broadcast_at=timezone.now(),
)
Movement.objects.create(
user=round_.winner, kind=Movement.Kind.WIN, amount_sats=winner_amount,
status=Movement.Status.PENDING, round=round_, chain_transaction=chain_tx,
)
round_.pool_amount_sats, round_.winner_amount_sats, round_.fee_amount_sats = pool, winner_amount, fee_amount
round_.payout_transaction = chain_tx
round_.save(update_fields=["pool_amount_sats", "winner_amount_sats", "fee_amount_sats", "payout_transaction"])
audit.record("payout_created", subject_type="round", subject_id=round_.pk,
payload={"pool_sats": pool, "winner_sats": winner_amount, "fee_sats": fee_amount})
return Result(chain_tx)
def confirm_payout(self, round_id: int) -> Round:
with transaction.atomic():
round_ = Round.objects.select_related("payout_transaction").get(pk=round_id)
chain_tx = round_.payout_transaction
if chain_tx is None:
raise LedgerError("no_payout", "the round has no payout to confirm")
if chain_tx.status == ChainTransaction.Status.CONFIRMED:
return round_
now = timezone.now()
chain_tx.status, chain_tx.confirmed_at = ChainTransaction.Status.CONFIRMED, now
chain_tx.save(update_fields=["status", "confirmed_at"])
Movement.objects.filter(chain_transaction=chain_tx, kind=Movement.Kind.WIN).update(
status=Movement.Status.CONFIRMED, confirmed_at=now)
audit.record("payout_confirmed", subject_type="round", subject_id=round_.pk)
return round_
# -- idempotency ------------------------------------------------------------------------
@staticmethod
def _replay(user, request_id: UUID | None, kind: str, amount_sats: int | None) -> Movement | None:
"""The earlier operation with this key, if any. A key reused for something else is an error,
not a replay (WEB-23)."""
if request_id is None:
return None
existing = Movement.objects.filter(user=user, request_id=request_id).select_related("participation").first()
if existing is None:
return None
if existing.kind != kind or (amount_sats is not None and existing.amount_sats != amount_sats):
raise LedgerError("idempotency_conflict", "this request key was already used for a different operation")
return existing
def get_ledger() -> Ledger:
if settings.LEDGER_BACKEND == "simulated":
return SimulatedLedger()
raise NotImplementedError("the chain ledger arrives with phase B (roadmap B6)")