"""A4 — round lifecycle, commit-reveal draw and simulated chain: RND-13..RND-21, RND-33..RND-36, ADR-22, ADR-23, ADR-24, ADR-29, ADR-57, ADR-59, DAT-61, DAT-64, DAT-65.""" import hashlib from datetime import timedelta from uuid import uuid4 import pytest from django.contrib.auth import get_user_model from django.utils import timezone from plm_engine.draw import draw_index, draw_seed, participants_hash, server_seed_commitment from apps.lottery import audit, lifecycle, simulation from apps.lottery.addresses import participant_address from apps.lottery.balances import balance_of from apps.lottery.ledger import SimulatedLedger from apps.lottery.models import AuditEntry, LotteryConfig, Movement, Participation, Round from apps.lottery.seedbox import decrypt_seed, encrypt_seed from apps.lottery.simulation import SimulatedChain, simulated_block_hash PLM = 100_000_000 BET = 10 * PLM pytestmark = pytest.mark.django_db ledger = SimulatedLedger() class FakeChain: """A chain the test drives by hand.""" def __init__(self, tip=1000): self.tip, self.agree, self.hashes = tip, True, {} def tip_height(self, now=None): return self.tip def agreed_block_hash(self, height, now=None): if not self.agree or height > self.tip: return None return self.hashes.get(height, "ab" * 32) def make_user(name): return get_user_model().objects.create_user(name, password="x" * 12) def players(round_, names, *, confirm=True): """Fund each player and place their bet; optionally confirm it.""" users = [] for name in names: user = make_user(name) ledger.deposit(user, round_.bet_amount_sats) bet = ledger.place_bet(user, round_.pk, request_id=uuid4()).obj if confirm: ledger.confirm_bet(bet) users.append(user) return users def actions(): return list(AuditEntry.objects.order_by("id").values_list("action", flat=True)) @pytest.fixture def t0(): return timezone.now() def deadline(round_): return round_.opened_at + timedelta(seconds=round_.duration_seconds) # --- opening ----------------------------------------------------------------------------------- def test_the_first_tick_opens_a_round_with_a_public_commitment(t0): """RND-34: the hash of the secret is public from the opening; the secret is not.""" round_ = lifecycle.open_new_round_if_needed(t0) assert round_.status == "open" and round_.opened_at == t0 assert len(round_.server_seed_hash) == 64 and round_.server_seed is None secret = decrypt_seed(round_.server_seed_enc) assert server_seed_commitment(secret) == round_.server_seed_hash assert secret not in round_.server_seed_enc assert actions() == ["round_opened"] def test_only_one_round_is_ever_open(t0): first = lifecycle.open_new_round_if_needed(t0) assert lifecycle.open_new_round_if_needed(t0).pk == first.pk assert Round.objects.count() == 1 def test_a_round_copies_its_rules_when_it_opens(t0): """DAT-61, ADR-10: a later edit of the configuration applies from the next round.""" config = LotteryConfig.get() config.bet_amount_sats, config.round_duration_seconds, config.max_round_pool_sats = 7 * PLM, 90, 100 * PLM config.draw_confirmations, config.round_cooldown_seconds, config.fee_address = 5, 11, " rplm1fee " config.save() round_ = lifecycle.open_new_round_if_needed(t0) config.bet_amount_sats, config.round_duration_seconds = 99 * PLM, 5 config.save() round_.refresh_from_db() assert (round_.bet_amount_sats, round_.duration_seconds, round_.max_round_pool_sats) == (7 * PLM, 90, 100 * PLM) assert (round_.draw_confirmations, round_.cooldown_seconds, round_.fee_address) == (5, 11, "rplm1fee") def test_a_real_ledger_needs_a_fee_address_to_open_a_round(settings, t0, tmp_path): """ADR-29: a round that cannot pay its commission is not opened. The simulated ledger needs none. A real one also derives the round's pool address from the public key (DAT-60), so it needs that configured.""" from apps.lottery import keys assert lifecycle.rounds_can_open(LotteryConfig.get()) settings.LEDGER_BACKEND = "chain" settings.PLM_ACCOUNT_XPUB = keys.generate_keys(tmp_path / "keys", settings.PLM_PROFILE) assert lifecycle.open_new_round_if_needed(t0) is None config = LotteryConfig.get() config.fee_address = "rplm1fee" config.save() opened = lifecycle.open_new_round_if_needed(t0) assert opened is not None and opened.pool_address.startswith("rplm1") # its own address, from the public key def test_the_pause_after_the_round_stops_only_the_next_one(t0): """ADR-57: «Pausa dopo il round in corso».""" config = LotteryConfig.get() config.pause_after_round = True config.save() assert lifecycle.open_new_round_if_needed(t0) is None and Round.objects.count() == 0 # --- the betting window ------------------------------------------------------------------------ def test_the_round_closes_for_bets_at_its_own_deadline(t0): """ADR-23.""" round_ = lifecycle.open_new_round_if_needed(t0) assert lifecycle.tick(now=deadline(round_) - timedelta(seconds=1), chain=FakeChain()) == 0 assert Round.objects.get().status == "open" lifecycle.tick(now=deadline(round_), chain=FakeChain()) assert Round.objects.get().status in ("closing", "closed") def test_the_deadline_is_the_rounds_own_not_the_live_config(t0): round_ = lifecycle.open_new_round_if_needed(t0) config = LotteryConfig.get() config.round_duration_seconds = 1 config.save() lifecycle.tick(now=t0 + timedelta(seconds=30), chain=FakeChain()) assert Round.objects.get(pk=round_.pk).status == "open" def test_closing_waits_for_every_bet_in_flight(t0): """RND-13: a bet placed before the deadline is not lost because it confirmed after it.""" round_ = lifecycle.open_new_round_if_needed(t0) (user,) = players(round_, ["a"], confirm=False) at_deadline = deadline(round_) lifecycle.tick(now=at_deadline, chain=FakeChain()) assert Round.objects.get().status == "closing" # still waiting: the bet is pending ledger.confirm_bet(Participation.objects.get()) lifecycle.tick(now=at_deadline, chain=FakeChain()) assert Round.objects.get().status == "drawing" def test_a_round_nobody_joined_closes_and_reveals_its_secret(t0): """DAT-64: with nothing drawn the secret has nothing left to protect.""" round_ = lifecycle.open_new_round_if_needed(t0) lifecycle.tick(now=deadline(round_), chain=FakeChain()) round_.refresh_from_db() assert round_.status == "closed" and round_.closed_at is not None assert server_seed_commitment(round_.server_seed) == round_.server_seed_hash assert actions() == ["round_opened", "round_closed"] # --- committing to the draw -------------------------------------------------------------------- def committed_round(t0, names=("c", "a", "b"), tip=1000, reverse_txids=False): round_ = lifecycle.open_new_round_if_needed(t0) users = players(round_, list(names)) if reverse_txids: # first to bet gets the highest txid, so id order and txid order are opposite for i, bet in enumerate(Participation.objects.order_by("id")): Participation.objects.filter(pk=bet.pk).update(bet_txid=f"{len(names) - i:064x}") chain = FakeChain(tip) lifecycle.tick(now=deadline(round_), chain=chain) round_.refresh_from_db() return round_, users, chain def test_the_list_is_ordered_by_bet_txid_and_fingerprinted(t0): """RND-14, DAT-65: public data, no ties, never a server-side timestamp.""" round_, users, _ = committed_round(t0, reverse_txids=True) assert round_.status == "drawing" ordered = list(Participation.objects.filter(round=round_).order_by("draw_position").select_related("user")) assert [p.draw_position for p in ordered] == [0, 1, 2] assert [p.bet_txid for p in ordered] == sorted(p.bet_txid for p in ordered) assert [p.user.username for p in ordered] == ["b", "a", "c"] # last to bet, first in the list expected = participants_hash([(p.bet_txid, p.bet_vout, participant_address(p.user)) for p in ordered]) assert round_.participants_hash == expected assert round_.pool_amount_sats == 3 * BET def test_the_draw_block_is_after_the_close(t0): """RND-19: `draw_height` is the height known at closing plus one — a block that did not exist yet.""" round_, _, _ = committed_round(t0, tip=1234) assert round_.draw_height == 1235 audit_row = AuditEntry.objects.get(action="draw_committed") assert audit_row.payload["draw_height"] == 1235 and audit_row.payload["participants"] == 3 def test_the_proof_does_not_expose_usernames(t0): """WEB-12: participants appear under a pseudonymous address only.""" round_, users, _ = committed_round(t0, names=("mariorossi", "lucia")) for user in users: assert user.username not in participant_address(user) assert participant_address(user) == participant_address(user) # stable: the same player, the same entry assert len({participant_address(u) for u in users}) == len(users) published = AuditEntry.objects.get(action="draw_committed").payload assert "mariorossi" not in str(published) and "lucia" not in str(published) # --- the draw ---------------------------------------------------------------------------------- def test_the_draw_waits_for_the_confirmations_of_the_block(t0): """RND-15: the chain needs `draw_confirmations` blocks from `draw_height`.""" round_, _, chain = committed_round(t0, tip=1000) # draw_height 1001, 3 confirmations -> tip 1003 chain.tip = 1002 lifecycle.tick(now=deadline(round_), chain=chain) assert Round.objects.get().status == "drawing" chain.tip = 1003 lifecycle.tick(now=deadline(round_), chain=chain) assert Round.objects.get().status in ("paying_out", "closed") def test_a_block_that_is_not_agreed_is_asked_again_never_replaced(t0): """RND-16: nobody can pick another block to seed the draw; a missing agreement only delays it.""" round_, _, chain = committed_round(t0) chain.tip, chain.agree = 1010, False for _ in range(3): assert lifecycle.tick(now=deadline(round_), chain=chain) == 0 assert Round.objects.get().winner_id is None chain.agree = True lifecycle.tick(now=deadline(round_), chain=chain) round_.refresh_from_db() assert round_.draw_height == 1001 and round_.draw_block_hash == "ab" * 32 # the same block as always def test_the_winner_is_recomputable_from_the_public_proof(t0): """RND-17, RND-18: anyone can redo the draw once the secret is revealed.""" round_, users, chain = committed_round(t0) chain.tip = 1003 chain.hashes[1001] = "cd" * 32 lifecycle.tick(now=deadline(round_), chain=chain) round_.refresh_from_db() ordered = list(Participation.objects.filter(round=round_).order_by("draw_position")) seed = draw_seed(round_.server_seed, "cd" * 32, round_.participants_hash) assert round_.winner_id == ordered[draw_index(seed, len(ordered))].user_id assert server_seed_commitment(round_.server_seed) == round_.server_seed_hash assert round_.draw_block_hash == "cd" * 32 and round_.status == "paying_out" payload = AuditEntry.objects.get(action="winner_drawn").payload assert payload["server_seed"] == round_.server_seed and payload["block_hash"] == "cd" * 32 def test_the_secret_is_revealed_only_with_the_winner(t0): """RND-18, DAT-64.""" round_, _, chain = committed_round(t0) assert Round.objects.get().server_seed is None # committed, drawing, not yet revealed chain.tip = 1003 lifecycle.tick(now=deadline(round_), chain=chain) round_.refresh_from_db() assert round_.server_seed and round_.winner_id def test_an_interrupted_draw_gives_the_same_winner(t0, monkeypatch): """RND-36: a failure mid-draw leaves nothing behind, and the resumed draw picks the same winner.""" round_, _, chain = committed_round(t0) chain.tip = 1003 def explode(action, **kwargs): if action == "winner_drawn": raise RuntimeError("database locked") return real(action, **kwargs) real = audit.record monkeypatch.setattr(audit, "record", explode) with pytest.raises(RuntimeError): lifecycle.tick(now=deadline(round_), chain=chain) interrupted = Round.objects.get() assert (interrupted.status, interrupted.winner_id, interrupted.server_seed) == ("drawing", None, None) monkeypatch.setattr(audit, "record", real) lifecycle.tick(now=deadline(round_), chain=chain) resumed = Round.objects.get() ordered = list(Participation.objects.filter(round=resumed).order_by("draw_position")) expected = ordered[draw_index(draw_seed(decrypt_seed(resumed.server_seed_enc), "ab" * 32, resumed.participants_hash), len(ordered))] assert resumed.winner_id == expected.user_id def test_a_tampered_list_or_secret_is_refused(t0): """RND-14, RND-34: the list must match its fingerprint and the secret its commitment.""" round_, _, chain = committed_round(t0) chain.tip = 1003 Round.objects.filter(pk=round_.pk).update(participants_hash="0" * 64) with pytest.raises(RuntimeError, match="fingerprint"): lifecycle.tick(now=deadline(round_), chain=chain) Round.objects.filter(pk=round_.pk).update(participants_hash=round_.participants_hash, server_seed_hash="1" * 64) with pytest.raises(RuntimeError, match="commitment"): lifecycle.tick(now=deadline(round_), chain=chain) assert Round.objects.get().winner_id is None def test_a_tick_that_changes_nothing_writes_nothing(t0): round_, _, chain = committed_round(t0) before = AuditEntry.objects.count() assert lifecycle.tick(now=deadline(round_), chain=chain) == 0 # still waiting for blocks assert AuditEntry.objects.count() == before # --- payout and cooldown ----------------------------------------------------------------------- def drawn_round(t0, names=("a", "b", "c", "d")): round_ = lifecycle.open_new_round_if_needed(t0) users = players(round_, list(names)) chain = FakeChain(1000) lifecycle.tick(now=deadline(round_), chain=chain) chain.tip = 1003 lifecycle.tick(now=deadline(round_), chain=chain) round_.refresh_from_db() return round_, users, chain def test_the_winner_is_paid_70_percent_and_the_round_closes_when_it_confirms(t0): """RND-21: paying_out until the payout confirms, then closed.""" round_, users, chain = drawn_round(t0) assert round_.status == "paying_out" and round_.payout_transaction_id is not None assert (round_.winner_amount_sats, round_.fee_amount_sats) == (28 * PLM, 12 * PLM) win = Movement.objects.get(kind="win") assert win.user_id == round_.winner_id and win.status == "pending" assert balance_of(round_.winner).incoming_sats == 28 * PLM assert Round.objects.get().status == "paying_out" done = deadline(round_) + timedelta(minutes=5) simulation.settle(done) lifecycle.tick(now=done, chain=chain) round_.refresh_from_db() assert round_.status == "closed" and round_.closed_at == done assert balance_of(round_.winner).spendable_sats == 28 * PLM and balance_of(round_.winner).incoming_sats == 0 def test_the_next_round_opens_only_after_the_cooldown_it_announced(t0): """B-61: the gap of the closed round is the gap honoured, whatever the config says now.""" round_, _, chain = drawn_round(t0) done = deadline(round_) + timedelta(minutes=5) simulation.settle(done) lifecycle.tick(now=done, chain=chain) assert Round.objects.get().status == "closed" config = LotteryConfig.get() config.round_cooldown_seconds = 1 config.save() lifecycle.tick(now=done + timedelta(seconds=29), chain=chain) assert Round.objects.count() == 1 lifecycle.tick(now=done + timedelta(seconds=30), chain=chain) assert Round.objects.count() == 2 and Round.objects.latest("id").status == "open" def test_a_round_in_progress_finishes_even_if_the_lottery_is_paused(t0): """ADR-57: the pause after the round lets the current one close, draw and pay; no new one opens.""" round_ = lifecycle.open_new_round_if_needed(t0) players(round_, ["a", "b"]) config = LotteryConfig.get() config.pause_after_round = True config.save() chain = FakeChain(1000) lifecycle.tick(now=deadline(round_), chain=chain) chain.tip = 1003 lifecycle.tick(now=deadline(round_), chain=chain) done = deadline(round_) + timedelta(minutes=5) simulation.settle(done) lifecycle.tick(now=done, chain=chain) assert Round.objects.get().status == "closed" lifecycle.tick(now=done + timedelta(hours=1), chain=chain) assert Round.objects.count() == 1 # still paused config.pause_after_round = False config.save() lifecycle.tick(now=done + timedelta(hours=1), chain=chain) assert Round.objects.count() == 2 # --- the whole thing, on the simulated chain --------------------------------------------------- def test_a_whole_round_on_the_simulated_chain(settings, t0): """The first milestone: open -> bets -> close -> draw -> payout -> closed, money conserved, audit in order.""" settings.SIMULATED_BLOCK_SECONDS, settings.SIMULATED_CONFIRM_SECONDS = 10, 2 chain = SimulatedChain() lifecycle.tick(now=t0, chain=chain) round_ = Round.objects.get() users = players(round_, ["a", "b", "c"], confirm=False) now = t0 for _ in range(400): # 400 steps of 5 simulated seconds: far more than a round needs now += timedelta(seconds=5) simulation.settle(now) lifecycle.tick(now=now, chain=chain) if Round.objects.filter(status="open").exclude(pk=round_.pk).exists(): break round_.refresh_from_db() assert round_.status == "closed" assert Round.objects.filter(status="open").exclude(pk=round_.pk).exists() # the next one opened # the winner is exactly what the public proof says ordered = list(Participation.objects.filter(round=round_).order_by("draw_position")) seed = draw_seed(round_.server_seed, simulated_block_hash(round_.draw_height), round_.participants_hash) assert round_.winner_id == ordered[draw_index(seed, 3)].user_id assert round_.draw_height > simulation.BASE_HEIGHT # money: what players deposited is what they hold plus the platform's share held = sum(balance_of(u).spendable_sats for u in users) deposited = sum(Movement.objects.filter(kind="deposit").values_list("amount_sats", flat=True)) assert held + round_.fee_amount_sats == deposited assert round_.winner_amount_sats == 21 * PLM and round_.fee_amount_sats == 9 * PLM interesting = [a for a in actions() if a in ("round_opened", "draw_committed", "winner_drawn", "payout_created", "payout_confirmed", "round_closed")] assert interesting == ["round_opened", "draw_committed", "winner_drawn", "payout_created", "payout_confirmed", "round_closed", "round_opened"] # --- the simulated chain and its confirmations ------------------------------------------------- def test_the_simulated_chain_grows_with_time(settings, t0): settings.SIMULATED_BLOCK_SECONDS = 20 chain = SimulatedChain() later = chain.tip_height(t0 + timedelta(seconds=40)) assert later - chain.tip_height(t0) in (2,) # a block every 20 simulated seconds assert chain.tip_height(t0 + timedelta(seconds=19)) - chain.tip_height(t0) in (0, 1) def test_a_future_block_has_no_hash_and_a_past_one_always_the_same(t0): chain = SimulatedChain() tip = chain.tip_height(t0) assert chain.agreed_block_hash(tip + 1, t0) is None assert chain.agreed_block_hash(tip, t0) == simulated_block_hash(tip) == chain.agreed_block_hash(tip, t0) assert simulated_block_hash(tip) != simulated_block_hash(tip - 1) def test_settling_confirms_only_what_has_waited_long_enough(settings): settings.SIMULATED_CONFIRM_SECONDS = 5 round_ = Round.objects.create() (user,) = players(round_, ["a"], confirm=False) pending_deposit = ledger.deposit(make_user("b"), PLM, confirmed=False).obj now = timezone.now() assert simulation.settle(now + timedelta(seconds=4)) == 0 assert Participation.objects.get().status == "pending" assert simulation.settle(now + timedelta(seconds=6)) == 2 assert Participation.objects.get().status == "confirmed" pending_deposit.refresh_from_db() assert pending_deposit.status == "confirmed" def test_the_round_secret_needs_the_right_key(settings): token = encrypt_seed("ab" * 32) assert decrypt_seed(token) == "ab" * 32 settings.SECRET_KEY = "another-key-" + "y" * 50 with pytest.raises(RuntimeError): decrypt_seed(token)