B4: chain tables, HD index assignment and signing key reserved to the worker (DAT-81..84, ARC-78)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 15:53:50 +01:00
1 parent 0092596b07
commit f1d09075a1
18 files changed
+741 -8

No files matched your search

+123
View File
@@ -11,6 +11,8 @@ 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
@@ -420,3 +422,124 @@ class Report(models.Model):
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})"