From 1d4b53d778e6799dca56a5e4b04611522da1b36a Mon Sep 17 00:00:00 2001 From: Davide Grilli Date: Mon, 16 Nov 2026 13:43:09 +0100 Subject: [PATCH] A4: round lifecycle, commit-reveal draw and simulated chain (RND-41..44, ADR-57, ADR-59) lifecycle.tick runs the round from open to closed one write-locked step at a time, resumable from the database (an interrupted draw gives the same winner). Draw primitives move to plm_engine.draw and are shared with the old module. SimulatedChain and settle() stand in for blocks and confirmations; the worker runs both every tick and opens the first round. The round secret is stored encrypted and revealed with the winner; the proof exposes no usernames. Mutation checks confirmed the wait for in-flight bets and the txid ordering are caught by the tests. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 4 +- Dockerfile | 1 + README.md | 2 +- app/rounds/draw.py | 65 +-- apps/lottery/addresses.py | 11 + apps/lottery/lifecycle.py | 236 +++++++++ .../lottery/management/commands/run_worker.py | 24 +- apps/lottery/seedbox.py | 28 ++ apps/lottery/simulation.py | 70 +++ config/settings.py | 5 + docs/ciclo-di-vita-del-round.md | 46 ++ plm_engine/__init__.py | 1 + plm_engine/draw.py | 65 +++ pyproject.toml | 2 +- roadmap.md | 4 +- tests/django/test_lifecycle.py | 475 ++++++++++++++++++ tests/django/test_scaffold.py | 6 +- 17 files changed, 978 insertions(+), 67 deletions(-) create mode 100644 apps/lottery/addresses.py create mode 100644 apps/lottery/lifecycle.py create mode 100644 apps/lottery/seedbox.py create mode 100644 apps/lottery/simulation.py create mode 100644 plm_engine/__init__.py create mode 100644 plm_engine/draw.py create mode 100644 tests/django/test_lifecycle.py diff --git a/CLAUDE.md b/CLAUDE.md index a37c4c5..6866272 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 — 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. +All 10 stages of the original build order are code-complete and unit-tested — 912 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 884 tests +python -m pytest # all 912 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/Dockerfile b/Dockerfile index 61f02c3..d204c93 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,6 +14,7 @@ RUN pip install --no-cache-dir --require-hashes --no-deps -r requirements.lock COPY pyproject.toml manage.py ./ COPY config ./config COPY apps ./apps +COPY plm_engine ./plm_engine RUN pip install --no-cache-dir --no-deps . \ && DJANGO_DEBUG=true python manage.py collectstatic --noinput \ diff --git a/README.md b/README.md index 8b1cdb2..9944676 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 ``` -884 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +912 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/app/rounds/draw.py b/app/rounds/draw.py index 36ce6ab..eff8ff1 100644 --- a/app/rounds/draw.py +++ b/app/rounds/draw.py @@ -1,5 +1,4 @@ import hashlib -import secrets # Byte offsets of a standard 80-byte block header: version(4) + prev_block(32) + # merkle_root(32) + timestamp(4) + bits(4) + nonce(4). @@ -89,56 +88,14 @@ def header_meets_its_own_target(header_hex: str) -> bool: return hash_int <= target -def sha256_hex(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def new_server_seed() -> str: - """B-73 (RND-34, DAT-64): a round's secret — 32 random bytes from the OS CSPRNG, as - 64 lowercase hex characters.""" - return secrets.token_bytes(32).hex() - - -def server_seed_commitment(server_seed_hex: str) -> str: - """`server_seed_hash`: sha256 of the secret's 32 bytes, published from the opening of - the round so the operator cannot change the secret afterwards (RND-34).""" - return sha256_hex(bytes.fromhex(server_seed_hex)) - - -def participants_hash(rows: list[tuple[str, int, str]]) -> str: - """The fingerprint of the ordered draw list (RND-14): sha256 of one `txid:vout:address` - line per participant, in `draw_position` order, each line ending in `\n`, UTF-8. `txid` - is the bet transaction's, lowercase hex as explorers show it; `vout` is the output paying - the round's pool address, in decimal; `address` is the participant's own.""" - text = "".join(f"{txid}:{vout}:{address}\n" for txid, vout, address in rows) - return sha256_hex(text.encode("utf-8")) - - -def draw_seed(server_seed_hex: str, block_hash_hex: str, participants_hash_hex: str) -> int: - """RND-17: sha256 of the secret (32 bytes), the hash of the block at `draw_height` (32 - bytes, in the order explorers show it) and `participants_hash` (32 bytes), read as an - unsigned big-endian integer. Nobody who lacks the secret can predict it, and the - operator, who knows the secret, cannot know the block when committing to the list.""" - digest = hashlib.sha256( - bytes.fromhex(server_seed_hex) + bytes.fromhex(block_hash_hex) + bytes.fromhex(participants_hash_hex) - ).digest() - return int.from_bytes(digest, "big") - - -def draw_index(seed: int, participant_count: int) -> int: - """The winner's `draw_position`: seed modulo the number of participants. Every - participant holds exactly one position, so odds are equal whatever the amount.""" - if participant_count <= 0: - raise ValueError("no participants to draw from") - return seed % participant_count - - -def draw_winner(participants: list[str], server_seed_hex: str, block_hash_hex: str, participants_hash_hex: str) -> str: - """The v1 draw algorithm (docs/ciclo-di-vita-del-round.md RND-17), recomputable by anyone - from the public proof (GET /rounds/{id}/proof): `participants` are the entries in - `draw_position` order, the winner is the one at `draw_index(draw_seed(...), n)`. Deliberately - simple and replaceable.""" - if not participants: - raise ValueError("no participants to draw from") - seed = draw_seed(server_seed_hex, block_hash_hex, participants_hash_hex) - return participants[draw_index(seed, len(participants))] +# The draw primitives live in `plm_engine.draw` (shared with the Django site); re-exported here so the +# old modules and their tests keep working until the old backend is removed (roadmap D1). +from plm_engine.draw import ( # noqa: E402,F401 + draw_index, + draw_seed, + draw_winner, + new_server_seed, + participants_hash, + server_seed_commitment, + sha256_hex, +) diff --git a/apps/lottery/addresses.py b/apps/lottery/addresses.py new file mode 100644 index 0000000..1a07dab --- /dev/null +++ b/apps/lottery/addresses.py @@ -0,0 +1,11 @@ +"""The address under which a participant appears in the public draw list (RND-14, DAT-65).""" + +from django.conf import settings + +from .simulation import simulated_address + + +def participant_address(user) -> str: + if settings.LEDGER_BACKEND == "simulated": + return simulated_address(user) + raise NotImplementedError("HD addresses arrive with phase B (roadmap B4)") diff --git a/apps/lottery/lifecycle.py b/apps/lottery/lifecycle.py new file mode 100644 index 0000000..7a5447f --- /dev/null +++ b/apps/lottery/lifecycle.py @@ -0,0 +1,236 @@ +"""The life of a round, one step at a time (RND-01 .. RND-36, roadmap A4). + +`tick` is what the worker runs every few seconds. It holds no state: everything it needs is in the +database (the secret, the ordered list with positions, its fingerprint, the draw height), so a round +found in any status after a crash or a restart is simply continued, and a draw that was interrupted +gives the same winner it would have given (RND-36). Each step is one write-locked transaction with its +audit row (ARC-77); a step that fails leaves the round exactly where it was. + + open -> closing -> drawing -> paying_out -> closed + +Rounds never overlap (ADR-22): the next one opens only when the previous is closed, its cooldown has +elapsed, and the lottery is not paused after the round in progress (ADR-57). +""" + +import logging +from datetime import datetime, timedelta + +from django.conf import settings +from django.db import IntegrityError, transaction +from django.utils import timezone +from plm_engine.draw import ( + draw_index, + draw_seed, + new_server_seed, + participants_hash, + server_seed_commitment, +) + +from . import audit +from .addresses import participant_address +from .ledger import Ledger, get_ledger +from .models import LotteryConfig, Participation, Round +from .rules import round_deadline +from .seedbox import decrypt_seed, encrypt_seed +from .simulation import SimulatedChain + +logger = logging.getLogger(__name__) + +WORKER = "worker" +_MAX_STEPS_PER_TICK = 8 + + +# --- opening ----------------------------------------------------------------------------------- + + +def rounds_can_open(config: LotteryConfig) -> bool: + """A real round pays its commission to `fee_address`, so without one it would take bets and only + then discover it cannot be paid (ADR-29). The simulated ledger moves no coins and needs none.""" + if settings.LEDGER_BACKEND == "simulated": + return True + return bool(config.fee_address.strip()) + + +def get_active_round() -> Round | None: + return Round.objects.filter(status__in=Round.ACTIVE_STATUSES).first() + + +def open_new_round_if_needed(now: datetime | None = None) -> Round | None: + """The active round if there is one; otherwise a fresh round, unless the cooldown of the last one has + not elapsed, the lottery is paused after the round in progress, or the instance cannot pay a winner. + The round copies its rules from the configuration *now* and keeps them (DAT-61, ADR-10).""" + now = now or timezone.now() + with transaction.atomic(): + active = get_active_round() + if active is not None: + return active + config = LotteryConfig.get() + if config.pause_after_round or not rounds_can_open(config): + return None + last = Round.objects.filter(status=Round.Status.CLOSED).order_by("-id").first() + if last is not None and last.closed_at is not None: + # The gap the closed round announced is the one honoured, whatever the config says now. + if now < last.closed_at + timedelta(seconds=last.cooldown_seconds): + return None + + seed = new_server_seed() + try: + with transaction.atomic(): + round_ = Round.objects.create( + opened_at=now, + duration_seconds=config.round_duration_seconds, + cooldown_seconds=config.round_cooldown_seconds, + bet_amount_sats=config.bet_amount_sats, + fee_address=config.fee_address.strip(), + max_round_pool_sats=config.max_round_pool_sats, + draw_confirmations=config.draw_confirmations, + 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 + ) + 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, + payload={"server_seed_hash": round_.server_seed_hash, "bet_amount_sats": round_.bet_amount_sats, + "duration_seconds": round_.duration_seconds}) + return round_ + + +# --- one tick ---------------------------------------------------------------------------------- + + +def tick(*, now: datetime | None = None, chain: SimulatedChain | None = None, ledger: Ledger | None = None) -> int: + """Advance the active round as far as it can go right now. Returns the number of steps taken.""" + chain = chain or SimulatedChain() + ledger = ledger or get_ledger() + steps = 0 + for _ in range(_MAX_STEPS_PER_TICK): + if not _step(now or timezone.now(), chain, ledger): # a fixed `now` is for tests; otherwise time moves on + break + steps += 1 + return steps + + +def _step(now: datetime, chain, ledger: Ledger) -> bool: + round_ = get_active_round() + if round_ is None: + return open_new_round_if_needed(now) is not None + if round_.status == Round.Status.OPEN: + return _close_betting(round_, now) + if round_.status == Round.Status.CLOSING: + return _close_and_draw(round_, chain, now) + if round_.status == Round.Status.DRAWING: + return _complete_draw(round_, chain, now) + return _pay_out(round_, ledger, now) + + +def _close_betting(round_: Round, now: datetime) -> bool: + """The deadline passed: from here on no bet is accepted, whatever the wait for in-flight bets takes.""" + if now < round_deadline(round_): + return False + with transaction.atomic(): + fresh = Round.objects.get(pk=round_.pk) + if fresh.status != Round.Status.OPEN: + return False + fresh.status = Round.Status.CLOSING + fresh.save(update_fields=["status"]) + return True + + +def _close_and_draw(round_: Round, chain, now: datetime) -> bool: + """Once no bet is in flight: close the round if nobody took part, otherwise commit to the draw — fix the + list, its fingerprint and the height, and enter `drawing` — all in one transaction (RND-13, RND-14).""" + with transaction.atomic(): + fresh = Round.objects.get(pk=round_.pk) + if fresh.status != Round.Status.CLOSING: + return False + # "Yellow light": wait for every bet already placed to confirm, so none is lost at the boundary. + if Participation.objects.filter(round=fresh, status=Participation.Status.PENDING).exists(): + return False + # The draw order is the bet txid, ascending: public data with no ties, which anyone can check + # (RND-14); never a server-side timestamp. + participants = list( + Participation.objects.filter(round=fresh, status=Participation.Status.CONFIRMED) + .select_related("user").order_by("bet_txid") + ) + if not participants: + fresh.status, fresh.closed_at = Round.Status.CLOSED, now + fresh.server_seed = decrypt_seed(fresh.server_seed_enc) # nothing drawn: nothing left to protect + fresh.save(update_fields=["status", "closed_at", "server_seed"]) + audit.record("round_closed", actor_label=WORKER, subject_type="round", subject_id=fresh.pk, + payload={"participants": 0}) + return True + + tip = chain.tip_height(now) + for position, participant in enumerate(participants): + participant.draw_position = position + participant.save(update_fields=["draw_position"]) + fresh.participants_hash = participants_hash( + [(p.bet_txid, p.bet_vout, participant_address(p.user)) for p in participants] + ) + fresh.draw_height = tip + 1 # a block that did not exist when the list was fixed (RND-19) + fresh.pool_amount_sats = sum(p.bet_amount_sats for p in participants) + fresh.status, fresh.drawing_started_at = Round.Status.DRAWING, now + fresh.save(update_fields=["participants_hash", "draw_height", "pool_amount_sats", "status", "drawing_started_at"]) + audit.record("draw_committed", actor_label=WORKER, subject_type="round", subject_id=fresh.pk, + payload={"participants_hash": fresh.participants_hash, "draw_height": fresh.draw_height, + "participants": len(participants), "server_seed_hash": fresh.server_seed_hash}) + return True + + +def _complete_draw(round_: Round, chain, now: datetime) -> bool: + """The draw of a round in `drawing`, from nothing but what the database holds (RND-36): wait for the block at + `draw_height` to have its confirmations and to exist, compute the winner and reveal the secret in the same + transaction that stores it.""" + required_tip = round_.draw_height + round_.draw_confirmations - 1 + if chain.tip_height(now) < required_tip: + return False + block_hash = chain.agreed_block_hash(round_.draw_height, now) + if block_hash is None: + return False # asked again at the next tick — never another block (RND-16) + + with transaction.atomic(): + fresh = Round.objects.get(pk=round_.pk) + if fresh.status != Round.Status.DRAWING or fresh.winner_id is not None: + return False + server_seed = decrypt_seed(fresh.server_seed_enc) + if server_seed_commitment(server_seed) != fresh.server_seed_hash: + raise RuntimeError(f"round {fresh.pk}: the stored secret does not match its published commitment") + participants = list( + Participation.objects.filter(round=fresh, draw_position__isnull=False) + .select_related("user").order_by("draw_position") + ) + rows = [(p.bet_txid, p.bet_vout, participant_address(p.user)) for p in participants] + if participants_hash(rows) != fresh.participants_hash: + raise RuntimeError(f"round {fresh.pk}: the draw list no longer matches its published fingerprint") + + seed = draw_seed(server_seed, block_hash, fresh.participants_hash) + winner = participants[draw_index(seed, len(participants))] + fresh.draw_block_hash, fresh.winner = block_hash, winner.user + fresh.server_seed = server_seed # the reveal, in the same transaction as the winner (RND-18) + fresh.status = Round.Status.PAYING_OUT + fresh.save(update_fields=["draw_block_hash", "winner", "server_seed", "status"]) + audit.record("winner_drawn", actor_label=WORKER, subject_type="round", subject_id=fresh.pk, + payload={"draw_height": fresh.draw_height, "block_hash": block_hash, + "participants": len(participants), "participants_hash": fresh.participants_hash, + "server_seed": server_seed, "seed": f"{seed:064x}", + "winner_position": winner.draw_position}) + return True + + +def _pay_out(round_: Round, ledger: Ledger, now: datetime) -> bool: + """Create the payout once (idempotent), and close the round when it has confirmed.""" + changed = False + if round_.payout_transaction_id is None: + ledger.pay_winner(round_.pk) + changed = True + round_.refresh_from_db() + with transaction.atomic(): + fresh = Round.objects.select_related("payout_transaction").get(pk=round_.pk) + if fresh.status != Round.Status.PAYING_OUT or fresh.payout_transaction.status != "confirmed": + return changed + fresh.status, fresh.closed_at = Round.Status.CLOSED, now + fresh.save(update_fields=["status", "closed_at"]) + audit.record("round_closed", actor_label=WORKER, subject_type="round", subject_id=fresh.pk, + payload={"participants": fresh.participations.filter(status="confirmed").count(), + "pool_amount_sats": fresh.pool_amount_sats}) + return True diff --git a/apps/lottery/management/commands/run_worker.py b/apps/lottery/management/commands/run_worker.py index cd6db60..b7219cf 100644 --- a/apps/lottery/management/commands/run_worker.py +++ b/apps/lottery/management/commands/run_worker.py @@ -1,7 +1,7 @@ -"""The background worker process (ADR-55). - -A1 ships the process shell only: it starts, logs, stops cleanly on SIGTERM and shows up as a -compose service. The round scheduler (A4) and the chain tasks (Phase B) plug into `tick`. +"""The background worker process (ADR-55): runs the round lifecycle every few seconds and, on the +simulated ledger, settles the confirmations that a real chain would bring (roadmap A4). The chain tasks +of phase B plug into `tick` too. A step that fails is logged and retried at the next tick: the lifecycle +keeps no state outside the database. """ import logging @@ -16,7 +16,14 @@ TICK_SECONDS = 5 def tick() -> None: - """One pass over everything the worker is responsible for. Empty until A4.""" + """One pass over everything the worker is responsible for.""" + from django.conf import settings + + from apps.lottery import lifecycle, simulation + + if settings.LEDGER_BACKEND == "simulated": + simulation.settle() + lifecycle.tick() class Command(BaseCommand): @@ -32,7 +39,12 @@ class Command(BaseCommand): logger.info("worker started") while not stop.is_set(): - tick() + try: + tick() + except Exception: # a failed step leaves the round where it was; the next tick retries + logger.exception("worker tick failed") + if options["once"]: + raise if options["once"]: break stop.wait(TICK_SECONDS) diff --git a/apps/lottery/seedbox.py b/apps/lottery/seedbox.py new file mode 100644 index 0000000..fba81f8 --- /dev/null +++ b/apps/lottery/seedbox.py @@ -0,0 +1,28 @@ +"""A round's secret, encrypted at rest (DAT-64, RND-34). + +The plaintext secret is written to the database only at the reveal; until then a copy of the database +alone must not tell who will win. Fernet with a key derived from `DJANGO_SECRET_KEY`. When the master +key file returns for the real engine (roadmap B4) this is where it plugs in. +""" + +import base64 +import hashlib + +from cryptography.fernet import Fernet, InvalidToken +from django.conf import settings + + +def _fernet() -> Fernet: + key = hashlib.sha256(b"plm-lottery/round-seed/" + settings.SECRET_KEY.encode()).digest() + return Fernet(base64.urlsafe_b64encode(key)) + + +def encrypt_seed(seed_hex: str) -> str: + return _fernet().encrypt(seed_hex.encode()).decode() + + +def decrypt_seed(token: str) -> str: + try: + return _fernet().decrypt(token.encode()).decode() + except InvalidToken as exc: + raise RuntimeError("the round secret cannot be decrypted with this key") from exc diff --git a/apps/lottery/simulation.py b/apps/lottery/simulation.py new file mode 100644 index 0000000..455cb26 --- /dev/null +++ b/apps/lottery/simulation.py @@ -0,0 +1,70 @@ +"""The simulated chain and its confirmations (ADR-59, roadmap A4). + +A chain that exists only in time: block `h` is the one produced `h` block-intervals after a fixed epoch, +and its hash is a pure function of `h`. Nothing is stored, so a restart changes nothing. Bets, deposits and +payouts of the simulated ledger confirm a few seconds after they are made (`settle`). +""" + +import hashlib +from datetime import datetime, timedelta, timezone + +from django.conf import settings +from django.utils import timezone as dj_timezone + +from .models import ChainTransaction, Movement, Participation, Round + +EPOCH = datetime(2026, 1, 1, tzinfo=timezone.utc) +BASE_HEIGHT = 1000 + + +def simulated_block_hash(height: int) -> str: + return hashlib.sha256(f"simulated-block:{height}".encode()).hexdigest() + + +class SimulatedChain: + """What the round engine asks of a chain: where the tip is, and the hash of a block at a height.""" + + def tip_height(self, now: datetime | None = None) -> int: + now = now or dj_timezone.now() + return BASE_HEIGHT + int((now - EPOCH).total_seconds() // settings.SIMULATED_BLOCK_SECONDS) + + def agreed_block_hash(self, height: int, now: datetime | None = None) -> str | None: + """The hash of the block at exactly `height`, or None while it does not exist yet (RND-16).""" + if height > self.tip_height(now): + return None + return simulated_block_hash(height) + + +def settle(now: datetime | None = None) -> int: + """Confirm what has been waiting long enough. Returns how many operations were confirmed.""" + from .ledger import SimulatedLedger + + now = now or dj_timezone.now() + cutoff = now - timedelta(seconds=settings.SIMULATED_CONFIRM_SECONDS) + ledger, confirmed = SimulatedLedger(), 0 + + for movement in Movement.objects.filter( + kind=Movement.Kind.DEPOSIT, status=Movement.Status.PENDING, created_at__lte=cutoff + ): + ledger.confirm_deposit(movement) + confirmed += 1 + for chain_tx in ChainTransaction.objects.filter( + status=ChainTransaction.Status.PENDING, broadcast_at__lte=cutoff + ): + if chain_tx.kind == ChainTransaction.Kind.BET: + participation = Participation.objects.filter(bet_txid=chain_tx.current_txid).first() + if participation is not None: + ledger.confirm_bet(participation) + confirmed += 1 + elif chain_tx.kind == ChainTransaction.Kind.PAYOUT: + round_ = Round.objects.filter(payout_transaction=chain_tx).first() + if round_ is not None: + ledger.confirm_payout(round_.pk) + confirmed += 1 + return confirmed + + +def simulated_address(user) -> str: + """A stable, pseudonymous address for a participant in the public proof (WEB-12): derived from the + account id, it reveals no username. The real HD address replaces it in phase B (roadmap B4).""" + return "rplm1sim" + hashlib.sha256(f"simulated-address:{user.pk}".encode()).hexdigest()[:32] diff --git a/config/settings.py b/config/settings.py index f71294b..5c977ae 100644 --- a/config/settings.py +++ b/config/settings.py @@ -154,3 +154,8 @@ 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)") + +# The simulated chain (ADR-59): a block every N seconds and a confirmation after M, so a whole round +# runs in a few minutes on localhost. Real chains ignore both. +SIMULATED_BLOCK_SECONDS = int(os.environ.get("SIMULATED_BLOCK_SECONDS", "20")) +SIMULATED_CONFIRM_SECONDS = int(os.environ.get("SIMULATED_CONFIRM_SECONDS", "5")) diff --git a/docs/ciclo-di-vita-del-round.md b/docs/ciclo-di-vita-del-round.md index 1b026f2..e788950 100644 --- a/docs/ciclo-di-vita-del-round.md +++ b/docs/ciclo-di-vita-del-round.md @@ -585,3 +585,49 @@ Due livelli indipendenti: - ~~[RND-32]~~ Assorbito da [RND-36]: nel comportamento atteso un round in `drawing` riprende da solo dopo un riavvio o un errore (B-81). + +## Il ciclo nel sito Django (migrazione in corso) + +Il worker del nuovo sito ([ADR-55](adr/ADR-55-sqlite-wal-web-worker-processi-separati.md)) porta in `apps/lottery/lifecycle.py` +la stessa macchina a stati e le stesse regole di sopra, sul modello Django ([DAT-78]); finché il vecchio scheduler non +è rimosso (roadmap D1) il resto del documento resta lo stato storico. In particolare valgono, con questo codice: +apertura con parametri copiati ([RND-05], [DAT-61]), un solo round attivo ([RND-02]), scadenza propria del round +([RND-11], [ADR-23](adr/ADR-23-limite-scommettere-scadenza-round-stesso-suo.md)), attesa delle puntate in volo ([RND-13]), +elenco ordinato per txid con impronta e altezza fissati in una transazione ([RND-14], [RND-19], [DAT-65]), attesa delle +conferme del blocco e blocco mai sostituito ([RND-15], [RND-16]), vincitore ricalcolabile e rivelazione del segreto con +il vincitore ([RND-17], [RND-18]), ripresa dopo un errore con lo stesso vincitore ([RND-36]), pagamento 70/30 ([RND-21]) +e pausa che ferma solo il round successivo ([ADR-57](adr/ADR-57-due-pause-distinte-dopo-round-e-incidente.md)). +*Codice:* `apps/lottery/lifecycle.py` · *Test:* `tests/django/test_lifecycle.py`. Aggiunte e differenze: + +- **[RND-41]** **Un passo alla volta, senza stato in memoria.** `lifecycle.tick` esegue i passi che il round può fare + adesso (al massimo 8 per chiamata) e si ferma; ogni passo è una transazione con blocco di scrittura e la sua riga di + audit ([ARC-77]), e rilegge il round dentro la transazione. Un passo che fallisce lascia il round dov'era; il tick + successivo lo riprende da quello che il database contiene. Un tick che non cambia nulla non scrive nulla. + *Stato:* implementato (A4) · + *Codice:* `apps/lottery/lifecycle.py:tick` · + *Test:* `tests/django/test_lifecycle.py::test_an_interrupted_draw_gives_the_same_winner`, `test_a_tick_that_changes_nothing_writes_nothing` +- **[RND-42]** **Catena e conferme simulate.** Con `LEDGER_BACKEND=simulated` la catena esiste solo nel tempo: il blocco `h` + è prodotto `h` intervalli (`SIMULATED_BLOCK_SECONDS`, 20 s) dopo un'epoca fissa e il suo hash è una funzione di `h`; + non si memorizza nulla, quindi un riavvio non cambia niente. Una puntata, un deposito o un pagamento simulati si + confermano `SIMULATED_CONFIRM_SECONDS` (5 s) dopo l'invio. Il blocco di estrazione resta quello dell'altezza + fissata, mai un altro; un'altezza futura non ha hash ([RND-16]). Il worker esegue `settle` e `tick` a ogni giro. + *Stato:* implementato (A4); la catena reale con la Fase B · + *Codice:* `apps/lottery/simulation.py`, `apps/lottery/management/commands/run_worker.py` · + *Test:* `tests/django/test_lifecycle.py::test_a_whole_round_on_the_simulated_chain`, `test_settling_confirms_only_what_has_waited_long_enough` +- **[RND-43]** **Il segreto del round è cifrato a riposo.** Alla pubblicazione dell'impegno ([RND-34]) il segreto si + salva cifrato (Fernet, chiave derivata da `DJANGO_SECRET_KEY`); la colonna in chiaro resta vuota fino alla + rivelazione, quindi una copia del solo database non dice chi vincerà. Con un'altra chiave il segreto non si decifra. + *Stato:* implementato (A4); la chiave dedicata torna con la Fase B · + *Codice:* `apps/lottery/seedbox.py` · + *Test:* `tests/django/test_lifecycle.py::test_the_round_secret_needs_the_right_key` +- **[RND-44]** **La prova non espone gli account.** L'elenco di estrazione e la sua impronta contengono, per ogni + partecipante, il txid e l'uscita della sua scommessa e un indirizzo pseudonimo ([ADR-59](adr/ADR-59-motore-plm-pacchetto-senza-framework-ledger-simulato.md)): + nel pilota derivato dall'id dell'account senza rivelarlo, in Fase B l'indirizzo HD. Nessun username compare. + *Stato:* implementato (A4) · + *Codice:* `apps/lottery/addresses.py`, `apps/lottery/simulation.py:simulated_address` · + *Test:* `tests/django/test_lifecycle.py::test_the_proof_does_not_expose_usernames` +- **Differenze rispetto al vecchio scheduler.** `closed_at` è l'istante in cui il round si chiude del tutto (pagamento + confermato, o chiusura senza partecipanti) e da lì parte la pausa fra round; non si scrive all'ingresso in `closing`. + Gli eventi di stallo dell'estrazione (`draw_stalled`, `draw_baseline_tip_unknown`, `draw_header_corroboration_failed`) e + la verifica del montepremi sulla catena riguardano la catena reale e arrivano con la Fase B (B8). Senza `fee_address` + un round non si apre solo con il ledger reale ([ADR-29](adr/ADR-29-senza-fee-address-apre-nessun-round.md)). diff --git a/plm_engine/__init__.py b/plm_engine/__init__.py new file mode 100644 index 0000000..97aa10c --- /dev/null +++ b/plm_engine/__init__.py @@ -0,0 +1 @@ +"""PLM engine: framework-free building blocks (ADR-59).""" diff --git a/plm_engine/draw.py b/plm_engine/draw.py new file mode 100644 index 0000000..5eabbba --- /dev/null +++ b/plm_engine/draw.py @@ -0,0 +1,65 @@ +"""The draw's pure primitives: no database, no framework (ADR-59, roadmap B1). + +Commit-reveal (RND-14 .. RND-20): the round's secret is committed to (`server_seed_commitment`) +when it opens, the ordered list of participants is fixed and fingerprinted (`participants_hash`), +and the winner is `draw_index(draw_seed(secret, block_hash, participants_hash), n)` — a value +anyone can recompute from the public proof once the secret is revealed. +""" + +import hashlib +import secrets + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def new_server_seed() -> str: + """B-73 (RND-34, DAT-64): a round's secret — 32 random bytes from the OS CSPRNG, as + 64 lowercase hex characters.""" + return secrets.token_bytes(32).hex() + + +def server_seed_commitment(server_seed_hex: str) -> str: + """`server_seed_hash`: sha256 of the secret's 32 bytes, published from the opening of + the round so the operator cannot change the secret afterwards (RND-34).""" + return sha256_hex(bytes.fromhex(server_seed_hex)) + + +def participants_hash(rows: list[tuple[str, int, str]]) -> str: + """The fingerprint of the ordered draw list (RND-14): sha256 of one `txid:vout:address` + line per participant, in `draw_position` order, each line ending in `\n`, UTF-8. `txid` + is the bet transaction's, lowercase hex as explorers show it; `vout` is the output paying + the round's pool address, in decimal; `address` is the participant's own.""" + text = "".join(f"{txid}:{vout}:{address}\n" for txid, vout, address in rows) + return sha256_hex(text.encode("utf-8")) + + +def draw_seed(server_seed_hex: str, block_hash_hex: str, participants_hash_hex: str) -> int: + """RND-17: sha256 of the secret (32 bytes), the hash of the block at `draw_height` (32 + bytes, in the order explorers show it) and `participants_hash` (32 bytes), read as an + unsigned big-endian integer. Nobody who lacks the secret can predict it, and the + operator, who knows the secret, cannot know the block when committing to the list.""" + digest = hashlib.sha256( + bytes.fromhex(server_seed_hex) + bytes.fromhex(block_hash_hex) + bytes.fromhex(participants_hash_hex) + ).digest() + return int.from_bytes(digest, "big") + + +def draw_index(seed: int, participant_count: int) -> int: + """The winner's `draw_position`: seed modulo the number of participants. Every + participant holds exactly one position, so odds are equal whatever the amount.""" + if participant_count <= 0: + raise ValueError("no participants to draw from") + return seed % participant_count + + +def draw_winner(participants: list[str], server_seed_hex: str, block_hash_hex: str, participants_hash_hex: str) -> str: + """The v1 draw algorithm (docs/ciclo-di-vita-del-round.md RND-17), recomputable by anyone + from the public proof (GET /rounds/{id}/proof): `participants` are the entries in + `draw_position` order, the winner is the one at `draw_index(draw_seed(...), n)`. Deliberately + simple and replaceable.""" + if not participants: + raise ValueError("no participants to draw from") + seed = draw_seed(server_seed_hex, block_hash_hex, participants_hash_hex) + return participants[draw_index(seed, len(participants))] diff --git a/pyproject.toml b/pyproject.toml index 75a2773..e9cbfed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,4 +33,4 @@ testpaths = ["tests"] DJANGO_SETTINGS_MODULE = "config.settings_test" [tool.setuptools.packages.find] -include = ["app*", "config*", "apps*"] +include = ["app*", "config*", "apps*", "plm_engine*"] diff --git a/roadmap.md b/roadmap.md index 0001fe0..5f2d872 100644 --- a/roadmap.md +++ b/roadmap.md @@ -27,7 +27,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. - [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. +- [x] **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. - [ ] **A7 · Area giocatore.** `/app/` (puntata con conferma esplicita), `/app/portafoglio/` (saldo spendibile e in conferma, deposito simulato **solo fuori da mainnet**), `/app/movimenti/`. *Requisiti:* WEB-03, WEB-20, WEB-21, WEB-22. *Test:* isolamento tra utenti (404 su dati altrui), stato salvato dopo ricarica. @@ -39,7 +39,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore Uscita: flusso completo su regtest; un riavvio durante il broadcast, due richieste concorrenti e una riorganizzazione simulata lasciano dati e fondi riconciliabili. -- [ ] **B1 · Pacchetto `plm_engine`.** Spostamento dei moduli senza database (derivazione HD, `psbt_builder`, client Electrum, `merkle`, `draw`) e dei loro test, senza cambiare il comportamento. *Requisiti:* ADR-59. *Test:* i test esistenti dei moduli passano invariati. +- [ ] **B1 · Pacchetto `plm_engine`** (le primitive dell'estrazione sono già state spostate in A4). Spostamento dei moduli senza database (derivazione HD, `psbt_builder`, client Electrum, `merkle`, `draw`) e dei loro test, senza cambiare il comportamento. *Requisiti:* ADR-59. *Test:* i test esistenti dei moduli passano invariati. - [ ] **B2 · Profilo di rete.** `PLM_NETWORK=regtest|mainnet` (hrp, prefissi, genesis, powLimit), conferma esplicita per `mainnet`, validazione degli indirizzi con l'hrp del profilo. *Requisiti:* ADR-58, ELC-30. *Test:* indirizzi e genesis per ciascun profilo. - [ ] **B3 · Ambiente regtest e fixture.** Compose con nodo e Fulcrum regtest (profilo `regtest`), script che genera blocchi e fondi, fixture di integrazione che si salta se il regtest non c'è. *Test:* smoke di connessione e generazione di un blocco. - [ ] **B4 · Modelli di catena.** UTXO, transazioni con tutte le versioni TXID, depositi, assegnazione dell'indice HD; la chiave di firma è accessibile solo al processo worker. *Requisiti:* DAT, TX. *Test:* vincoli, derivazione identica a parità di input. diff --git a/tests/django/test_lifecycle.py b/tests/django/test_lifecycle.py new file mode 100644 index 0000000..8b339a3 --- /dev/null +++ b/tests/django/test_lifecycle.py @@ -0,0 +1,475 @@ +"""A4 — round lifecycle, commit-reveal draw and simulated chain: RND-13..RND-21, RND-33..RND-36, ADR-22, +ADR-23, ADR-24, ADR-29, ADR-57, ADR-59, DAT-61, DAT-64, DAT-65.""" + +import hashlib +from datetime import timedelta +from uuid import uuid4 + +import pytest +from django.contrib.auth import get_user_model +from django.utils import timezone +from plm_engine.draw import draw_index, draw_seed, participants_hash, server_seed_commitment + +from apps.lottery import audit, lifecycle, simulation +from apps.lottery.addresses import participant_address +from apps.lottery.balances import balance_of +from apps.lottery.ledger import SimulatedLedger +from apps.lottery.models import AuditEntry, LotteryConfig, Movement, Participation, Round +from apps.lottery.seedbox import decrypt_seed, encrypt_seed +from apps.lottery.simulation import SimulatedChain, simulated_block_hash + +PLM = 100_000_000 +BET = 10 * PLM + +pytestmark = pytest.mark.django_db +ledger = SimulatedLedger() + + +class FakeChain: + """A chain the test drives by hand.""" + + def __init__(self, tip=1000): + self.tip, self.agree, self.hashes = tip, True, {} + + def tip_height(self, now=None): + return self.tip + + def agreed_block_hash(self, height, now=None): + if not self.agree or height > self.tip: + return None + return self.hashes.get(height, "ab" * 32) + + +def make_user(name): + return get_user_model().objects.create_user(name, password="x" * 12) + + +def players(round_, names, *, confirm=True): + """Fund each player and place their bet; optionally confirm it.""" + users = [] + for name in names: + user = make_user(name) + ledger.deposit(user, round_.bet_amount_sats) + bet = ledger.place_bet(user, round_.pk, request_id=uuid4()).obj + if confirm: + ledger.confirm_bet(bet) + users.append(user) + return users + + +def actions(): + return list(AuditEntry.objects.order_by("id").values_list("action", flat=True)) + + +@pytest.fixture +def t0(): + return timezone.now() + + +def deadline(round_): + return round_.opened_at + timedelta(seconds=round_.duration_seconds) + + +# --- opening ----------------------------------------------------------------------------------- + + +def test_the_first_tick_opens_a_round_with_a_public_commitment(t0): + """RND-34: the hash of the secret is public from the opening; the secret is not.""" + round_ = lifecycle.open_new_round_if_needed(t0) + assert round_.status == "open" and round_.opened_at == t0 + assert len(round_.server_seed_hash) == 64 and round_.server_seed is None + secret = decrypt_seed(round_.server_seed_enc) + assert server_seed_commitment(secret) == round_.server_seed_hash + assert secret not in round_.server_seed_enc + assert actions() == ["round_opened"] + + +def test_only_one_round_is_ever_open(t0): + first = lifecycle.open_new_round_if_needed(t0) + assert lifecycle.open_new_round_if_needed(t0).pk == first.pk + assert Round.objects.count() == 1 + + +def test_a_round_copies_its_rules_when_it_opens(t0): + """DAT-61, ADR-10: a later edit of the configuration applies from the next round.""" + config = LotteryConfig.get() + config.bet_amount_sats, config.round_duration_seconds, config.max_round_pool_sats = 7 * PLM, 90, 100 * PLM + config.draw_confirmations, config.round_cooldown_seconds, config.fee_address = 5, 11, " rplm1fee " + config.save() + round_ = lifecycle.open_new_round_if_needed(t0) + config.bet_amount_sats, config.round_duration_seconds = 99 * PLM, 5 + config.save() + round_.refresh_from_db() + assert (round_.bet_amount_sats, round_.duration_seconds, round_.max_round_pool_sats) == (7 * PLM, 90, 100 * PLM) + assert (round_.draw_confirmations, round_.cooldown_seconds, round_.fee_address) == (5, 11, "rplm1fee") + + +def test_a_real_ledger_needs_a_fee_address_to_open_a_round(settings, t0): + """ADR-29: a round that cannot pay its commission is not opened. The simulated ledger needs none.""" + assert lifecycle.rounds_can_open(LotteryConfig.get()) + settings.LEDGER_BACKEND = "chain" + assert lifecycle.open_new_round_if_needed(t0) is None + config = LotteryConfig.get() + config.fee_address = "rplm1fee" + config.save() + assert lifecycle.open_new_round_if_needed(t0) is not None + + +def test_the_pause_after_the_round_stops_only_the_next_one(t0): + """ADR-57: «Pausa dopo il round in corso».""" + config = LotteryConfig.get() + config.pause_after_round = True + config.save() + assert lifecycle.open_new_round_if_needed(t0) is None and Round.objects.count() == 0 + + +# --- the betting window ------------------------------------------------------------------------ + + +def test_the_round_closes_for_bets_at_its_own_deadline(t0): + """ADR-23.""" + round_ = lifecycle.open_new_round_if_needed(t0) + assert lifecycle.tick(now=deadline(round_) - timedelta(seconds=1), chain=FakeChain()) == 0 + assert Round.objects.get().status == "open" + lifecycle.tick(now=deadline(round_), chain=FakeChain()) + assert Round.objects.get().status in ("closing", "closed") + + +def test_the_deadline_is_the_rounds_own_not_the_live_config(t0): + round_ = lifecycle.open_new_round_if_needed(t0) + config = LotteryConfig.get() + config.round_duration_seconds = 1 + config.save() + lifecycle.tick(now=t0 + timedelta(seconds=30), chain=FakeChain()) + assert Round.objects.get(pk=round_.pk).status == "open" + + +def test_closing_waits_for_every_bet_in_flight(t0): + """RND-13: a bet placed before the deadline is not lost because it confirmed after it.""" + round_ = lifecycle.open_new_round_if_needed(t0) + (user,) = players(round_, ["a"], confirm=False) + at_deadline = deadline(round_) + lifecycle.tick(now=at_deadline, chain=FakeChain()) + assert Round.objects.get().status == "closing" # still waiting: the bet is pending + ledger.confirm_bet(Participation.objects.get()) + lifecycle.tick(now=at_deadline, chain=FakeChain()) + assert Round.objects.get().status == "drawing" + + +def test_a_round_nobody_joined_closes_and_reveals_its_secret(t0): + """DAT-64: with nothing drawn the secret has nothing left to protect.""" + round_ = lifecycle.open_new_round_if_needed(t0) + lifecycle.tick(now=deadline(round_), chain=FakeChain()) + round_.refresh_from_db() + assert round_.status == "closed" and round_.closed_at is not None + assert server_seed_commitment(round_.server_seed) == round_.server_seed_hash + assert actions() == ["round_opened", "round_closed"] + + +# --- committing to the draw -------------------------------------------------------------------- + + +def committed_round(t0, names=("c", "a", "b"), tip=1000, reverse_txids=False): + round_ = lifecycle.open_new_round_if_needed(t0) + users = players(round_, list(names)) + if reverse_txids: # first to bet gets the highest txid, so id order and txid order are opposite + for i, bet in enumerate(Participation.objects.order_by("id")): + Participation.objects.filter(pk=bet.pk).update(bet_txid=f"{len(names) - i:064x}") + chain = FakeChain(tip) + lifecycle.tick(now=deadline(round_), chain=chain) + round_.refresh_from_db() + return round_, users, chain + + +def test_the_list_is_ordered_by_bet_txid_and_fingerprinted(t0): + """RND-14, DAT-65: public data, no ties, never a server-side timestamp.""" + round_, users, _ = committed_round(t0, reverse_txids=True) + assert round_.status == "drawing" + ordered = list(Participation.objects.filter(round=round_).order_by("draw_position").select_related("user")) + assert [p.draw_position for p in ordered] == [0, 1, 2] + assert [p.bet_txid for p in ordered] == sorted(p.bet_txid for p in ordered) + assert [p.user.username for p in ordered] == ["b", "a", "c"] # last to bet, first in the list + expected = participants_hash([(p.bet_txid, p.bet_vout, participant_address(p.user)) for p in ordered]) + assert round_.participants_hash == expected + assert round_.pool_amount_sats == 3 * BET + + +def test_the_draw_block_is_after_the_close(t0): + """RND-19: `draw_height` is the height known at closing plus one — a block that did not exist yet.""" + round_, _, _ = committed_round(t0, tip=1234) + assert round_.draw_height == 1235 + audit_row = AuditEntry.objects.get(action="draw_committed") + assert audit_row.payload["draw_height"] == 1235 and audit_row.payload["participants"] == 3 + + +def test_the_proof_does_not_expose_usernames(t0): + """WEB-12: participants appear under a pseudonymous address only.""" + round_, users, _ = committed_round(t0, names=("mariorossi", "lucia")) + for user in users: + assert user.username not in participant_address(user) + assert participant_address(user) == participant_address(user) # stable: the same player, the same entry + assert len({participant_address(u) for u in users}) == len(users) + published = AuditEntry.objects.get(action="draw_committed").payload + assert "mariorossi" not in str(published) and "lucia" not in str(published) + + +# --- the draw ---------------------------------------------------------------------------------- + + +def test_the_draw_waits_for_the_confirmations_of_the_block(t0): + """RND-15: the chain needs `draw_confirmations` blocks from `draw_height`.""" + round_, _, chain = committed_round(t0, tip=1000) # draw_height 1001, 3 confirmations -> tip 1003 + chain.tip = 1002 + lifecycle.tick(now=deadline(round_), chain=chain) + assert Round.objects.get().status == "drawing" + chain.tip = 1003 + lifecycle.tick(now=deadline(round_), chain=chain) + assert Round.objects.get().status in ("paying_out", "closed") + + +def test_a_block_that_is_not_agreed_is_asked_again_never_replaced(t0): + """RND-16: nobody can pick another block to seed the draw; a missing agreement only delays it.""" + round_, _, chain = committed_round(t0) + chain.tip, chain.agree = 1010, False + for _ in range(3): + assert lifecycle.tick(now=deadline(round_), chain=chain) == 0 + assert Round.objects.get().winner_id is None + chain.agree = True + lifecycle.tick(now=deadline(round_), chain=chain) + round_.refresh_from_db() + assert round_.draw_height == 1001 and round_.draw_block_hash == "ab" * 32 # the same block as always + + +def test_the_winner_is_recomputable_from_the_public_proof(t0): + """RND-17, RND-18: anyone can redo the draw once the secret is revealed.""" + round_, users, chain = committed_round(t0) + chain.tip = 1003 + chain.hashes[1001] = "cd" * 32 + lifecycle.tick(now=deadline(round_), chain=chain) + round_.refresh_from_db() + ordered = list(Participation.objects.filter(round=round_).order_by("draw_position")) + seed = draw_seed(round_.server_seed, "cd" * 32, round_.participants_hash) + assert round_.winner_id == ordered[draw_index(seed, len(ordered))].user_id + assert server_seed_commitment(round_.server_seed) == round_.server_seed_hash + assert round_.draw_block_hash == "cd" * 32 and round_.status == "paying_out" + payload = AuditEntry.objects.get(action="winner_drawn").payload + assert payload["server_seed"] == round_.server_seed and payload["block_hash"] == "cd" * 32 + + +def test_the_secret_is_revealed_only_with_the_winner(t0): + """RND-18, DAT-64.""" + round_, _, chain = committed_round(t0) + assert Round.objects.get().server_seed is None # committed, drawing, not yet revealed + chain.tip = 1003 + lifecycle.tick(now=deadline(round_), chain=chain) + round_.refresh_from_db() + assert round_.server_seed and round_.winner_id + + +def test_an_interrupted_draw_gives_the_same_winner(t0, monkeypatch): + """RND-36: a failure mid-draw leaves nothing behind, and the resumed draw picks the same winner.""" + round_, _, chain = committed_round(t0) + chain.tip = 1003 + + def explode(action, **kwargs): + if action == "winner_drawn": + raise RuntimeError("database locked") + return real(action, **kwargs) + + real = audit.record + monkeypatch.setattr(audit, "record", explode) + with pytest.raises(RuntimeError): + lifecycle.tick(now=deadline(round_), chain=chain) + interrupted = Round.objects.get() + assert (interrupted.status, interrupted.winner_id, interrupted.server_seed) == ("drawing", None, None) + + monkeypatch.setattr(audit, "record", real) + lifecycle.tick(now=deadline(round_), chain=chain) + resumed = Round.objects.get() + ordered = list(Participation.objects.filter(round=resumed).order_by("draw_position")) + expected = ordered[draw_index(draw_seed(decrypt_seed(resumed.server_seed_enc), "ab" * 32, + resumed.participants_hash), len(ordered))] + assert resumed.winner_id == expected.user_id + + +def test_a_tampered_list_or_secret_is_refused(t0): + """RND-14, RND-34: the list must match its fingerprint and the secret its commitment.""" + round_, _, chain = committed_round(t0) + chain.tip = 1003 + Round.objects.filter(pk=round_.pk).update(participants_hash="0" * 64) + with pytest.raises(RuntimeError, match="fingerprint"): + lifecycle.tick(now=deadline(round_), chain=chain) + Round.objects.filter(pk=round_.pk).update(participants_hash=round_.participants_hash, server_seed_hash="1" * 64) + with pytest.raises(RuntimeError, match="commitment"): + lifecycle.tick(now=deadline(round_), chain=chain) + assert Round.objects.get().winner_id is None + + +def test_a_tick_that_changes_nothing_writes_nothing(t0): + round_, _, chain = committed_round(t0) + before = AuditEntry.objects.count() + assert lifecycle.tick(now=deadline(round_), chain=chain) == 0 # still waiting for blocks + assert AuditEntry.objects.count() == before + + +# --- payout and cooldown ----------------------------------------------------------------------- + + +def drawn_round(t0, names=("a", "b", "c", "d")): + round_ = lifecycle.open_new_round_if_needed(t0) + users = players(round_, list(names)) + chain = FakeChain(1000) + lifecycle.tick(now=deadline(round_), chain=chain) + chain.tip = 1003 + lifecycle.tick(now=deadline(round_), chain=chain) + round_.refresh_from_db() + return round_, users, chain + + +def test_the_winner_is_paid_70_percent_and_the_round_closes_when_it_confirms(t0): + """RND-21: paying_out until the payout confirms, then closed.""" + round_, users, chain = drawn_round(t0) + assert round_.status == "paying_out" and round_.payout_transaction_id is not None + assert (round_.winner_amount_sats, round_.fee_amount_sats) == (28 * PLM, 12 * PLM) + win = Movement.objects.get(kind="win") + assert win.user_id == round_.winner_id and win.status == "pending" + assert balance_of(round_.winner).incoming_sats == 28 * PLM + assert Round.objects.get().status == "paying_out" + + done = deadline(round_) + timedelta(minutes=5) + simulation.settle(done) + lifecycle.tick(now=done, chain=chain) + round_.refresh_from_db() + assert round_.status == "closed" and round_.closed_at == done + assert balance_of(round_.winner).spendable_sats == 28 * PLM and balance_of(round_.winner).incoming_sats == 0 + + +def test_the_next_round_opens_only_after_the_cooldown_it_announced(t0): + """B-61: the gap of the closed round is the gap honoured, whatever the config says now.""" + round_, _, chain = drawn_round(t0) + done = deadline(round_) + timedelta(minutes=5) + simulation.settle(done) + lifecycle.tick(now=done, chain=chain) + assert Round.objects.get().status == "closed" + config = LotteryConfig.get() + config.round_cooldown_seconds = 1 + config.save() + lifecycle.tick(now=done + timedelta(seconds=29), chain=chain) + assert Round.objects.count() == 1 + lifecycle.tick(now=done + timedelta(seconds=30), chain=chain) + assert Round.objects.count() == 2 and Round.objects.latest("id").status == "open" + + +def test_a_round_in_progress_finishes_even_if_the_lottery_is_paused(t0): + """ADR-57: the pause after the round lets the current one close, draw and pay; no new one opens.""" + round_ = lifecycle.open_new_round_if_needed(t0) + players(round_, ["a", "b"]) + config = LotteryConfig.get() + config.pause_after_round = True + config.save() + chain = FakeChain(1000) + lifecycle.tick(now=deadline(round_), chain=chain) + chain.tip = 1003 + lifecycle.tick(now=deadline(round_), chain=chain) + done = deadline(round_) + timedelta(minutes=5) + simulation.settle(done) + lifecycle.tick(now=done, chain=chain) + assert Round.objects.get().status == "closed" + lifecycle.tick(now=done + timedelta(hours=1), chain=chain) + assert Round.objects.count() == 1 # still paused + config.pause_after_round = False + config.save() + lifecycle.tick(now=done + timedelta(hours=1), chain=chain) + assert Round.objects.count() == 2 + + +# --- the whole thing, on the simulated chain --------------------------------------------------- + + +def test_a_whole_round_on_the_simulated_chain(settings, t0): + """The first milestone: open -> bets -> close -> draw -> payout -> closed, money conserved, audit in order.""" + settings.SIMULATED_BLOCK_SECONDS, settings.SIMULATED_CONFIRM_SECONDS = 10, 2 + chain = SimulatedChain() + lifecycle.tick(now=t0, chain=chain) + round_ = Round.objects.get() + users = players(round_, ["a", "b", "c"], confirm=False) + + now = t0 + for _ in range(400): # 400 steps of 5 simulated seconds: far more than a round needs + now += timedelta(seconds=5) + simulation.settle(now) + lifecycle.tick(now=now, chain=chain) + if Round.objects.filter(status="open").exclude(pk=round_.pk).exists(): + break + round_.refresh_from_db() + assert round_.status == "closed" + assert Round.objects.filter(status="open").exclude(pk=round_.pk).exists() # the next one opened + + # the winner is exactly what the public proof says + ordered = list(Participation.objects.filter(round=round_).order_by("draw_position")) + seed = draw_seed(round_.server_seed, simulated_block_hash(round_.draw_height), round_.participants_hash) + assert round_.winner_id == ordered[draw_index(seed, 3)].user_id + assert round_.draw_height > simulation.BASE_HEIGHT + + # money: what players deposited is what they hold plus the platform's share + 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 + assert round_.winner_amount_sats == 21 * PLM and round_.fee_amount_sats == 9 * PLM + + interesting = [a for a in actions() if a in ("round_opened", "draw_committed", "winner_drawn", + "payout_created", "payout_confirmed", "round_closed")] + assert interesting == ["round_opened", "draw_committed", "winner_drawn", "payout_created", + "payout_confirmed", "round_closed", "round_opened"] + + +# --- the simulated chain and its confirmations ------------------------------------------------- + + +def test_the_simulated_chain_grows_with_time(settings, t0): + settings.SIMULATED_BLOCK_SECONDS = 20 + chain = SimulatedChain() + later = chain.tip_height(t0 + timedelta(seconds=40)) + assert later - chain.tip_height(t0) in (2,) # a block every 20 simulated seconds + assert chain.tip_height(t0 + timedelta(seconds=19)) - chain.tip_height(t0) in (0, 1) + + +def test_a_future_block_has_no_hash_and_a_past_one_always_the_same(t0): + chain = SimulatedChain() + tip = chain.tip_height(t0) + assert chain.agreed_block_hash(tip + 1, t0) is None + assert chain.agreed_block_hash(tip, t0) == simulated_block_hash(tip) == chain.agreed_block_hash(tip, t0) + assert simulated_block_hash(tip) != simulated_block_hash(tip - 1) + + +def test_settling_confirms_only_what_has_waited_long_enough(settings): + settings.SIMULATED_CONFIRM_SECONDS = 5 + round_ = Round.objects.create() + (user,) = players(round_, ["a"], confirm=False) + pending_deposit = ledger.deposit(make_user("b"), PLM, confirmed=False).obj + now = timezone.now() + assert simulation.settle(now + timedelta(seconds=4)) == 0 + assert Participation.objects.get().status == "pending" + assert simulation.settle(now + timedelta(seconds=6)) == 2 + assert Participation.objects.get().status == "confirmed" + pending_deposit.refresh_from_db() + assert pending_deposit.status == "confirmed" + + +def test_the_round_secret_needs_the_right_key(settings): + token = encrypt_seed("ab" * 32) + assert decrypt_seed(token) == "ab" * 32 + settings.SECRET_KEY = "another-key-" + "y" * 50 + with pytest.raises(RuntimeError): + decrypt_seed(token) + + +def test_the_old_draw_module_and_the_engine_share_one_implementation(): + """ADR-59: the primitives live once, in `plm_engine.draw`; the old module re-exports them.""" + import plm_engine.draw as engine + from app.rounds import draw as old + + for name in ("draw_seed", "draw_index", "draw_winner", "participants_hash", "new_server_seed", + "server_seed_commitment", "sha256_hex"): + assert getattr(old, name) is getattr(engine, name) + assert engine.sha256_hex(b"x") == hashlib.sha256(b"x").hexdigest() diff --git a/tests/django/test_scaffold.py b/tests/django/test_scaffold.py index 7710569..62a3da8 100644 --- a/tests/django/test_scaffold.py +++ b/tests/django/test_scaffold.py @@ -178,9 +178,13 @@ def test_passwords_use_argon2_outside_tests(): # --- ADR-55: the worker is its own process ----------------------------------------------------- +@pytest.mark.django_db def test_worker_runs_one_tick_and_exits(): - """ARC-71: `manage.py run_worker --once` starts, ticks and stops.""" + """ARC-71: `manage.py run_worker --once` starts, ticks (opening the first round) and stops.""" + from apps.lottery.models import Round + call_command("run_worker", "--once") + assert Round.objects.filter(status="open").count() == 1 @pytest.mark.django_db