diff --git a/CLAUDE.md b/CLAUDE.md index bc35c95..a37c4c5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin ## Project status -All 10 stages of the original build order are code-complete and unit-tested — 831 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. +All 10 stages of the original build order are code-complete and unit-tested — 884 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. Verified on mainnet with real money: registration + address derivation, deposit crediting (at the time, 1-conf; deposits now need `deposit_confirmations`), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only. @@ -61,7 +61,7 @@ PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+pr PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace) PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip -python -m pytest # all 831 tests +python -m pytest # all 884 tests python -m pytest tests/unit/test_hd.py # one file python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test ``` diff --git a/README.md b/README.md index 885eb0c..8b1cdb2 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ python -m pytest # all tests python -m pytest tests/unit/test_hd.py # one file ``` -831 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +884 unit tests cover HD derivation, PSBT building, the Electrum client, bets, deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config, the pending-inclusive balance calculation, and the SSE push channel. No automated integration tests against a live Electrum connection — mainnet diff --git a/apps/lottery/balances.py b/apps/lottery/balances.py new file mode 100644 index 0000000..7623989 --- /dev/null +++ b/apps/lottery/balances.py @@ -0,0 +1,31 @@ +"""A player's balance, derived from the ledger (DAT-78) — never stored beside it.""" + +from dataclasses import dataclass + +from django.db.models import Q, Sum + +from .models import Movement + + +@dataclass(frozen=True) +class Balance: + spendable_sats: int # confirmed funds, minus whatever a pending operation has already reserved + incoming_sats: int # funds in confirmation: pending credits, not spendable yet (WEB-21) + + @property + def total_sats(self) -> int: + return self.spendable_sats + self.incoming_sats + + +def balance_of(user) -> Balance: + """Spendable = confirmed lines + pending debits (a bet or withdrawal in flight reserves its + amount at once). Incoming = pending credits. Failed lines count for nothing.""" + totals = Movement.objects.filter(user=user).aggregate( + confirmed=Sum("amount_sats", filter=Q(status=Movement.Status.CONFIRMED)), + pending_debits=Sum("amount_sats", filter=Q(status=Movement.Status.PENDING, amount_sats__lt=0)), + pending_credits=Sum("amount_sats", filter=Q(status=Movement.Status.PENDING, amount_sats__gt=0)), + ) + return Balance( + spendable_sats=(totals["confirmed"] or 0) + (totals["pending_debits"] or 0), + incoming_sats=totals["pending_credits"] or 0, + ) diff --git a/apps/lottery/errors.py b/apps/lottery/errors.py new file mode 100644 index 0000000..56096d1 --- /dev/null +++ b/apps/lottery/errors.py @@ -0,0 +1,18 @@ +"""Domain errors with a stable code (the contract of the old API, `app/api/errors.py`). + +`code` is what a page maps to its own text; `message` is plain English for logs and tests; +`params` carries the values to place in the text (amounts as `*_sats`). +""" + +from typing import Any + + +class LedgerError(Exception): + def __init__(self, code: str, message: str, **params: Any) -> None: + super().__init__(message) + self.code = code + self.message = message + self.params = params + + def as_dict(self) -> dict[str, Any]: + return {"code": self.code, "message": self.message, "params": self.params} diff --git a/apps/lottery/ledger.py b/apps/lottery/ledger.py new file mode 100644 index 0000000..929359f --- /dev/null +++ b/apps/lottery/ledger.py @@ -0,0 +1,307 @@ +"""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)") diff --git a/apps/lottery/rules.py b/apps/lottery/rules.py new file mode 100644 index 0000000..a72325d --- /dev/null +++ b/apps/lottery/rules.py @@ -0,0 +1,30 @@ +"""Rules of the game that do not depend on how money moves (shared by the simulated ledger and, +later, the chain engine).""" + +from datetime import datetime, timedelta + +from django.utils import timezone + +from .models import Round + +# B-52: a round never grows past what one payout can spend ("it can always be paid out"). +MAX_PARTICIPANTS_PER_ROUND = 400 + +# ADR-14: 70% to the winner, 30% to the platform, the rounding remainder to the platform. +WINNER_PERCENT = 70 + + +def winner_share(pool_sats: int) -> int: + return pool_sats * WINNER_PERCENT // 100 + + +def round_deadline(round_: Round) -> datetime: + """The round's own deadline: opening plus *its* duration, never the live config (ADR-23, B-61).""" + return round_.opened_at + timedelta(seconds=round_.duration_seconds) + + +def round_accepts_bets(round_: Round, now: datetime | None = None) -> bool: + """The authoritative "yellow light": a bet is refused from the deadline on, even if the + scheduler has not flipped the status yet (ADR-23).""" + now = now or timezone.now() + return round_.status == Round.Status.OPEN and now < round_deadline(round_) diff --git a/config/settings.py b/config/settings.py index a82dd65..f71294b 100644 --- a/config/settings.py +++ b/config/settings.py @@ -143,3 +143,14 @@ LOGGING = { "handlers": {"console": {"class": "logging.StreamHandler"}}, "root": {"handlers": ["console"], "level": os.environ.get("LOG_LEVEL", "INFO")}, } + +# ADR-58, ADR-59: the network profile and how money moves. The alpha runs on regtest with a +# simulated ledger; the simulated ledger can never run on mainnet (B2 adds the full profile). +PLM_NETWORK = os.environ.get("PLM_NETWORK", "regtest") +if PLM_NETWORK not in ("regtest", "mainnet"): + raise ImproperlyConfigured(f"PLM_NETWORK must be 'regtest' or 'mainnet', not {PLM_NETWORK!r}") +LEDGER_BACKEND = os.environ.get("LEDGER_BACKEND", "simulated") +if LEDGER_BACKEND not in ("simulated", "chain"): + raise ImproperlyConfigured(f"LEDGER_BACKEND must be 'simulated' or 'chain', not {LEDGER_BACKEND!r}") +if LEDGER_BACKEND == "simulated" and PLM_NETWORK == "mainnet": + raise ImproperlyConfigured("the simulated ledger cannot run on mainnet (ADR-59)") diff --git a/docs/architettura.md b/docs/architettura.md index 9022067..544d9ad 100644 --- a/docs/architettura.md +++ b/docs/architettura.md @@ -990,3 +990,28 @@ non è rimosso le sezioni precedenti descrivono lo stato storico. Scelte: [ADR-5 solo `DJANGO_DEBUG=true` (sviluppo senza Docker) ne genera uno non sicuro. *Stato:* implementato (A1) · *Codice:* `config/settings.py` · *Test:* `tests/django/test_scaffold.py::test_refuses_to_start_without_a_secret` +- **[ARC-75]** **Il denaro si muove attraverso un'interfaccia sola.** Viste e worker usano `Ledger` + (`deposit`, `place_bet`, `confirm_bet`, `reject_bet`, `exclude_bet`, `pay_winner`, `confirm_payout`); + `LEDGER_BACKEND` sceglie l'implementazione. Nella Fase A è `SimulatedLedger` (fondi che esistono solo nel + database, la conferma è una chiamata); nella Fase B un'implementazione di catena sta dietro gli stessi metodi + senza toccare viste né modelli ([ADR-59](adr/ADR-59-motore-plm-pacchetto-senza-framework-ledger-simulato.md)). + Il ledger simulato **non parte su `mainnet`** (`PLM_NETWORK=mainnet` con `LEDGER_BACKEND=simulated` è un errore + di configurazione), e `PLM_NETWORK` e `LEDGER_BACKEND` sconosciuti sono rifiutati all'avvio. + *Stato:* implementato (A3) · + *Codice:* `apps/lottery/ledger.py`, `config/settings.py` · + *Test:* `tests/django/test_ledger.py::test_the_simulated_ledger_cannot_run_on_mainnet`, `test_get_ledger_follows_the_configuration` +- **[ARC-76]** **Idempotenza.** Ogni richiesta di deposito o di puntata porta una chiave (`request_id`): + la stessa chiave dello stesso giocatore è la stessa operazione. Il secondo invio restituisce l'esito del primo + (`replayed`), non addebita né registra nulla e non scrive una seconda riga di audit; una chiave riusata per + un'altra operazione (importo, tipo o round diversi) è l'errore `idempotency_conflict`. La puntata richiede la + chiave (`missing_request_id`). Il vincolo `(user, request_id)` di [DAT-78] è la rete di sicurezza. + *Stato:* implementato (A3) · + *Codice:* `apps/lottery/ledger.py:SimulatedLedger._replay` · + *Test:* `tests/django/test_ledger.py::test_the_same_bet_request_is_one_bet`, `test_the_same_deposit_request_is_one_deposit`, `test_concurrent_requests_with_the_same_key_make_one_bet` +- **[ARC-77]** **Un'operazione è una transazione.** Controlli e scritture di ogni operazione del ledger stanno in una + sola transazione che prende subito il blocco di scrittura ([ARC-70]), così nessun'altra richiesta si inserisce fra + la verifica del saldo e l'addebito; la riga di audit si scrive nella stessa transazione ([AUD-47]). Un'operazione + rifiutata non lascia nulla. Una puntata concorrente dello stesso giocatore nello stesso round ne produce una sola. + *Stato:* implementato (A3) · + *Codice:* `apps/lottery/ledger.py` · + *Test:* `tests/django/test_ledger.py::test_a_failed_operation_leaves_nothing_behind`, `test_concurrent_requests_with_different_keys_make_one_bet` (sei processi su un solo file SQLite) diff --git a/docs/modello-dati.md b/docs/modello-dati.md index 0ccd256..3dc6e47 100644 --- a/docs/modello-dati.md +++ b/docs/modello-dati.md @@ -1525,3 +1525,9 @@ Le tabelle di catena (UTXO, versioni delle transazioni, depositi, indici HD) arr [ADR-56](adr/ADR-56-staff-account-individuali-permessi-mfa-dopo-pilota.md)); username unico senza distinzione fra maiuscole ([DAT-06]), memorizzato come digitato. *Stato:* implementato (A1) · *Codice:* `apps/accounts/models.py` · *Test:* `tests/django/test_scaffold.py::test_usernames_are_unique_ignoring_case` +- **[DAT-80]** **Il saldo si deriva dal libro mastro.** `balance_of(user)` somma le righe di `Movement`: + **spendibile** = righe `confirmed` + addebiti `pending` (una puntata o un prelievo in corso riserva subito il suo + importo); **in conferma** = accrediti `pending`; le righe `failed` non contano. Non esiste un saldo memorizzato + accanto alle righe, quindi non può divergere da esse. + *Stato:* implementato (A3) · *Codice:* `apps/lottery/balances.py:balance_of` · + *Test:* `tests/django/test_ledger.py::test_a_pending_deposit_is_incoming_not_spendable`, `test_a_whole_round_conserves_the_money` diff --git a/docs/sito-e-app.md b/docs/sito-e-app.md index c0dfeaf..1ef0eb8 100644 --- a/docs/sito-e-app.md +++ b/docs/sito-e-app.md @@ -80,8 +80,14 @@ backend FastAPI (vedi [architettura.md](architettura.md)). - **[WEB-22]** Prima di inviare una puntata si mostrano round e importo; il server valida disponibilità, quota, limiti e stato del round. Dopo l'invio si mostra lo stato effettivo (attesa, conferma, rifiuto o esclusione). + *Stato:* validazione e stati implementati nel ledger (A3: round, scadenza, quota del round, limiti, fondi, + `round_closing`, `already_betting`, `round_full`, `bets_suspended`, `balance_pending_confirmation`, rifiuto ed esclusione); + la schermata con l'A7 · + *Codice:* `apps/lottery/ledger.py:SimulatedLedger.place_bet` · *Test:* `tests/django/test_ledger.py` - **[WEB-23]** Un doppio invio della stessa richiesta produce una sola operazione logica (chiave di idempotenza associata alla richiesta). + *Stato:* implementato nel ledger (A3, [ARC-76]); il modulo di invio con l'A7 · + *Test:* `tests/django/test_ledger.py::test_the_same_bet_request_is_one_bet` - **[WEB-24]** Il prelievo mostra, prima della conferma, indirizzo, importo richiesto, commissione e importo netto previsto. Lo storico distingue lo stato dell'operazione dal TXID corrente e lo collega all'explorer quando disponibile. diff --git a/roadmap.md b/roadmap.md index 5deaace..0001fe0 100644 --- a/roadmap.md +++ b/roadmap.md @@ -26,7 +26,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore - [x] **A1 · Scheletro Django.** Progetto Django 5.2 (`config/`, app `accounts`, `lottery`, `web`, `ops`), modello utente personalizzato prima delle migrazioni, impostazioni da ambiente (`SITE_ADDRESS`, `ALLOWED_HOSTS`, `CSRF_TRUSTED_ORIGINS`), SQLite WAL con `transaction_mode=IMMEDIATE`, servizi `web` e `worker` nel compose dietro Caddy. *Requisiti:* WEB-01, WEB-07, ARC. *Test:* `manage.py check`, avvio e risposta `200` su `/`. - [x] **A2 · Modelli e vincoli.** Account, Round (parametri fotografati all'apertura), Partecipazione, Movimento, Transazione, Audit (solo aggiunta). Importi interi in unità minime; un solo round attivo e una sola puntata per utente e round come vincoli del database. *Requisiti:* WEB-04, DAT. *Test:* violazione di ogni vincolo. -- [ ] **A3 · Ledger simulato.** Interfaccia dei servizi (deposito, puntata, pagamento) con implementazione simulata e **chiave di idempotenza**: un doppio invio produce una sola operazione. *Requisiti:* WEB-23, ADR-59. *Test:* doppio invio, saldo insufficiente, importi al limite. +- [x] **A3 · Ledger simulato.** Interfaccia dei servizi (deposito, puntata, pagamento) con implementazione simulata e **chiave di idempotenza**: un doppio invio produce una sola operazione. *Requisiti:* WEB-23, ADR-59. *Test:* doppio invio, saldo insufficiente, importi al limite. - [ ] **A4 · Ciclo del round e worker.** Apertura, chiusura, estrazione e pagamento 70/30 nel worker (`manage.py run_worker`), con l'estrazione commit-reveal dello stesso algoritmo del motore. *Requisiti:* RND esistenti riletti sul modello nuovo. *Test:* round completo deterministico, ripresa dopo riavvio del worker. - [ ] **A5 · Autenticazione e base grafica.** `/registrati/`, `/accedi/`, `/app/profilo/` (password, logout), CSRF, cookie di sessione, ritorno alla destinazione interna (`next`) solo se interna, template base e CSS responsivo. *Requisiti:* WEB-02, WEB-06. *Test:* redirect aperto rifiutato, cookie, throttling dei tentativi. - [ ] **A6 · Home pubblica.** `/` con quota, montepremi confermato, chiusura (ora server) e i sei stati, «Partecipa», aggiornamento a polling. *Requisiti:* WEB-05, WEB-10, WEB-11. *Test:* un test per stato, polling dell'endpoint. diff --git a/tests/django/test_ledger.py b/tests/django/test_ledger.py new file mode 100644 index 0000000..58266ec --- /dev/null +++ b/tests/django/test_ledger.py @@ -0,0 +1,486 @@ +"""A3 — simulated ledger with idempotency: WEB-22, WEB-23, ADR-59, ARC-72, DAT-78, RND-21, BET-07, BET-20.""" + +import json +import os +import subprocess +import sys +from datetime import timedelta +from pathlib import Path +from uuid import uuid4 + +import pytest +from django.contrib.auth import get_user_model +from django.utils import timezone + +from apps.lottery import ledger as ledger_module +from apps.lottery.balances import balance_of +from apps.lottery.errors import LedgerError +from apps.lottery.ledger import SimulatedLedger, get_ledger +from apps.lottery.models import ( + AuditEntry, + ChainTransaction, + LotteryConfig, + Movement, + Participation, + Round, +) +from apps.lottery.rules import winner_share + +ROOT = Path(__file__).resolve().parents[2] +PLM = 100_000_000 +BET = 10 * PLM + +pytestmark = pytest.mark.django_db +ledger = SimulatedLedger() + + +def make_user(name="mario"): + return get_user_model().objects.create_user(name, password="x" * 12) + + +def open_round(**kwargs): + return Round.objects.create(**kwargs) + + +def funded(name="mario", amount=BET): + user = make_user(name) + ledger.deposit(user, amount) + return user + + +def code_of(call) -> str: + with pytest.raises(LedgerError) as caught: + call() + return caught.value.code + + +def audit_actions(): + return list(AuditEntry.objects.order_by("id").values_list("action", flat=True)) + + +# --- deposits ---------------------------------------------------------------------------------- + + +def test_a_confirmed_deposit_is_spendable(): + user = make_user() + result = ledger.deposit(user, 25 * PLM) + assert not result.replayed + assert balance_of(user).spendable_sats == 25 * PLM and balance_of(user).incoming_sats == 0 + assert audit_actions() == ["deposit_credited"] + + +def test_a_pending_deposit_is_incoming_not_spendable(): + """WEB-21: funds in confirmation are shown apart and cannot be spent.""" + user = make_user() + movement = ledger.deposit(user, BET, confirmed=False).obj + assert (balance_of(user).spendable_sats, balance_of(user).incoming_sats) == (0, BET) + ledger.confirm_deposit(movement) + assert (balance_of(user).spendable_sats, balance_of(user).incoming_sats) == (BET, 0) + ledger.confirm_deposit(movement) # again: nothing changes + assert balance_of(user).spendable_sats == BET + + +@pytest.mark.parametrize("amount", [0, -5, 1.5, "10", True, None]) +def test_deposit_refuses_a_bad_amount(amount): + assert code_of(lambda: ledger.deposit(make_user(), amount)) == "invalid_amount" + + +def test_the_same_deposit_request_is_one_deposit(): + """WEB-23.""" + user, key = make_user(), uuid4() + first = ledger.deposit(user, BET, request_id=key) + second = ledger.deposit(user, BET, request_id=key) + assert (first.replayed, second.replayed) == (False, True) and first.obj.pk == second.obj.pk + assert Movement.objects.count() == 1 and balance_of(user).spendable_sats == BET + assert audit_actions() == ["deposit_credited"] # the replay left no second trace + + +def test_a_deposit_key_reused_for_a_different_amount_is_an_error(): + user, key = make_user(), uuid4() + ledger.deposit(user, BET, request_id=key) + assert code_of(lambda: ledger.deposit(user, BET + 1, request_id=key)) == "idempotency_conflict" + assert Movement.objects.count() == 1 + + +def test_a_failed_operation_leaves_nothing_behind(): + """ARC-72: the write and its audit row commit together or not at all.""" + user = make_user() + assert code_of(lambda: ledger.deposit(user, 0)) == "invalid_amount" + assert Movement.objects.count() == 0 and AuditEntry.objects.count() == 0 + + +# --- placing a bet ----------------------------------------------------------------------------- + + +def test_a_bet_reserves_the_funds_and_waits_for_confirmation(): + user, round_ = funded(), open_round() + result = ledger.place_bet(user, round_.pk, request_id=uuid4()) + bet = result.obj + assert not result.replayed + assert (bet.status, bet.bet_amount_sats, bet.round_id) == ("pending", BET, round_.pk) + movement = Movement.objects.get(kind="bet") + assert (movement.amount_sats, movement.status, movement.participation_id) == (-BET, "pending", bet.pk) + chain = ChainTransaction.objects.get(kind="bet") + assert chain.status == "pending" and len(chain.current_txid) == 64 and bet.bet_txid == chain.current_txid + assert balance_of(user).spendable_sats == 0 # reserved at once + assert audit_actions() == ["deposit_credited", "bet_placed"] + + +def test_the_same_bet_request_is_one_bet(): + """WEB-23: a double send is one logical operation, charged once.""" + user, round_, key = funded(), open_round(), uuid4() + first = ledger.place_bet(user, round_.pk, request_id=key) + second = ledger.place_bet(user, round_.pk, request_id=key) + assert (first.replayed, second.replayed) == (False, True) and first.obj.pk == second.obj.pk + assert Participation.objects.count() == 1 and Movement.objects.filter(kind="bet").count() == 1 + assert ChainTransaction.objects.count() == 1 + assert audit_actions().count("bet_placed") == 1 + + +def test_a_replay_still_answers_after_the_round_has_closed_for_bets(): + user, round_, key = funded(), open_round(), uuid4() + first = ledger.place_bet(user, round_.pk, request_id=key) + Round.objects.filter(pk=round_.pk).update(status="closing") + assert ledger.place_bet(user, round_.pk, request_id=key).obj.pk == first.obj.pk + + +def test_a_bet_key_reused_for_another_round_or_kind_is_an_error(): + user, key = funded(amount=2 * BET), uuid4() + first = open_round() + ledger.place_bet(user, first.pk, request_id=key) + first.status, first.closed_at = "closed", timezone.now() + first.save() + second = open_round() + assert code_of(lambda: ledger.place_bet(user, second.pk, request_id=key)) == "idempotency_conflict" + deposit_key = uuid4() + ledger.deposit(user, PLM, request_id=deposit_key) + assert code_of(lambda: ledger.place_bet(user, second.pk, request_id=deposit_key)) == "idempotency_conflict" + + +def test_a_bet_needs_an_idempotency_key(): + user, round_ = funded(), open_round() + assert code_of(lambda: ledger.place_bet(user, round_.pk, request_id=None)) == "missing_request_id" + assert code_of(lambda: ledger.place_bet(user, round_.pk, request_id="not-a-uuid")) == "missing_request_id" + + +def test_the_server_charges_the_rounds_own_quota(): + """ADR-10: an edit of the config after the round opened does not change what it costs.""" + user, round_ = funded(amount=BET), open_round(bet_amount_sats=BET) + config = LotteryConfig.get() + config.bet_amount_sats = 20 * PLM + config.save() + assert ledger.place_bet(user, round_.pk, request_id=uuid4()).obj.bet_amount_sats == BET + + +def test_insufficient_funds_are_refused_with_the_required_amount(): + user, round_ = funded(amount=BET - 1), open_round() + with pytest.raises(LedgerError) as caught: + ledger.place_bet(user, round_.pk, request_id=uuid4()) + assert caught.value.code == "insufficient_balance" and caught.value.params == {"required_sats": BET} + assert Participation.objects.count() == 0 + + +def test_funds_still_in_confirmation_ask_to_wait(): + """BET-07: the balance on screen covers the bet, but it is not confirmed yet.""" + user, round_ = make_user(), open_round() + ledger.deposit(user, BET, confirmed=False) + with pytest.raises(LedgerError) as caught: + ledger.place_bet(user, round_.pk, request_id=uuid4()) + assert caught.value.code == "balance_pending_confirmation" and caught.value.params == {"pending_sats": BET} + + +def test_one_bet_per_player_per_round_even_with_another_key(): + user, round_ = funded(amount=2 * BET), open_round() + ledger.place_bet(user, round_.pk, request_id=uuid4()) + assert code_of(lambda: ledger.place_bet(user, round_.pk, request_id=uuid4())) == "already_betting" + assert balance_of(user).spendable_sats == BET # charged once + + +def test_bets_are_refused_from_the_rounds_own_deadline(): + """ADR-23: the deadline decides, not the status the scheduler has not flipped yet.""" + user = funded() + late = open_round(opened_at=timezone.now() - timedelta(seconds=601), duration_seconds=600) + assert code_of(lambda: ledger.place_bet(user, late.pk, request_id=uuid4())) == "round_closing" + + +@pytest.mark.parametrize("status", ["closing", "drawing", "paying_out"]) +def test_bets_are_refused_once_the_round_leaves_open(status): + user, round_ = funded(), open_round(status=status) + assert code_of(lambda: ledger.place_bet(user, round_.pk, request_id=uuid4())) == "round_closing" + + +def test_no_round_open(): + user = funded() + closed = open_round(status="closed", closed_at=timezone.now()) + assert code_of(lambda: ledger.place_bet(user, closed.pk, request_id=uuid4())) == "no_round_open" + assert code_of(lambda: ledger.place_bet(user, 99999, request_id=uuid4())) == "no_round_open" + + +def test_suspended_bets_are_refused(): + """ADR-57: «Sospendi nuove puntate».""" + user, round_ = funded(), open_round() + config = LotteryConfig.get() + config.new_bets_suspended = True + config.save() + assert code_of(lambda: ledger.place_bet(user, round_.pk, request_id=uuid4())) == "bets_suspended" + + +def test_a_round_has_a_maximum_of_players(monkeypatch): + """B-52, BET-20: refused before any money moves.""" + monkeypatch.setattr(ledger_module, "MAX_PARTICIPANTS_PER_ROUND", 2) + round_ = open_round() + for name in ("a", "b"): + ledger.place_bet(funded(name), round_.pk, request_id=uuid4()) + late = funded("c") + assert code_of(lambda: ledger.place_bet(late, round_.pk, request_id=uuid4())) == "round_full" + assert balance_of(late).spendable_sats == BET + + +def test_a_round_stops_at_its_pool_cap(): + """BET-20: refused once the pool has reached the cap — it may exceed it by at most one bet.""" + round_ = open_round(max_round_pool_sats=BET + 1) + ledger.place_bet(funded("a"), round_.pk, request_id=uuid4()) # pool 10 < cap + ledger.place_bet(funded("b"), round_.pk, request_id=uuid4()) # pool 20 >= cap now + assert code_of(lambda: ledger.place_bet(funded("c"), round_.pk, request_id=uuid4())) == "round_full" + + +# --- what happens to a bet afterwards ---------------------------------------------------------- + + +def placed(name="mario"): + user, round_ = funded(name), Round.objects.filter(status="open").first() or open_round() + return user, ledger.place_bet(user, round_.pk, request_id=uuid4()).obj + + +def test_confirming_a_bet_confirms_its_transaction_and_movement(): + user, bet = placed() + confirmed = ledger.confirm_bet(bet) + assert confirmed.status == "confirmed" and confirmed.confirmed_at is not None + assert ChainTransaction.objects.get(kind="bet").status == "confirmed" + assert Movement.objects.get(kind="bet").status == "confirmed" + assert balance_of(user).spendable_sats == 0 + ledger.confirm_bet(bet) # idempotent + assert audit_actions().count("bet_confirmed") == 1 + + +def test_a_rejected_bet_returns_the_funds_and_keeps_the_reason(): + user, bet = placed() + ledger.reject_bet(bet, "refused by the network") + assert Participation.objects.get().status == "rejected" + chain = ChainTransaction.objects.get(kind="bet") + assert (chain.status, chain.failure_reason) == ("failed", "refused by the network") + assert balance_of(user).spendable_sats == BET + assert code_of(lambda: ledger.confirm_bet(bet)) == "invalid_state" + entry = AuditEntry.objects.get(action="bet_rejected") + assert entry.reason == "refused by the network" + + +def test_rejecting_or_excluding_needs_a_reason(): + _, bet = placed() + assert code_of(lambda: ledger.reject_bet(bet, " ")) == "reason_required" + ledger.confirm_bet(bet) + assert code_of(lambda: ledger.exclude_bet(bet, "")) == "reason_required" + + +def test_a_confirmed_bet_cannot_be_rejected_and_a_pending_one_cannot_be_excluded(): + _, first = placed("a") + assert code_of(lambda: ledger.exclude_bet(first, "gone")) == "invalid_state" + ledger.confirm_bet(first) + assert code_of(lambda: ledger.reject_bet(first, "late")) == "invalid_state" + + +def test_an_excluded_bet_is_refunded_once(): + user, bet = placed() + ledger.confirm_bet(bet) + Participation.objects.filter(pk=bet.pk).update(draw_position=0) + ledger.exclude_bet(bet, "the bet is no longer on the chain") + excluded = Participation.objects.get() + assert (excluded.status, excluded.draw_position) == ("excluded", None) + assert balance_of(user).spendable_sats == BET + ledger.exclude_bet(bet, "again") # idempotent: no second refund + assert Movement.objects.filter(kind="refund").count() == 1 and balance_of(user).spendable_sats == BET + + +# --- the payout -------------------------------------------------------------------------------- + + +def paying_round(bets=3, bet_amount=BET): + """A round in `paying_out` with `bets` confirmed participants; the first one won.""" + round_ = open_round(bet_amount_sats=bet_amount) + users = [] + for i in range(bets): + user = funded(f"p{i}", bet_amount) + users.append(user) + ledger.confirm_bet(ledger.place_bet(user, round_.pk, request_id=uuid4()).obj) + round_.status, round_.winner = Round.Status.PAYING_OUT, users[0] + round_.save() + return round_, users + + +def test_the_pool_is_split_70_30_and_the_winner_is_credited(): + """RND-21.""" + round_, users = paying_round(bets=3) + result = ledger.pay_winner(round_.pk) + round_.refresh_from_db() + assert (round_.pool_amount_sats, round_.winner_amount_sats, round_.fee_amount_sats) == (3 * BET, 21 * PLM, 9 * PLM) + assert round_.payout_transaction_id == result.obj.pk and result.obj.kind == "payout" + win = Movement.objects.get(kind="win") + assert (win.user, win.amount_sats, win.status) == (users[0], 21 * PLM, "pending") + assert balance_of(users[0]).incoming_sats == 21 * PLM # in confirmation, not spendable yet + ledger.confirm_payout(round_.pk) + assert balance_of(users[0]).spendable_sats == 21 * PLM and balance_of(users[0]).incoming_sats == 0 + assert balance_of(users[1]).spendable_sats == 0 + + +@pytest.mark.parametrize("pool", [1, 3, 10, 11, 99, 1000, 123_456_789]) +def test_the_split_never_loses_or_invents_a_satoshi(pool): + """RND-21: the rounding remainder goes to the platform; winner + fee == pool.""" + winner = winner_share(pool) + assert winner == pool * 70 // 100 and 0 <= winner <= pool + assert winner + (pool - winner) == pool + + +def test_the_rounding_remainder_goes_to_the_platform(): + round_, _ = paying_round(bets=1, bet_amount=11) + ledger.pay_winner(round_.pk) + round_.refresh_from_db() + assert (round_.winner_amount_sats, round_.fee_amount_sats) == (7, 4) # 70% of 11 = 7.7 -> 7 + + +def test_a_round_is_paid_once(): + round_, users = paying_round() + first, second = ledger.pay_winner(round_.pk), ledger.pay_winner(round_.pk) + assert (first.replayed, second.replayed) == (False, True) and first.obj.pk == second.obj.pk + assert Movement.objects.filter(kind="win").count() == 1 + assert audit_actions().count("payout_created") == 1 + ledger.confirm_payout(round_.pk) + ledger.confirm_payout(round_.pk) + assert audit_actions().count("payout_confirmed") == 1 + assert balance_of(users[0]).spendable_sats == 21 * PLM + + +def test_only_a_round_that_is_paying_out_can_be_paid(): + round_, _ = paying_round() + Round.objects.filter(pk=round_.pk).update(status="drawing") + assert code_of(lambda: ledger.pay_winner(round_.pk)) == "round_not_paying_out" + + +def test_the_winner_must_be_a_confirmed_participant(): + round_, _ = paying_round() + outsider = make_user("outsider") + Round.objects.filter(pk=round_.pk).update(winner=outsider) + assert code_of(lambda: ledger.pay_winner(round_.pk)) == "winner_not_a_participant" + Round.objects.filter(pk=round_.pk).update(winner=None) + assert code_of(lambda: ledger.pay_winner(round_.pk)) == "winner_not_a_participant" + assert Movement.objects.filter(kind="win").count() == 0 + + +def test_a_payout_without_a_transaction_cannot_be_confirmed(): + round_, _ = paying_round() + assert code_of(lambda: ledger.confirm_payout(round_.pk)) == "no_payout" + + +# --- conservation ------------------------------------------------------------------------------ + + +def test_a_whole_round_conserves_the_money(): + """Deposits in == balances + the platform's share, after a full round.""" + round_, users = paying_round(bets=4) + ledger.pay_winner(round_.pk) + ledger.confirm_payout(round_.pk) + round_.refresh_from_db() + held = sum(balance_of(u).spendable_sats for u in users) + deposited = sum(Movement.objects.filter(kind="deposit").values_list("amount_sats", flat=True)) + assert held + round_.fee_amount_sats == deposited # nothing lost, nothing invented + + +# --- configuration ----------------------------------------------------------------------------- + + +def _run_settings(**env): + clean = {"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60, **env} + return subprocess.run([sys.executable, "-c", "import config.settings"], cwd=ROOT, env=clean, + capture_output=True, text=True) + + +def test_the_simulated_ledger_cannot_run_on_mainnet(): + """ADR-59.""" + result = _run_settings(PLM_NETWORK="mainnet") + assert result.returncode != 0 and "simulated ledger" in result.stderr + assert _run_settings(PLM_NETWORK="mainnet", LEDGER_BACKEND="chain").returncode == 0 + assert _run_settings().returncode == 0 # the default: regtest + simulated + + +@pytest.mark.parametrize("env", [{"PLM_NETWORK": "testnet"}, {"LEDGER_BACKEND": "magic"}]) +def test_unknown_network_or_ledger_is_refused(env): + assert _run_settings(**env).returncode != 0 + + +def test_get_ledger_follows_the_configuration(settings): + assert isinstance(get_ledger(), SimulatedLedger) + settings.LEDGER_BACKEND = "chain" + with pytest.raises(NotImplementedError): + get_ledger() + + +# --- real concurrency: separate processes on one SQLite file ----------------------------------- + +_WORKER = """ +import json, os, sys, uuid +import django +django.setup() +from django.contrib.auth import get_user_model +from apps.lottery.errors import LedgerError +from apps.lottery.ledger import get_ledger +user = get_user_model().objects.get(username=sys.argv[1]) +try: + result = get_ledger().place_bet(user, int(sys.argv[2]), request_id=uuid.UUID(sys.argv[3])) + print(json.dumps({"ok": result.obj.pk, "replayed": result.replayed})) +except LedgerError as exc: + print(json.dumps({"err": exc.code})) +""" + +_SETUP = """ +import django +django.setup() +from django.contrib.auth import get_user_model +from apps.lottery.ledger import get_ledger +from apps.lottery.models import Round +user = get_user_model().objects.create_user("mario", password="x" * 12) +get_ledger().deposit(user, 10 * 10**8) +print(Round.objects.create().pk) +""" + + +@pytest.fixture +def shared_db(tmp_path): + env = {"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60, + "DJANGO_DB_PATH": str(tmp_path / "site.sqlite3"), "DJANGO_SETTINGS_MODULE": "config.settings"} + subprocess.run([sys.executable, "manage.py", "migrate", "--noinput", "-v", "0"], cwd=ROOT, env=env, check=True) + round_id = subprocess.run([sys.executable, "-c", _SETUP], cwd=ROOT, env=env, check=True, + capture_output=True, text=True).stdout.strip() + return env, int(round_id) + + +def _race(env, round_id, keys): + procs = [subprocess.Popen([sys.executable, "-c", _WORKER, "mario", str(round_id), key], cwd=ROOT, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for key in keys] + outputs = [p.communicate(timeout=120) for p in procs] + assert all(p.returncode == 0 for p in procs), [o[1] for o in outputs] + return [json.loads(o[0].strip().splitlines()[-1]) for o in outputs] + + +def test_concurrent_requests_with_the_same_key_make_one_bet(shared_db): + """ARC-72, WEB-23: six processes send the same request at once; one bet, one charge.""" + env, round_id = shared_db + results = _race(env, round_id, ["3f1c6a52-0000-4000-8000-000000000001"] * 6) + assert all("ok" in r for r in results) and len({r["ok"] for r in results}) == 1 + assert sorted(r["replayed"] for r in results) == [False] + [True] * 5 + + +def test_concurrent_requests_with_different_keys_make_one_bet(shared_db): + """ARC-72: six different requests from one player race for one place; exactly one wins.""" + env, round_id = shared_db + results = _race(env, round_id, [str(uuid4()) for _ in range(6)]) + assert sum("ok" in r for r in results) == 1 + assert [r["err"] for r in results if "err" in r] == ["already_betting"] * 5