"""B5 — real deposits on the ORM: DEP-20..DEP-23, DAT-62, DAT-77, DAT-82, DAT-84.""" import pytest from django.contrib.auth import get_user_model from django.db import IntegrityError, transaction from apps.lottery import chain, deposits, keys from apps.lottery.balances import balance_of from apps.lottery.deposits import Observation, ScanResult, Seen from apps.lottery.models import AuditEntry, Deposit, LotteryConfig, Movement, TransactionVersion, Utxo, ChainTransaction pytestmark = pytest.mark.django_db User = get_user_model() PLM = 100_000_000 TXID = "ab" * 32 OTHER = "cd" * 32 class FakeChain: """The network phase, scripted: a tip, what each address lists, and which coins the 'servers' corroborate.""" def __init__(self, tip=1000): self.tip, self.entries, self.verified, self.coinbase, self.absent, self.silent = tip, {}, set(), set(), set(), set() self.policies = [] def observe(self, policy): self.policies.append(policy) result = ScanResult(self.tip, {}) for address in policy.addresses: if address in self.silent: result.addresses[address] = Observation(None) continue entries = self.entries.get(address, []) result.addresses[address] = Observation( entries, {o for o in self.verified}, {o for o in self.absent}, set(self.coinbase)) return result @pytest.fixture def player(settings, tmp_path): settings.PLM_ACCOUNT_XPUB = keys.generate_keys(tmp_path / "keys", settings.PLM_PROFILE) user = User.objects.create_user("mario", password="x" * 12) return user, chain.assign_deposit_address(user).address def coin(txid=TXID, vout=0, value=5 * PLM, height=995): return Seen(txid, vout, value, height) def scan(fake): return deposits.scan_deposits(fake) # --- DEP-21: thresholds ------------------------------------------------------------------------------ def test_a_deposit_is_credited_exactly_at_its_threshold(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=1000 - 5 + 1)] # 5 confirmations, the threshold is 6 fake.verified = {(TXID, 0)} assert scan(fake) == {"detected": 1, "credited": 0, "orphaned": 0, "reinstated": 0} assert balance_of(user).spendable_sats == 0 fake.tip = 1001 # 6 confirmations assert scan(fake)["credited"] == 1 assert balance_of(user).spendable_sats == 5 * PLM def test_the_threshold_is_the_configured_one(player): """DAT-77: the operator changes it and the next scan uses it.""" user, address = player config = LotteryConfig.get() config.deposit_confirmations = 2 config.save() fake = FakeChain() fake.entries[address] = [coin(height=999)] # 2 confirmations fake.verified = {(TXID, 0)} assert scan(fake)["credited"] == 1 def test_a_coinbase_needs_120(player): user, address = player fake = FakeChain(tip=2000) fake.coinbase = {TXID} fake.verified = {(TXID, 0)} fake.entries[address] = [coin(height=2000 - 118)] # 119 confirmations assert scan(fake)["credited"] == 0 fake.tip = 2001 # 120 assert scan(fake)["credited"] == 1 def test_the_change_of_our_own_transactions_is_spendable_but_never_a_deposit(player): """BET-30: the stake was taken from the balance when the bet was placed; its change coming back must not be credited.""" user, address = player tx = ChainTransaction.objects.create(kind="bet", user=user) chain.register_version(tx, TXID, "00") fake = FakeChain() fake.entries[address] = [coin(height=1000)] # one confirmation assert scan(fake) == {"detected": 0, "credited": 0, "orphaned": 0, "reinstated": 0} utxo = Utxo.objects.get() assert utxo.user == user and utxo.confirmed_height == 1000 and not Deposit.objects.exists() assert not Movement.objects.exists() and balance_of(user).spendable_sats == 0 scan(fake) # and once only assert Utxo.objects.count() == 1 def test_dust_and_mempool_coins_are_ignored(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(vout=0, value=293), coin(vout=1, height=0), coin(vout=2, height=-1)] assert scan(fake) == {"detected": 0, "credited": 0, "orphaned": 0, "reinstated": 0} assert not Utxo.objects.exists() and not Movement.objects.exists() # --- DEP-22: verified, idempotent ------------------------------------------------------------------------ def test_an_unverified_deposit_is_deferred_not_lost(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=900)] # deep enough, but nobody corroborated it scan(fake) assert balance_of(user).spendable_sats == 0 and Deposit.objects.get().status == "detected" fake.verified = {(TXID, 0)} assert scan(fake)["credited"] == 1 def test_scanning_twice_credits_once(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=900)] fake.verified = {(TXID, 0)} assert scan(fake)["credited"] == 1 assert scan(fake) == {"detected": 0, "credited": 0, "orphaned": 0, "reinstated": 0} assert Movement.objects.filter(kind="deposit").count() == 1 and balance_of(user).spendable_sats == 5 * PLM def test_the_credit_is_audited(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=900)] fake.verified = {(TXID, 0)} scan(fake) entry = AuditEntry.objects.get(action="deposit_credited") assert entry.actor_label == "worker" and entry.payload["amount_sats"] == 5 * PLM and entry.payload["threshold"] == 6 def test_the_database_refuses_a_second_deposit_for_the_same_output(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=900)] scan(fake) with pytest.raises(IntegrityError), transaction.atomic(): Utxo.objects.create(txid=TXID, vout=0, amount_sats=1, address=address) def test_silence_concludes_nothing(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=900)] fake.silent = {address} assert scan(fake) == {"detected": 0, "credited": 0, "orphaned": 0, "reinstated": 0} result = ScanResult(None, {address: Observation([coin(height=900)])}) # no usable tip: nothing is written either assert deposits.apply_observations(result, deposits.plan())["detected"] == 0 # --- DEP-23: waiting deposits ------------------------------------------------------------------------------ def test_a_waiting_deposit_shows_as_incoming(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=999)] scan(fake) balance = balance_of(user) assert (balance.spendable_sats, balance.incoming_sats) == (0, 5 * PLM) def test_a_vanished_waiting_deposit_is_orphaned_and_can_return(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=999)] scan(fake) fake.entries[address] = [] scan(fake) # gone, but the others did not confirm that: nothing changes assert Deposit.objects.get().status == "detected" fake.absent = {(TXID, 0)} assert scan(fake)["orphaned"] == 1 assert Deposit.objects.get().status == "orphaned" and balance_of(user).incoming_sats == 0 fake.entries[address], fake.absent = [coin(height=999)], set() assert scan(fake)["reinstated"] == 1 assert balance_of(user).incoming_sats == 5 * PLM def test_a_credited_deposit_is_left_alone_by_this_module(player): """What happens to a credited coin that later disappears is B7.""" user, address = player fake = FakeChain() fake.entries[address] = [coin(height=900)] fake.verified = {(TXID, 0)} scan(fake) fake.entries[address], fake.absent = [], {(TXID, 0)} assert scan(fake)["orphaned"] == 0 and Deposit.objects.get().status == "credited" def test_the_policy_names_what_the_network_phase_needs(player): user, address = player fake = FakeChain() fake.entries[address] = [coin(height=999)] scan(fake) scan(fake) # the second scan reads what the first one wrote policy = fake.policies[-1] assert policy.addresses == (address,) and policy.deposit_confirmations == 6 assert policy.waiting == {address: frozenset({(TXID, 0)})} # --- configuration (DAT-77, ELC-31) ---------------------------------------------------------------------- def test_the_operator_changes_the_threshold_from_the_admin_and_it_is_audited(client): admin = User.objects.create_superuser("boss", password="x" * 12) client.force_login(admin) config = LotteryConfig.get() data = {f: getattr(config, f) for f in ("fee_address", "bet_amount_sats", "round_duration_seconds", "round_cooldown_seconds", "draw_confirmations", "deposit_confirmations", "max_round_pool_sats", "fee_rate_sat_vb")} data["deposit_confirmations"] = 3 assert client.post("/admin/lottery/lotteryconfig/1/change/", data).status_code == 302 assert LotteryConfig.get().deposit_confirmations == 3 entry = AuditEntry.objects.get(action="config_changed") assert entry.actor == admin and entry.payload == {"changed": {"deposit_confirmations": [6, 3]}} @pytest.mark.parametrize("value", [0, 101]) def test_the_database_refuses_a_threshold_out_of_range(value): config = LotteryConfig.get() config.deposit_confirmations = value with pytest.raises(IntegrityError), transaction.atomic(): config.save() def _settings_import(**env): import os import subprocess import sys from pathlib import Path clean = {"PATH": os.environ["PATH"], "PYTHONPATH": str(Path(__file__).resolve().parents[2]), "DJANGO_SECRET_KEY": "k" * 60, "LEDGER_BACKEND": "chain", **env} return subprocess.run([sys.executable, "-c", "import config.settings as s; print(len(s.ELECTRUM_ENDPOINTS))"], cwd=Path(__file__).resolve().parents[2], env=clean, capture_output=True, text=True) def test_a_real_ledger_needs_servers_and_a_quorum(): assert "ELECTRUM_SERVERS" in _settings_import().stderr assert "three servers" in _settings_import(ELECTRUM_SERVERS="a:1,b:1").stderr assert _settings_import(ELECTRUM_SERVERS="a:1,b:1,c:1").stdout.strip() == "3" assert _settings_import(ELECTRUM_SERVERS="a:1", ELECTRUM_ALLOW_NO_QUORUM="true").stdout.strip() == "1" assert _settings_import(ELECTRUM_SERVERS="bad").returncode != 0 def test_no_quorum_is_refused_on_mainnet(): result = _settings_import(PLM_NETWORK="mainnet", PLM_MAINNET_CONFIRMED="yes", ELECTRUM_SERVERS="a:1", ELECTRUM_ALLOW_NO_QUORUM="true") assert result.returncode != 0 and "mainnet" in result.stderr