Files
plm-lottery/apps/lottery/models.py
T

558 lines
26 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.db.models.functions import Length
from django.db.models.lookups import Exact
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)
# DAT-62, DEP-21: confirmations a deposit needs before it is credited; read at every scan, so a change
# applies at once to the credits that follow.
deposit_confirmations = models.PositiveSmallIntegerField(default=6)
max_round_pool_sats = models.BigIntegerField(default=0) # 0 = no cap
# Network fee of the transactions built from now on, sat/vB (BET-04); a transaction in flight keeps its own.
fee_rate_sat_vb = models.PositiveIntegerField(default=1)
# 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)
# WEB-31: written by the worker at every tick; the console reads it to tell a live worker from a dead one.
worker_seen_at = models.DateTimeField(null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
# WEB-30, WEB-44: one explicit permission per operational command, checked in the view and again in the service.
permissions = [
("view_console", "Can open the operations console"),
("pause_after_round", "Can pause the lottery after the round in progress"),
("suspend_new_bets", "Can suspend new bets"),
("suspend_withdrawals", "Can suspend withdrawals"),
]
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",
),
models.CheckConstraint(
condition=Q(deposit_confirmations__gte=1, deposit_confirmations__lte=100),
name="lottery_config_deposit_confirmations_range",
),
models.CheckConstraint(
condition=Q(fee_rate_sat_vb__gte=1, fee_rate_sat_vb__lte=5000), name="lottery_config_fee_rate_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}"
class Report(models.Model):
"""A problem report written by a player from the profile (WEB-55). Staff reads it and changes its
status from the admin; each status change is in the audit."""
class Status(models.TextChoices):
OPEN = "open", "Aperta"
READ = "read", "Letta"
RESOLVED = "resolved", "Risolta"
MAX_LENGTH = 1000
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="reports")
text = models.TextField(max_length=MAX_LENGTH)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
created_at = models.DateTimeField(default=timezone.now)
status_changed_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=["user", "-created_at"]), models.Index(fields=["status"])]
constraints = [
models.CheckConstraint(condition=Q(status__in=["open", "read", "resolved"]), name="lottery_report_status_valid"),
]
def __str__(self) -> str:
return f"Report {self.pk} ({self.status})"
# --- chain tables (roadmap B4, DAT-81..DAT-84) ---------------------------------------------------
class DepositAddress(models.Model):
"""A player's one deposit address and the HD index it comes from (DAT-81)."""
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="deposit_address")
derivation_index = models.PositiveIntegerField(unique=True)
address = models.CharField(max_length=128, unique=True)
network = models.CharField(max_length=16) # the profile it was derived for (ADR-58)
created_at = models.DateTimeField(default=timezone.now)
class Meta:
constraints = [
models.CheckConstraint(condition=Q(network__in=["mainnet", "regtest"]), name="lottery_depositaddress_network_valid"),
]
def __str__(self) -> str:
return f"{self.address} (index {self.derivation_index})"
class Utxo(models.Model):
"""An output the platform controls (DAT-82): a player's deposit or a round's pool money."""
txid = models.CharField(max_length=64)
vout = models.PositiveIntegerField()
amount_sats = models.BigIntegerField()
address = models.CharField(max_length=128)
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT, related_name="utxos")
round = models.ForeignKey(Round, null=True, blank=True, on_delete=models.PROTECT, related_name="utxos")
confirmed_height = models.PositiveIntegerField(null=True, blank=True)
spent_txid = models.CharField(max_length=64, null=True, blank=True)
# ARC-72: the transaction that is spending it. Taken atomically in the database, never in memory (B6).
reserved_by = models.ForeignKey(
ChainTransaction, null=True, blank=True, on_delete=models.PROTECT, related_name="reserved_utxos"
)
created_at = models.DateTimeField(default=timezone.now)
class Meta:
indexes = [models.Index(fields=["address"]), models.Index(fields=["user"])]
constraints = [
models.UniqueConstraint(fields=["txid", "vout"], name="lottery_utxo_outpoint_unique"),
models.CheckConstraint(condition=Q(amount_sats__gt=0), name="lottery_utxo_amount_positive"),
models.CheckConstraint(condition=Exact(Length("txid"), 64), name="lottery_utxo_txid_length"),
models.CheckConstraint(
condition=Q(spent_txid__isnull=True) | Q(Exact(Length("spent_txid"), 64)), name="lottery_utxo_spent_txid_length"
),
models.CheckConstraint(condition=Q(user__isnull=True) | Q(round__isnull=True), name="lottery_utxo_user_or_round"),
]
def __str__(self) -> str:
return f"{self.txid[:12]}:{self.vout}"
class TransactionVersionImmutable(Exception):
"""An attempt to change or delete a transaction version (DAT-83)."""
class TransactionVersionQuerySet(models.QuerySet):
def update(self, **kwargs):
raise TransactionVersionImmutable("transaction versions are append-only")
def delete(self):
raise TransactionVersionImmutable("transaction versions are append-only")
class TransactionVersion(models.Model):
"""Every txid a platform transaction has ever had (TX-19, DAT-83): the network may confirm any of them."""
transaction = models.ForeignKey(ChainTransaction, on_delete=models.PROTECT, related_name="versions")
txid = models.CharField(max_length=64, unique=True)
raw_hex = models.TextField(blank=True, default="")
created_at = models.DateTimeField(default=timezone.now)
objects = TransactionVersionQuerySet.as_manager()
class Meta:
constraints = [models.CheckConstraint(condition=Exact(Length("txid"), 64), name="lottery_txversion_txid_length")]
def save(self, *args, **kwargs):
if not self._state.adding:
raise TransactionVersionImmutable("transaction versions are append-only")
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
raise TransactionVersionImmutable("transaction versions are append-only")
def __str__(self) -> str:
return self.txid
class Deposit(models.Model):
"""An output that paid a player's deposit address (DAT-84)."""
class Status(models.TextChoices):
DETECTED = "detected"
CREDITED = "credited"
ORPHANED = "orphaned"
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="deposits")
utxo = models.OneToOneField(Utxo, on_delete=models.PROTECT, related_name="deposit")
movement = models.OneToOneField(Movement, null=True, blank=True, on_delete=models.PROTECT, related_name="deposit")
status = models.CharField(max_length=16, choices=Status.choices, default=Status.DETECTED)
detected_at = models.DateTimeField(default=timezone.now)
credited_at = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
models.CheckConstraint(
condition=Q(status__in=["detected", "credited", "orphaned"]), name="lottery_deposit_status_valid"
),
models.CheckConstraint(
condition=~Q(status="credited") | (Q(movement__isnull=False) & Q(credited_at__isnull=False)),
name="lottery_deposit_credited_has_movement",
),
]
def __str__(self) -> str:
return f"Deposit {self.pk} ({self.status})"