"""Services over the chain tables (roadmap B4): the HD index of a deposit address (DAT-81) and the versions of a transaction (DAT-83). Uniqueness is decided by the database, never by a read followed by a write (ARC-72).""" from django.conf import settings from django.db import IntegrityError, transaction from django.db.models import Max from plm_engine import hd from . import keys from .models import ChainTransaction, DepositAddress, TransactionVersion _ATTEMPTS = 20 class TxidConflict(Exception): """The txid already belongs to another platform transaction (DAT-83).""" def derive_deposit_address(index: int) -> str: """The address for an HD index: a pure function of the public key, the index and the network.""" return hd.user_address(keys.public_account_key(), index, settings.PLM_PROFILE) def assign_deposit_address(user) -> DepositAddress: """The player's deposit address; created on first use, the same one ever after (DAT-81). The index is the next after the highest assigned; if a concurrent assignment takes it first the unique index refuses ours and we take the next one.""" existing = DepositAddress.objects.filter(user=user).first() if existing is not None: return existing for _ in range(_ATTEMPTS): try: with transaction.atomic(): top = DepositAddress.objects.aggregate(top=Max("derivation_index"))["top"] index = 0 if top is None else top + 1 return DepositAddress.objects.create( user=user, derivation_index=index, address=derive_deposit_address(index), network=settings.PLM_NETWORK ) except IntegrityError: raced = DepositAddress.objects.filter(user=user).first() # the same player assigned twice at once if raced is not None: return raced raise RuntimeError("could not assign a deposit address: too many concurrent assignments") def register_version(tx: ChainTransaction, txid: str, raw_hex: str = "") -> TransactionVersion: """Record a txid of `tx` and make it the current one (DAT-83, TX-19). Idempotent for the same pair; a txid of another transaction is refused. One database transaction, so the version and `current_txid` agree.""" with transaction.atomic(): existing = TransactionVersion.objects.filter(txid=txid).first() if existing is not None: if existing.transaction_id != tx.pk: raise TxidConflict(f"{txid} belongs to transaction {existing.transaction_id}") version = existing else: version = TransactionVersion.objects.create(transaction=tx, txid=txid, raw_hex=raw_hex) if tx.current_txid != txid: tx.current_txid = txid if raw_hex: tx.raw_hex = raw_hex tx.save(update_fields=["current_txid", "raw_hex"]) return version