Files
plm-lottery/apps/lottery/lifecycle.py
T
davideandClaude Sonnet 5.5 1d4b53d778 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 <noreply@anthropic.com>
2026-11-16 13:43:09 +01:00

237 lines
12 KiB
Python

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