Files
plm-lottery/apps/lottery/models.py
T
davideandClaude Sonnet 5.5 0eba7bcfe6 A2: lottery models and database constraints (WEB-04, ADR-10, ADR-15, ADR-22, DAT-76..79, AUD-47)
LotteryConfig (single row, parameters and the three pause switches), Round
(single active round, own rules, split within the pool), Participation (one
bet per player and round, unique draw position), Movement (signed ledger,
idempotency key per player), ChainTransaction and an append-only AuditEntry
enforced by the model and by SQLite triggers. Every foreign key is PROTECT.
One test per constraint, each checked to hit the intended constraint.

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

386 lines
18 KiB
Python

"""Lottery data model (roadmap A2, WEB-04, ADR-55, ADR-59).
Rules that must hold whatever the code does are database constraints, not conventions
(ARC-72): the single active round, one bet per player and round, signed non-zero movements,
consistent timestamps and statuses. Every amount is an integer number of minimal units
(satoshi, DAT-01), never a float or a decimal.
Rows that carry money are never deleted: every foreign key is PROTECT (DAT-76).
"""
from django.conf import settings
from django.db import models
from django.db.models import F, Q, Value
from django.utils import timezone
SATS_PER_PLM = 100_000_000
class LotteryConfig(models.Model):
"""The single row of operational parameters, plus the three pause switches (ADR-57).
Parameters are *copied onto each round when it opens* (DAT-61, ADR-10): editing them
here never changes a round in progress.
"""
id = models.PositiveSmallIntegerField(primary_key=True, default=1)
fee_address = models.CharField(max_length=128, blank=True, default="")
bet_amount_sats = models.BigIntegerField(default=10 * SATS_PER_PLM)
round_duration_seconds = models.PositiveIntegerField(default=600)
round_cooldown_seconds = models.PositiveIntegerField(default=30)
draw_confirmations = models.PositiveSmallIntegerField(default=3)
max_round_pool_sats = models.BigIntegerField(default=0) # 0 = no cap
# ADR-57: three distinct commands.
pause_after_round = models.BooleanField(default=False)
new_bets_suspended = models.BooleanField(default=False)
withdrawals_suspended = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
constraints = [
models.CheckConstraint(condition=Q(id=1), name="lottery_config_single_row"),
models.CheckConstraint(condition=Q(bet_amount_sats__gt=0), name="lottery_config_bet_positive"),
models.CheckConstraint(condition=Q(round_duration_seconds__gt=0), name="lottery_config_duration_positive"),
models.CheckConstraint(condition=Q(max_round_pool_sats__gte=0), name="lottery_config_cap_not_negative"),
models.CheckConstraint(
condition=Q(draw_confirmations__gte=1, draw_confirmations__lte=20),
name="lottery_config_draw_confirmations_range",
),
]
@classmethod
def get(cls) -> "LotteryConfig":
config, _ = cls.objects.get_or_create(pk=1)
return config
class Round(models.Model):
class Status(models.TextChoices):
OPEN = "open"
CLOSING = "closing"
DRAWING = "drawing"
PAYING_OUT = "paying_out"
CLOSED = "closed"
ACTIVE_STATUSES = (Status.OPEN, Status.CLOSING, Status.DRAWING, Status.PAYING_OUT)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
opened_at = models.DateTimeField(default=timezone.now)
closed_at = models.DateTimeField(null=True, blank=True)
# DAT-61, ADR-10: the rules of *this* round, copied from LotteryConfig when it opens.
duration_seconds = models.PositiveIntegerField(default=600)
cooldown_seconds = models.PositiveIntegerField(default=30)
bet_amount_sats = models.BigIntegerField(default=10 * SATS_PER_PLM)
fee_address = models.CharField(max_length=128, blank=True, default="")
max_round_pool_sats = models.BigIntegerField(default=0)
draw_confirmations = models.PositiveSmallIntegerField(default=3)
pool_address = models.CharField(max_length=128, blank=True, default="")
# RND-14..20: the commit-reveal draw. The secret is stored encrypted and in clear only
# from the reveal (DAT-64); the hash is public from the opening.
server_seed_enc = models.TextField(null=True, blank=True)
server_seed = models.CharField(max_length=64, null=True, blank=True)
server_seed_hash = models.CharField(max_length=64, null=True, blank=True)
participants_hash = models.CharField(max_length=64, null=True, blank=True)
drawing_started_at = models.DateTimeField(null=True, blank=True)
draw_height = models.PositiveIntegerField(null=True, blank=True)
draw_block_hash = models.CharField(max_length=64, null=True, blank=True)
winner = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT, related_name="rounds_won"
)
pool_amount_sats = models.BigIntegerField(null=True, blank=True)
winner_amount_sats = models.BigIntegerField(null=True, blank=True)
fee_amount_sats = models.BigIntegerField(null=True, blank=True)
payout_transaction = models.ForeignKey(
"ChainTransaction", null=True, blank=True, on_delete=models.PROTECT, related_name="paid_rounds"
)
class Meta:
indexes = [models.Index(fields=["status"]), models.Index(fields=["-opened_at"])]
constraints = [
# ADR-22: at most one active round, whatever the code does. A unique index over a
# constant, restricted to the active statuses: any number of closed rounds, one live.
models.UniqueConstraint(
Value(1),
condition=Q(status__in=["open", "closing", "drawing", "paying_out"]),
name="lottery_round_single_active",
),
models.CheckConstraint(
condition=Q(status__in=["open", "closing", "drawing", "paying_out", "closed"]),
name="lottery_round_status_valid",
),
models.CheckConstraint(condition=Q(bet_amount_sats__gt=0), name="lottery_round_bet_positive"),
models.CheckConstraint(condition=Q(duration_seconds__gt=0), name="lottery_round_duration_positive"),
models.CheckConstraint(condition=Q(max_round_pool_sats__gte=0), name="lottery_round_cap_not_negative"),
models.CheckConstraint(
condition=Q(draw_confirmations__gte=1, draw_confirmations__lte=20),
name="lottery_round_draw_confirmations_range",
),
models.CheckConstraint(
condition=~Q(status="closed") | Q(closed_at__isnull=False), name="lottery_round_closed_has_time"
),
models.CheckConstraint(
condition=Q(pool_amount_sats__isnull=True) | Q(pool_amount_sats__gte=0),
name="lottery_round_pool_not_negative",
),
# The split can never pay out more than the pool (RND-21, DAT-01).
models.CheckConstraint(
condition=Q(pool_amount_sats__isnull=True)
| Q(winner_amount_sats__isnull=True)
| Q(fee_amount_sats__isnull=True)
| Q(winner_amount_sats__gte=0, fee_amount_sats__gte=0, winner_amount_sats__lte=F("pool_amount_sats") - F("fee_amount_sats")),
name="lottery_round_split_within_pool",
),
]
def __str__(self) -> str:
return f"Round {self.pk} ({self.status})"
class Participation(models.Model):
"""One player's bet in one round (WEB-22). At most one per player and round (ADR-15)."""
class Status(models.TextChoices):
PENDING = "pending" # accepted, waiting for confirmation
CONFIRMED = "confirmed" # takes part in the draw
REJECTED = "rejected" # refused after the fact; funds returned
EXCLUDED = "excluded" # left out of the draw (e.g. the bet disappeared from the chain)
round = models.ForeignKey(Round, on_delete=models.PROTECT, related_name="participations")
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="participations")
bet_amount_sats = models.BigIntegerField()
status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
created_at = models.DateTimeField(default=timezone.now)
confirmed_at = models.DateTimeField(null=True, blank=True)
# Written once, when the round enters `drawing` (DAT-66): 0-based position in the list
# ordered by public data, never by a server-side timestamp (RND-15).
draw_position = models.PositiveIntegerField(null=True, blank=True)
# The outpoint paying the round's pool address (DAT-63). Empty while the funds are simulated.
bet_txid = models.CharField(max_length=64, blank=True, default="")
bet_vout = models.PositiveIntegerField(default=0)
class Meta:
constraints = [
models.UniqueConstraint(fields=["round", "user"], name="lottery_participation_one_per_round"),
models.UniqueConstraint(
fields=["round", "draw_position"],
condition=Q(draw_position__isnull=False),
name="lottery_participation_unique_position",
),
models.CheckConstraint(condition=Q(bet_amount_sats__gt=0), name="lottery_participation_amount_positive"),
models.CheckConstraint(
condition=Q(status__in=["pending", "confirmed", "rejected", "excluded"]),
name="lottery_participation_status_valid",
),
models.CheckConstraint(
condition=~Q(status="confirmed") | Q(confirmed_at__isnull=False),
name="lottery_participation_confirmed_has_time",
),
# Only a confirmed participant is in the draw list.
models.CheckConstraint(
condition=Q(draw_position__isnull=True) | Q(status="confirmed"),
name="lottery_participation_position_only_confirmed",
),
]
def __str__(self) -> str:
return f"Participation {self.pk} (round {self.round_id}, {self.status})"
class ChainTransaction(models.Model):
"""A transaction the platform builds and tracks (TX-01). In phase A the txids are simulated;
the versions of an RBF replacement arrive with the real engine (roadmap B4)."""
class Kind(models.TextChoices):
BET = "bet"
WITHDRAWAL = "withdrawal"
PAYOUT = "payout"
class Status(models.TextChoices):
BUILDING = "building" # written before it is sent (ADR-31)
PENDING = "pending"
CONFIRMED = "confirmed"
FAILED = "failed"
kind = models.CharField(max_length=16, choices=Kind.choices)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.BUILDING)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT, related_name="chain_transactions"
)
round = models.ForeignKey(
Round, null=True, blank=True, on_delete=models.PROTECT, related_name="chain_transactions"
)
current_txid = models.CharField(max_length=64, null=True, blank=True)
raw_hex = models.TextField(blank=True, default="")
created_at = models.DateTimeField(default=timezone.now)
broadcast_at = models.DateTimeField(null=True, blank=True)
confirmed_at = models.DateTimeField(null=True, blank=True)
failed_at = models.DateTimeField(null=True, blank=True)
failure_reason = models.TextField(blank=True, default="")
class Meta:
indexes = [models.Index(fields=["status"])]
constraints = [
models.UniqueConstraint(
fields=["current_txid"], condition=Q(current_txid__isnull=False), name="lottery_chaintx_unique_txid"
),
models.CheckConstraint(
condition=Q(kind__in=["bet", "withdrawal", "payout"]), name="lottery_chaintx_kind_valid"
),
models.CheckConstraint(
condition=Q(status__in=["building", "pending", "confirmed", "failed"]),
name="lottery_chaintx_status_valid",
),
models.CheckConstraint(
condition=~Q(status="confirmed") | Q(confirmed_at__isnull=False),
name="lottery_chaintx_confirmed_has_time",
),
# A failure always says why (ADR-51: nothing is given up without a reason).
models.CheckConstraint(
condition=~Q(status="failed") | (Q(failed_at__isnull=False) & ~Q(failure_reason="")),
name="lottery_chaintx_failed_has_reason",
),
# Bets and withdrawals belong to a player, payouts to a round.
models.CheckConstraint(
condition=~Q(kind__in=["bet", "withdrawal"]) | Q(user__isnull=False),
name="lottery_chaintx_user_kinds_have_user",
),
models.CheckConstraint(
condition=~Q(kind="payout") | Q(round__isnull=False), name="lottery_chaintx_payout_has_round"
),
]
def __str__(self) -> str:
return f"{self.kind} {self.current_txid or self.pk} ({self.status})"
class Movement(models.Model):
"""One line of a player's ledger (WEB-21, WEB-24). The balance is derived from these lines,
never stored beside them: a credit is positive, a debit negative, and never zero."""
class Kind(models.TextChoices):
DEPOSIT = "deposit"
BET = "bet"
WIN = "win"
REFUND = "refund" # a bet returned after a rejection
WITHDRAWAL = "withdrawal"
class Status(models.TextChoices):
PENDING = "pending" # funds in confirmation
CONFIRMED = "confirmed"
FAILED = "failed"
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="movements")
kind = models.CharField(max_length=16, choices=Kind.choices)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
amount_sats = models.BigIntegerField()
round = models.ForeignKey(Round, null=True, blank=True, on_delete=models.PROTECT, related_name="movements")
participation = models.ForeignKey(
Participation, null=True, blank=True, on_delete=models.PROTECT, related_name="movements"
)
chain_transaction = models.ForeignKey(
ChainTransaction, null=True, blank=True, on_delete=models.PROTECT, related_name="movements"
)
# WEB-23: the client-chosen key of the request. The same key from the same player is the
# same operation, however many times it is sent.
request_id = models.UUIDField(null=True, blank=True)
destination = models.CharField(max_length=128, blank=True, default="") # withdrawals
created_at = models.DateTimeField(default=timezone.now)
confirmed_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=["user", "-created_at"]), models.Index(fields=["user", "status"])]
constraints = [
models.UniqueConstraint(
fields=["user", "request_id"],
condition=Q(request_id__isnull=False),
name="lottery_movement_idempotency",
),
models.CheckConstraint(condition=~Q(amount_sats=0), name="lottery_movement_amount_not_zero"),
models.CheckConstraint(
condition=Q(kind__in=["deposit", "bet", "win", "refund", "withdrawal"]),
name="lottery_movement_kind_valid",
),
models.CheckConstraint(
condition=Q(status__in=["pending", "confirmed", "failed"]), name="lottery_movement_status_valid"
),
# The sign follows the kind: money in is positive, money out is negative.
models.CheckConstraint(
condition=(Q(kind__in=["deposit", "win", "refund"]) & Q(amount_sats__gt=0))
| (Q(kind__in=["bet", "withdrawal"]) & Q(amount_sats__lt=0)),
name="lottery_movement_sign_follows_kind",
),
models.CheckConstraint(
condition=~Q(kind__in=["bet", "win", "refund"]) | Q(round__isnull=False),
name="lottery_movement_round_kinds_have_round",
),
models.CheckConstraint(
condition=~Q(status="confirmed") | Q(confirmed_at__isnull=False),
name="lottery_movement_confirmed_has_time",
),
]
def __str__(self) -> str:
return f"{self.kind} {self.amount_sats} ({self.status})"
class AuditQuerySet(models.QuerySet):
def update(self, **kwargs):
raise AuditEntryImmutable("the audit log is append-only")
def delete(self):
raise AuditEntryImmutable("the audit log is append-only")
class AuditEntryImmutable(Exception):
"""An attempt to change or delete an audit row (AUD-47)."""
class AuditEntry(models.Model):
"""Who did what, when, why and with what outcome (WEB-32, AUD-47).
Append-only: the model refuses updates and deletes, and so does the database (triggers in
the migration), so no code path — nor a stray SQL statement — can rewrite history.
"""
class Outcome(models.TextChoices):
OK = "ok"
DENIED = "denied"
ERROR = "error"
created_at = models.DateTimeField(default=timezone.now, db_index=True)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT, related_name="audit_entries"
)
# The name at the time (or "system"/"worker" for automatic actions): it survives a rename.
actor_label = models.CharField(max_length=150)
action = models.CharField(max_length=64, db_index=True)
reason = models.TextField(blank=True, default="")
outcome = models.CharField(max_length=8, choices=Outcome.choices, default=Outcome.OK)
subject_type = models.CharField(max_length=32, blank=True, default="")
subject_id = models.CharField(max_length=64, blank=True, default="")
payload = models.JSONField(default=dict, blank=True)
objects = AuditQuerySet.as_manager()
class Meta:
verbose_name_plural = "audit entries"
constraints = [
models.CheckConstraint(condition=Q(outcome__in=["ok", "denied", "error"]), name="lottery_audit_outcome_valid"),
]
def save(self, *args, **kwargs):
if not self._state.adding:
raise AuditEntryImmutable("the audit log is append-only")
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
raise AuditEntryImmutable("the audit log is append-only")
def __str__(self) -> str:
return f"{self.created_at:%Y-%m-%d %H:%M} {self.actor_label} {self.action}"