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>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 13:43:09 +01:00
1 parent eded058dbb
commit 1d4b53d778
17 files changed
+978 -67

No files matched your search

+11
View File
@@ -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)")
+236
View File
@@ -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
+18 -6
View File
@@ -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)
+28
View File
@@ -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
+70
View File
@@ -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]