diff --git a/CLAUDE.md b/CLAUDE.md index d7224d3..bc35c95 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 — 775 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 — 831 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 775 tests +python -m pytest # all 831 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/README.md b/README.md index e1b7bc7..885eb0c 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 ``` -775 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +831 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/apps/lottery/audit.py b/apps/lottery/audit.py new file mode 100644 index 0000000..102a7b8 --- /dev/null +++ b/apps/lottery/audit.py @@ -0,0 +1,35 @@ +"""The one place audit rows are written (AUD-01, AUD-47). + +Call it inside the same database transaction as the change it records (ADR-53), so a change +and its trace commit or roll back together. +""" + +from typing import Any + +from .models import AuditEntry + + +def record( + action: str, + *, + actor=None, + actor_label: str | None = None, + reason: str = "", + outcome: str = AuditEntry.Outcome.OK, + subject_type: str = "", + subject_id: object = "", + payload: dict[str, Any] | None = None, +) -> AuditEntry: + """Append one audit row. `actor` is the user who acted, or None for the system/worker.""" + if actor_label is None: + actor_label = actor.get_username() if actor is not None else "system" + return AuditEntry.objects.create( + actor=actor, + actor_label=actor_label, + action=action, + reason=reason, + outcome=outcome, + subject_type=subject_type, + subject_id=str(subject_id), + payload=payload or {}, + ) diff --git a/apps/lottery/migrations/0001_initial.py b/apps/lottery/migrations/0001_initial.py new file mode 100644 index 0000000..e4be1b6 --- /dev/null +++ b/apps/lottery/migrations/0001_initial.py @@ -0,0 +1,274 @@ +# Generated by Django 5.2.19 on 2026-11-16 11:02 + +import django.db.models.deletion +import django.db.models.expressions +import django.utils.timezone +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='ChainTransaction', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('kind', models.CharField(choices=[('bet', 'Bet'), ('withdrawal', 'Withdrawal'), ('payout', 'Payout')], max_length=16)), + ('status', models.CharField(choices=[('building', 'Building'), ('pending', 'Pending'), ('confirmed', 'Confirmed'), ('failed', 'Failed')], default='building', max_length=16)), + ('current_txid', models.CharField(blank=True, max_length=64, null=True)), + ('raw_hex', models.TextField(blank=True, default='')), + ('created_at', models.DateTimeField(default=django.utils.timezone.now)), + ('broadcast_at', models.DateTimeField(blank=True, null=True)), + ('confirmed_at', models.DateTimeField(blank=True, null=True)), + ('failed_at', models.DateTimeField(blank=True, null=True)), + ('failure_reason', models.TextField(blank=True, default='')), + ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='chain_transactions', to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='LotteryConfig', + fields=[ + ('id', models.PositiveSmallIntegerField(default=1, primary_key=True, serialize=False)), + ('fee_address', models.CharField(blank=True, default='', max_length=128)), + ('bet_amount_sats', models.BigIntegerField(default=1000000000)), + ('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)), + ('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)), + ], + options={ + 'constraints': [models.CheckConstraint(condition=models.Q(('id', 1)), name='lottery_config_single_row'), models.CheckConstraint(condition=models.Q(('bet_amount_sats__gt', 0)), name='lottery_config_bet_positive'), models.CheckConstraint(condition=models.Q(('round_duration_seconds__gt', 0)), name='lottery_config_duration_positive'), models.CheckConstraint(condition=models.Q(('max_round_pool_sats__gte', 0)), name='lottery_config_cap_not_negative'), models.CheckConstraint(condition=models.Q(('draw_confirmations__gte', 1), ('draw_confirmations__lte', 20)), name='lottery_config_draw_confirmations_range')], + }, + ), + migrations.CreateModel( + name='Round', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('status', models.CharField(choices=[('open', 'Open'), ('closing', 'Closing'), ('drawing', 'Drawing'), ('paying_out', 'Paying Out'), ('closed', 'Closed')], default='open', max_length=16)), + ('opened_at', models.DateTimeField(default=django.utils.timezone.now)), + ('closed_at', models.DateTimeField(blank=True, null=True)), + ('duration_seconds', models.PositiveIntegerField(default=600)), + ('cooldown_seconds', models.PositiveIntegerField(default=30)), + ('bet_amount_sats', models.BigIntegerField(default=1000000000)), + ('fee_address', models.CharField(blank=True, default='', max_length=128)), + ('max_round_pool_sats', models.BigIntegerField(default=0)), + ('draw_confirmations', models.PositiveSmallIntegerField(default=3)), + ('pool_address', models.CharField(blank=True, default='', max_length=128)), + ('server_seed_enc', models.TextField(blank=True, null=True)), + ('server_seed', models.CharField(blank=True, max_length=64, null=True)), + ('server_seed_hash', models.CharField(blank=True, max_length=64, null=True)), + ('participants_hash', models.CharField(blank=True, max_length=64, null=True)), + ('drawing_started_at', models.DateTimeField(blank=True, null=True)), + ('draw_height', models.PositiveIntegerField(blank=True, null=True)), + ('draw_block_hash', models.CharField(blank=True, max_length=64, null=True)), + ('pool_amount_sats', models.BigIntegerField(blank=True, null=True)), + ('winner_amount_sats', models.BigIntegerField(blank=True, null=True)), + ('fee_amount_sats', models.BigIntegerField(blank=True, null=True)), + ('payout_transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='paid_rounds', to='lottery.chaintransaction')), + ('winner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='rounds_won', to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='Participation', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('bet_amount_sats', models.BigIntegerField()), + ('status', models.CharField(choices=[('pending', 'Pending'), ('confirmed', 'Confirmed'), ('rejected', 'Rejected'), ('excluded', 'Excluded')], default='pending', max_length=16)), + ('created_at', models.DateTimeField(default=django.utils.timezone.now)), + ('confirmed_at', models.DateTimeField(blank=True, null=True)), + ('draw_position', models.PositiveIntegerField(blank=True, null=True)), + ('bet_txid', models.CharField(blank=True, default='', max_length=64)), + ('bet_vout', models.PositiveIntegerField(default=0)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='participations', to=settings.AUTH_USER_MODEL)), + ('round', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='participations', to='lottery.round')), + ], + ), + migrations.CreateModel( + name='Movement', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('kind', models.CharField(choices=[('deposit', 'Deposit'), ('bet', 'Bet'), ('win', 'Win'), ('refund', 'Refund'), ('withdrawal', 'Withdrawal')], max_length=16)), + ('status', models.CharField(choices=[('pending', 'Pending'), ('confirmed', 'Confirmed'), ('failed', 'Failed')], default='pending', max_length=16)), + ('amount_sats', models.BigIntegerField()), + ('request_id', models.UUIDField(blank=True, null=True)), + ('destination', models.CharField(blank=True, default='', max_length=128)), + ('created_at', models.DateTimeField(default=django.utils.timezone.now)), + ('confirmed_at', models.DateTimeField(blank=True, null=True)), + ('chain_transaction', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='movements', to='lottery.chaintransaction')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='movements', to=settings.AUTH_USER_MODEL)), + ('participation', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='movements', to='lottery.participation')), + ('round', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='movements', to='lottery.round')), + ], + ), + migrations.AddField( + model_name='chaintransaction', + name='round', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='chain_transactions', to='lottery.round'), + ), + migrations.CreateModel( + name='AuditEntry', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(db_index=True, default=django.utils.timezone.now)), + ('actor_label', models.CharField(max_length=150)), + ('action', models.CharField(db_index=True, max_length=64)), + ('reason', models.TextField(blank=True, default='')), + ('outcome', models.CharField(choices=[('ok', 'Ok'), ('denied', 'Denied'), ('error', 'Error')], default='ok', max_length=8)), + ('subject_type', models.CharField(blank=True, default='', max_length=32)), + ('subject_id', models.CharField(blank=True, default='', max_length=64)), + ('payload', models.JSONField(blank=True, default=dict)), + ('actor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='audit_entries', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name_plural': 'audit entries', + 'constraints': [models.CheckConstraint(condition=models.Q(('outcome__in', ['ok', 'denied', 'error'])), name='lottery_audit_outcome_valid')], + }, + ), + migrations.AddIndex( + model_name='round', + index=models.Index(fields=['status'], name='lottery_rou_status_0bc276_idx'), + ), + migrations.AddIndex( + model_name='round', + index=models.Index(fields=['-opened_at'], name='lottery_rou_opened__cab610_idx'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.UniqueConstraint(models.Value(1), condition=models.Q(('status__in', ['open', 'closing', 'drawing', 'paying_out'])), name='lottery_round_single_active'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('status__in', ['open', 'closing', 'drawing', 'paying_out', 'closed'])), name='lottery_round_status_valid'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('bet_amount_sats__gt', 0)), name='lottery_round_bet_positive'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('duration_seconds__gt', 0)), name='lottery_round_duration_positive'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('max_round_pool_sats__gte', 0)), name='lottery_round_cap_not_negative'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('draw_confirmations__gte', 1), ('draw_confirmations__lte', 20)), name='lottery_round_draw_confirmations_range'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('status', 'closed'), _negated=True), ('closed_at__isnull', False), _connector='OR'), name='lottery_round_closed_has_time'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('pool_amount_sats__isnull', True), ('pool_amount_sats__gte', 0), _connector='OR'), name='lottery_round_pool_not_negative'), + ), + migrations.AddConstraint( + model_name='round', + constraint=models.CheckConstraint(condition=models.Q(('pool_amount_sats__isnull', True), ('winner_amount_sats__isnull', True), ('fee_amount_sats__isnull', True), models.Q(('fee_amount_sats__gte', 0), ('winner_amount_sats__gte', 0), ('winner_amount_sats__lte', django.db.models.expressions.CombinedExpression(models.F('pool_amount_sats'), '-', models.F('fee_amount_sats')))), _connector='OR'), name='lottery_round_split_within_pool'), + ), + migrations.AddConstraint( + model_name='participation', + constraint=models.UniqueConstraint(fields=('round', 'user'), name='lottery_participation_one_per_round'), + ), + migrations.AddConstraint( + model_name='participation', + constraint=models.UniqueConstraint(condition=models.Q(('draw_position__isnull', False)), fields=('round', 'draw_position'), name='lottery_participation_unique_position'), + ), + migrations.AddConstraint( + model_name='participation', + constraint=models.CheckConstraint(condition=models.Q(('bet_amount_sats__gt', 0)), name='lottery_participation_amount_positive'), + ), + migrations.AddConstraint( + model_name='participation', + constraint=models.CheckConstraint(condition=models.Q(('status__in', ['pending', 'confirmed', 'rejected', 'excluded'])), name='lottery_participation_status_valid'), + ), + migrations.AddConstraint( + model_name='participation', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('status', 'confirmed'), _negated=True), ('confirmed_at__isnull', False), _connector='OR'), name='lottery_participation_confirmed_has_time'), + ), + migrations.AddConstraint( + model_name='participation', + constraint=models.CheckConstraint(condition=models.Q(('draw_position__isnull', True), ('status', 'confirmed'), _connector='OR'), name='lottery_participation_position_only_confirmed'), + ), + migrations.AddIndex( + model_name='movement', + index=models.Index(fields=['user', '-created_at'], name='lottery_mov_user_id_a94bbb_idx'), + ), + migrations.AddIndex( + model_name='movement', + index=models.Index(fields=['user', 'status'], name='lottery_mov_user_id_5821a0_idx'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.UniqueConstraint(condition=models.Q(('request_id__isnull', False)), fields=('user', 'request_id'), name='lottery_movement_idempotency'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.CheckConstraint(condition=models.Q(('amount_sats', 0), _negated=True), name='lottery_movement_amount_not_zero'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.CheckConstraint(condition=models.Q(('kind__in', ['deposit', 'bet', 'win', 'refund', 'withdrawal'])), name='lottery_movement_kind_valid'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.CheckConstraint(condition=models.Q(('status__in', ['pending', 'confirmed', 'failed'])), name='lottery_movement_status_valid'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('kind__in', ['deposit', 'win', 'refund']), ('amount_sats__gt', 0)), models.Q(('kind__in', ['bet', 'withdrawal']), ('amount_sats__lt', 0)), _connector='OR'), name='lottery_movement_sign_follows_kind'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('kind__in', ['bet', 'win', 'refund']), _negated=True), ('round__isnull', False), _connector='OR'), name='lottery_movement_round_kinds_have_round'), + ), + migrations.AddConstraint( + model_name='movement', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('status', 'confirmed'), _negated=True), ('confirmed_at__isnull', False), _connector='OR'), name='lottery_movement_confirmed_has_time'), + ), + migrations.AddIndex( + model_name='chaintransaction', + index=models.Index(fields=['status'], name='lottery_cha_status_9a6ca9_idx'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.UniqueConstraint(condition=models.Q(('current_txid__isnull', False)), fields=('current_txid',), name='lottery_chaintx_unique_txid'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.CheckConstraint(condition=models.Q(('kind__in', ['bet', 'withdrawal', 'payout'])), name='lottery_chaintx_kind_valid'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.CheckConstraint(condition=models.Q(('status__in', ['building', 'pending', 'confirmed', 'failed'])), name='lottery_chaintx_status_valid'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('status', 'confirmed'), _negated=True), ('confirmed_at__isnull', False), _connector='OR'), name='lottery_chaintx_confirmed_has_time'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('status', 'failed'), _negated=True), models.Q(('failed_at__isnull', False), models.Q(('failure_reason', ''), _negated=True)), _connector='OR'), name='lottery_chaintx_failed_has_reason'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('kind__in', ['bet', 'withdrawal']), _negated=True), ('user__isnull', False), _connector='OR'), name='lottery_chaintx_user_kinds_have_user'), + ), + migrations.AddConstraint( + model_name='chaintransaction', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('kind', 'payout'), _negated=True), ('round__isnull', False), _connector='OR'), name='lottery_chaintx_payout_has_round'), + ), + ] diff --git a/apps/lottery/migrations/0002_audit_append_only_triggers.py b/apps/lottery/migrations/0002_audit_append_only_triggers.py new file mode 100644 index 0000000..5ada2a0 --- /dev/null +++ b/apps/lottery/migrations/0002_audit_append_only_triggers.py @@ -0,0 +1,24 @@ +"""The audit log is append-only in the database too (AUD-47). + +Whatever the code does — a raw `UPDATE`, a `QuerySet._raw_delete`, a shell session — a row of +`lottery_auditentry` can only be inserted. SQLite syntax; PostgreSQL gets its own migration the +day it replaces SQLite (ADR-55). +""" + +from django.db import migrations + +CREATE = [ + """CREATE TRIGGER lottery_audit_no_update BEFORE UPDATE ON lottery_auditentry + BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END""", + """CREATE TRIGGER lottery_audit_no_delete BEFORE DELETE ON lottery_auditentry + BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END""", +] +DROP = [ + "DROP TRIGGER IF EXISTS lottery_audit_no_update", + "DROP TRIGGER IF EXISTS lottery_audit_no_delete", +] + + +class Migration(migrations.Migration): + dependencies = [("lottery", "0001_initial")] + operations = [migrations.RunSQL(sql=CREATE, reverse_sql=DROP)] diff --git a/apps/lottery/migrations/__init__.py b/apps/lottery/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/lottery/models.py b/apps/lottery/models.py new file mode 100644 index 0000000..40335ec --- /dev/null +++ b/apps/lottery/models.py @@ -0,0 +1,385 @@ +"""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}" diff --git a/docs/audit-log.md b/docs/audit-log.md index 7b55324..599c5ca 100644 --- a/docs/audit-log.md +++ b/docs/audit-log.md @@ -685,3 +685,16 @@ nome tra parentesi quadre nel log è il modulo (`app.rounds.scheduler`, ecc.). | ERROR | `app.tx.reconcile` | `round N payout tx … vanished — round needs operator attention` | Pagamento abbandonato; il nuovo tentativo automatico parte da solo | | ERROR | `app.auth.security` | `stored password hash is unparseable …` | Hash di password corrotto nel database: quell'utente non può accedere | | ERROR (con traccia) | `app.main` | `Unhandled error on …` | Errore 500 su una richiesta ([AUD-35]) | + +## Registro di audit del sito Django + +- **[AUD-47]** **Registro in sola aggiunta, scritto da un solo punto.** `AuditEntry` registra data, attore + (l'utente, e il suo nome di allora, oppure `system`), azione, motivo, esito (`ok`, `denied`, `error`), + oggetto e dati. Si scrive solo con `apps/lottery/audit.py:record`, **nella stessa transazione** del + cambiamento che registra ([ADR-53](adr/ADR-53-registro-audit-solo-aggiunta-stessa-transazione.md)): se il cambiamento + si annulla, si annulla anche la riga. Il modello rifiuta modifiche e cancellazioni (`save` su riga esistente, + `delete`, `QuerySet.update`/`delete`) e **il database le rifiuta a sua volta** con trigger SQLite + (`BEFORE UPDATE`/`BEFORE DELETE`), quindi nemmeno un `UPDATE` SQL diretto riscrive la storia. + *Stato:* implementato (A2) · + *Codice:* `apps/lottery/audit.py:record`, `apps/lottery/models.py:AuditEntry`, `apps/lottery/migrations/0002_audit_append_only_triggers.py` · + *Test:* `tests/django/test_models.py::test_an_audit_row_cannot_be_changed_with_raw_sql_either`, `test_the_audit_is_written_in_the_same_transaction_as_the_change` diff --git a/docs/modello-dati.md b/docs/modello-dati.md index eeecd94..0ccd256 100644 --- a/docs/modello-dati.md +++ b/docs/modello-dati.md @@ -1487,3 +1487,41 @@ scrive la stringa vuota). - **Portabilità.** I pragma sono limitati al dialetto `sqlite` e l'indice del round attivo è dichiarato anche per PostgreSQL. Un `DATABASE_URL` PostgreSQL non è però mai stato provato, e il database supportato resta SQLite. + +## Modello Django (migrazione in corso) + +Lo schema del sito Django (`apps/lottery/models.py`, `apps/accounts/models.py`) sostituisce quello +SQLAlchemy descritto sopra (roadmap A2–D1); fino ad allora il resto del documento è lo stato storico. +Le regole che devono valere comunque sono **vincoli del database**, non convenzioni ([ARC-72]). +Le tabelle di catena (UTXO, versioni delle transazioni, depositi, indici HD) arrivano con la Fase B (B4). + +- **[DAT-76]** **Il denaro non si cancella.** Ogni chiave esterna delle tabelle `lottery_*` verso utenti, round, + partecipazioni e transazioni è `PROTECT`: un utente, un round o una transazione con righe collegate non + si elimina. Ogni importo è un intero in unità minime ([DAT-01]) e ogni timestamp è in UTC con fuso ([DAT-02]). + *Stato:* implementato (A2) · *Codice:* `apps/lottery/models.py` · *Test:* `tests/django/test_models.py::test_rows_that_carry_money_cannot_be_deleted_with_their_owner` +- **[DAT-77]** **Parametri e pause: `LotteryConfig`.** Una sola riga (`id = 1`, vincolo) con quota (10 PLM), + durata (600 s), pausa fra round (30 s), conferme del blocco di estrazione (1–20, default 3), tetto del + montepremi (0 = nessuno) e i tre interruttori di [ADR-57](adr/ADR-57-due-pause-distinte-dopo-round-e-incidente.md): + `pause_after_round`, `new_bets_suspended`, `withdrawals_suspended`. Valori non positivi o fuori intervallo + sono rifiutati dal database. I parametri si **copiano su `Round` all'apertura** ([DAT-61]); la copia la fa il + servizio (A4), le colonne del round sono già proprie. + *Stato:* tabella implementata (A2), copia all'apertura da implementare (A4) · + *Codice:* `apps/lottery/models.py:LotteryConfig` · *Test:* `tests/django/test_models.py::test_config_is_a_single_row`, `test_a_round_keeps_its_own_rules` +- **[DAT-78]** **Round, partecipazioni, movimenti, transazioni.** + - `Round`: stati `open`, `closing`, `drawing`, `paying_out`, `closed`; **al più un round attivo** + (indice unico parziale `lottery_round_single_active`, [ADR-22](adr/ADR-22-piu-round-attivo-come-invariante-database.md)); + un round chiuso ha `closed_at`; la ripartizione non supera il montepremi (`vincitore + commissioni ≤ montepremi`). + - `Participation`: una sola scommessa per giocatore e round ([ADR-15](adr/ADR-15-biglietto-prezzo-fisso-scommessa-utente-round.md)); + `draw_position` unica nel round e solo per partecipanti `confirmed` ([DAT-66]); `confirmed` richiede `confirmed_at`. + - `Movement`: riga del libro mastro del giocatore; **il segno segue il tipo** (`deposit`, `win`, `refund` positivi; + `bet`, `withdrawal` negativi; mai zero); `bet`, `win`, `refund` appartengono a un round; **`(user, request_id)` è unico** + quando la chiave c'è ([WEB-23]). Il saldo si **deriva** dai movimenti, non si memorizza accanto. + - `ChainTransaction`: stati `building`, `pending`, `confirmed`, `failed`; `current_txid` unico se presente; un + fallimento ha sempre data e motivo ([ADR-51](adr/ADR-51-dubbio-liberano-mai-fondi.md)); scommesse e prelievi hanno un + giocatore, i pagamenti un round. + *Stato:* implementato (A2) · *Codice:* `apps/lottery/models.py` · + *Test:* `tests/django/test_models.py` (un caso per ogni vincolo) +- **[DAT-79]** **`accounts.User`.** Modello utente personalizzato, unico per giocatori e staff (lo staff è un ruolo, + [ADR-56](adr/ADR-56-staff-account-individuali-permessi-mfa-dopo-pilota.md)); username unico senza distinzione fra + maiuscole ([DAT-06]), memorizzato come digitato. + *Stato:* implementato (A1) · *Codice:* `apps/accounts/models.py` · *Test:* `tests/django/test_scaffold.py::test_usernames_are_unique_ignoring_case` diff --git a/docs/sito-e-app.md b/docs/sito-e-app.md index 31d295e..c0dfeaf 100644 --- a/docs/sito-e-app.md +++ b/docs/sito-e-app.md @@ -37,6 +37,8 @@ backend FastAPI (vedi [architettura.md](architettura.md)). - **[WEB-04]** Importi e saldi si rappresentano in unità minime intere ([ADR-35](adr/ADR-35-aritmetica-satoshi-interi.md)); i parametri economici e temporali del round sono fissati alla sua apertura ([ADR-10](adr/ADR-10-parametri-round-fotografati-all-apertura.md)). + *Stato:* colonne e vincoli implementati (A2, [DAT-76]…[DAT-78]); la copia all'apertura con A4 · + *Test:* `tests/django/test_models.py::test_amounts_are_integers_only` - **[WEB-05]** I dati che cambiano (stato del round, saldo, esito) si aggiornano con richieste periodiche mirate e si recuperano al rientro nella pagina; ricaricare non perde lo stato salvato. diff --git a/roadmap.md b/roadmap.md index 833787f..5deaace 100644 --- a/roadmap.md +++ b/roadmap.md @@ -25,7 +25,7 @@ Il lavoro prosegue in un solo branch, senza convivenza di servizi. Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore lo segue e lo mette in pausa, un visitatore verifica l'esito. - [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 `/`. -- [ ] **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] **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. - [ ] **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. - [ ] **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. diff --git a/tests/django/test_models.py b/tests/django/test_models.py new file mode 100644 index 0000000..6dcae92 --- /dev/null +++ b/tests/django/test_models.py @@ -0,0 +1,364 @@ +"""A2 — lottery data model and its constraints: WEB-04, ADR-10, ADR-15, ADR-22, DAT-76..79, AUD-47.""" + +from datetime import timedelta +from uuid import uuid4 + +import pytest +from django.contrib.auth import get_user_model +from django.db import IntegrityError, connection, transaction +from django.utils import timezone + +from apps.lottery import audit +from apps.lottery.models import ( + AuditEntry, + AuditEntryImmutable, + ChainTransaction, + LotteryConfig, + Movement, + Participation, + Round, +) + +pytestmark = pytest.mark.django_db + +PLM = 100_000_000 + + +def make_user(name="mario"): + return get_user_model().objects.create_user(name, password="x" * 12) + + +def make_round(**kwargs): + return Round.objects.create(**kwargs) + + +def refused(make): + """True if the database refuses what `make` does.""" + try: + with transaction.atomic(): + make() + except IntegrityError: + return True + return False + + +# --- LotteryConfig ----------------------------------------------------------------------------- + + +def test_config_defaults_match_the_documented_economy(): + """DAT-77: bet 10 PLM, 600s rounds, 30s cooldown, 3 draw confirmations, nothing paused.""" + config = LotteryConfig.get() + assert config.bet_amount_sats == 10 * PLM + assert (config.round_duration_seconds, config.round_cooldown_seconds, config.draw_confirmations) == (600, 30, 3) + assert config.max_round_pool_sats == 0 + assert not (config.pause_after_round or config.new_bets_suspended or config.withdrawals_suspended) + + +def test_config_is_a_single_row(): + LotteryConfig.get() + assert LotteryConfig.objects.count() == 1 + assert refused(lambda: LotteryConfig.objects.create(id=2)) + + +@pytest.mark.parametrize( + "field,value", + [("bet_amount_sats", 0), ("round_duration_seconds", 0), ("max_round_pool_sats", -1), + ("draw_confirmations", 0), ("draw_confirmations", 21)], +) +def test_config_refuses_nonsense_values(field, value): + config = LotteryConfig.get() + setattr(config, field, value) + assert refused(config.save) + + +# --- Round ------------------------------------------------------------------------------------- + + +def test_only_one_round_can_be_active(): + """ADR-22: a second active round is refused whatever the code does.""" + make_round(status="open") + for status in ("open", "closing", "drawing", "paying_out"): + assert refused(lambda s=status: make_round(status=s)) + + +def test_any_number_of_closed_rounds_alongside_one_active(): + now = timezone.now() + for _ in range(3): + make_round(status="closed", closed_at=now) + make_round(status="open") + assert Round.objects.count() == 4 + + +def test_a_new_round_may_open_once_the_previous_is_closed(): + first = make_round(status="open") + first.status, first.closed_at = "closed", timezone.now() + first.save() + make_round(status="open") + + +def test_a_round_keeps_its_own_rules(): + """ADR-10, DAT-61: the round's parameters are its own columns, not read from the config.""" + config = LotteryConfig.get() + round_ = make_round(bet_amount_sats=config.bet_amount_sats, duration_seconds=600) + config.bet_amount_sats = 20 * PLM + config.save() + round_.refresh_from_db() + assert round_.bet_amount_sats == 10 * PLM + + +@pytest.mark.parametrize( + "kwargs", + [ + {"status": "bogus"}, + {"bet_amount_sats": 0}, + {"duration_seconds": 0}, + {"max_round_pool_sats": -1}, + {"draw_confirmations": 0}, + {"status": "closed"}, # closed without a closing time + {"pool_amount_sats": -1}, + {"pool_amount_sats": 100, "winner_amount_sats": 80, "fee_amount_sats": 30}, # pays out more than the pool + ], +) +def test_round_refuses_inconsistent_rows(kwargs): + assert refused(lambda: make_round(**kwargs)) + + +def test_a_split_equal_to_the_pool_is_accepted(): + make_round(status="closed", closed_at=timezone.now(), pool_amount_sats=100, + winner_amount_sats=70, fee_amount_sats=30) + + +# --- Participation ----------------------------------------------------------------------------- + + +def test_one_bet_per_player_per_round(): + """ADR-15.""" + round_, user = make_round(), make_user() + Participation.objects.create(round=round_, user=user, bet_amount_sats=10 * PLM) + assert refused(lambda: Participation.objects.create(round=round_, user=user, bet_amount_sats=10 * PLM)) + + +def test_the_same_player_can_bet_in_different_rounds(): + user = make_user() + first = make_round() + Participation.objects.create(round=first, user=user, bet_amount_sats=PLM) + first.status, first.closed_at = "closed", timezone.now() + first.save() + Participation.objects.create(round=make_round(), user=user, bet_amount_sats=PLM) + + +def test_draw_positions_are_unique_within_a_round(): + """DAT-66.""" + round_ = make_round() + now = timezone.now() + a, b = make_user("a"), make_user("b") + Participation.objects.create(round=round_, user=a, bet_amount_sats=PLM, status="confirmed", + confirmed_at=now, draw_position=0) + assert refused(lambda: Participation.objects.create( + round=round_, user=b, bet_amount_sats=PLM, status="confirmed", confirmed_at=now, draw_position=0)) + + +def test_unpositioned_participants_do_not_collide(): + round_ = make_round() + for name in ("a", "b", "c"): + Participation.objects.create(round=round_, user=make_user(name), bet_amount_sats=PLM) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"bet_amount_sats": 0}, + {"status": "bogus"}, + {"status": "confirmed"}, # confirmed without a confirmation time + {"draw_position": 0}, # a position for a participant that is not confirmed + ], +) +def test_participation_refuses_inconsistent_rows(kwargs): + base = {"round": make_round(), "user": make_user(), "bet_amount_sats": PLM} + assert refused(lambda: Participation.objects.create(**{**base, **kwargs})) + + +# --- Movement ---------------------------------------------------------------------------------- + + +def test_the_sign_follows_the_kind(): + """DAT-78: money in is positive, money out is negative.""" + user, round_ = make_user(), make_round() + now = timezone.now() + Movement.objects.create(user=user, kind="deposit", amount_sats=PLM, status="confirmed", confirmed_at=now) + Movement.objects.create(user=user, kind="bet", amount_sats=-PLM, round=round_) + Movement.objects.create(user=user, kind="withdrawal", amount_sats=-PLM) + Movement.objects.create(user=user, kind="win", amount_sats=PLM, round=round_) + Movement.objects.create(user=user, kind="refund", amount_sats=PLM, round=round_) + assert refused(lambda: Movement.objects.create(user=user, kind="deposit", amount_sats=-PLM)) + assert refused(lambda: Movement.objects.create(user=user, kind="withdrawal", amount_sats=PLM)) + assert refused(lambda: Movement.objects.create(user=user, kind="bet", amount_sats=PLM, round=round_)) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"kind": "deposit", "amount_sats": 0}, + {"kind": "bogus", "amount_sats": 1}, + {"kind": "deposit", "amount_sats": 1, "status": "bogus"}, + {"kind": "bet", "amount_sats": -1}, # a bet always belongs to a round + {"kind": "win", "amount_sats": 1}, + {"kind": "deposit", "amount_sats": 1, "status": "confirmed"}, # no confirmation time + ], +) +def test_movement_refuses_inconsistent_rows(kwargs): + assert refused(lambda: Movement.objects.create(user=make_user(), **kwargs)) + + +def test_the_same_request_id_is_the_same_operation(): + """WEB-23, DAT-78: a repeated key from the same player cannot create a second line.""" + user, other, key = make_user(), make_user("luigi"), uuid4() + Movement.objects.create(user=user, kind="deposit", amount_sats=PLM, request_id=key) + assert refused(lambda: Movement.objects.create(user=user, kind="deposit", amount_sats=PLM, request_id=key)) + Movement.objects.create(user=other, kind="deposit", amount_sats=PLM, request_id=key) # another player: fine + + +def test_movements_without_a_request_id_do_not_collide(): + user = make_user() + for _ in range(3): + Movement.objects.create(user=user, kind="deposit", amount_sats=PLM) + + +def test_amounts_are_integers_only(): + """WEB-04, DAT-01: the column stores whole minimal units.""" + user = make_user() + movement = Movement.objects.create(user=user, kind="deposit", amount_sats=10 * PLM) + movement.refresh_from_db() + assert isinstance(movement.amount_sats, int) and movement.amount_sats == 1_000_000_000 + + +# --- ChainTransaction -------------------------------------------------------------------------- + + +def test_txids_are_unique_but_may_be_absent(): + user = make_user() + ChainTransaction.objects.create(kind="withdrawal", user=user) + ChainTransaction.objects.create(kind="withdrawal", user=user) + ChainTransaction.objects.create(kind="withdrawal", user=user, current_txid="a" * 64) + assert refused(lambda: ChainTransaction.objects.create(kind="withdrawal", user=user, current_txid="a" * 64)) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"kind": "bogus"}, + {"kind": "withdrawal", "status": "bogus"}, + {"kind": "withdrawal", "status": "confirmed"}, + {"kind": "withdrawal", "status": "failed"}, # a failure always carries its reason + {"kind": "bet"}, # a bet without a player + {"kind": "payout"}, # a payout without a round + ], +) +def test_chain_transaction_refuses_inconsistent_rows(kwargs): + user = make_user() + kwargs = {"user": user, **kwargs} if kwargs["kind"] == "withdrawal" else kwargs + assert refused(lambda: ChainTransaction.objects.create(**kwargs)) + + +def test_a_failed_transaction_with_its_reason_is_accepted(): + ChainTransaction.objects.create(kind="withdrawal", user=make_user(), status="failed", + failed_at=timezone.now(), failure_reason="refused: inputs spent") + + +def test_a_payout_links_to_its_round(): + round_ = make_round() + payout = ChainTransaction.objects.create(kind="payout", round=round_, current_txid="b" * 64) + round_.payout_transaction = payout + round_.save() + assert Round.objects.get().payout_transaction_id == payout.pk + + +# --- Money is never deleted -------------------------------------------------------------------- + + +def test_rows_that_carry_money_cannot_be_deleted_with_their_owner(): + """DAT-76: every foreign key is PROTECT.""" + from django.db.models import ProtectedError + + user = make_user() + Movement.objects.create(user=user, kind="deposit", amount_sats=PLM) + with pytest.raises(ProtectedError): + user.delete() + + +# --- Audit ------------------------------------------------------------------------------------- + + +def test_record_appends_a_row_with_actor_reason_and_outcome(): + """AUD-47: who, when, what, why and with what outcome.""" + staff = make_user("operatore") + entry = audit.record("lottery_paused", actor=staff, reason="manutenzione", subject_type="config", + subject_id=1, payload={"scope": "after_round"}) + entry.refresh_from_db() + assert (entry.actor, entry.actor_label, entry.action) == (staff, "operatore", "lottery_paused") + assert (entry.reason, entry.outcome, entry.subject_id) == ("manutenzione", "ok", "1") + assert entry.payload == {"scope": "after_round"} and entry.created_at <= timezone.now() + + +def test_automatic_actions_are_attributed_to_the_system(): + entry = audit.record("round_opened") + assert entry.actor is None and entry.actor_label == "system" + + +def test_the_actor_name_survives_a_rename(): + staff = make_user("operatore") + entry = audit.record("x", actor=staff) + staff.username = "altro" + staff.save() + entry.refresh_from_db() + assert entry.actor_label == "operatore" + + +def test_an_audit_row_cannot_be_changed_through_the_model(): + entry = audit.record("x") + entry.reason = "rewritten" + with pytest.raises(AuditEntryImmutable): + entry.save() + with pytest.raises(AuditEntryImmutable): + entry.delete() + with pytest.raises(AuditEntryImmutable): + AuditEntry.objects.all().update(reason="rewritten") + with pytest.raises(AuditEntryImmutable): + AuditEntry.objects.all().delete() + + +def test_an_audit_row_cannot_be_changed_with_raw_sql_either(): + """AUD-47: the database refuses, not only the model.""" + audit.record("x") + from django.db import DatabaseError + + with connection.cursor() as cursor: + with pytest.raises(DatabaseError, match="append-only"): + with transaction.atomic(): + cursor.execute("UPDATE lottery_auditentry SET reason = 'rewritten'") + with pytest.raises(DatabaseError, match="append-only"): + with transaction.atomic(): + cursor.execute("DELETE FROM lottery_auditentry") + assert AuditEntry.objects.count() == 1 + + +def test_an_outcome_must_be_known(): + assert refused(lambda: audit.record("x", outcome="maybe")) + for outcome in ("ok", "denied", "error"): + audit.record("x", outcome=outcome) + + +def test_the_audit_is_written_in_the_same_transaction_as_the_change(): + """ADR-53: if the change rolls back, so does its trace.""" + with pytest.raises(RuntimeError): + with transaction.atomic(): + audit.record("lottery_paused") + raise RuntimeError("boom") + assert AuditEntry.objects.count() == 0 + + +def test_round_timestamps_are_timezone_aware(): + """DAT-02: UTC everywhere.""" + round_ = make_round() + assert round_.opened_at.tzinfo is not None + assert abs(timezone.now() - round_.opened_at) < timedelta(seconds=5)