A8: public results, reproducible proof, guide and rules (WEB-12, WEB-13, RND-37)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 14:49:47 +01:00
1 parent 42e5e33371
commit 58d1a38ac0
15 files changed
+454 -10

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
"""A8 — public results, proof, guide and rules: WEB-12, WEB-13, RND-14..RND-20, RND-37, DAT-65."""
import hashlib
import re
from datetime import timedelta
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from plm_engine.draw import draw_index, draw_seed, participants_hash, server_seed_commitment
from apps.lottery import lifecycle
from apps.lottery.addresses import participant_address
from apps.lottery.ledger import SimulatedLedger
from apps.lottery.models import LotteryConfig, Round
from apps.lottery.proof import round_proof
from apps.lottery.simulation import SimulatedChain
pytestmark = pytest.mark.django_db
ledger = SimulatedLedger()
NAMES = ["marta_rossi", "luca_bianchi", "giorgio_verdi"]
class FakeChain:
tip = 1000
def tip_height(self, now=None):
return self.tip
def agreed_block_hash(self, height, now=None):
return "cd" * 32
def finished_round(names=NAMES, *, confirm_payout=True):
"""A round played to the end with real lifecycle code: open, bets, close, draw, pay."""
t0 = timezone.now()
round_ = lifecycle.open_new_round_if_needed(t0)
for name in names:
user = get_user_model().objects.create_user(name, password="x" * 12)
ledger.deposit(user, round_.bet_amount_sats)
ledger.confirm_bet(ledger.place_bet(user, round_.pk, request_id=uuid4()).obj)
later = t0 + timedelta(seconds=round_.duration_seconds + 1)
chain = FakeChain()
lifecycle.tick(now=later, chain=chain) # closing, then drawing: waits for the block that does not exist yet
chain.tip += 10
lifecycle.tick(now=later, chain=chain) # draw, payout created (or closed, with nobody in it)
round_.refresh_from_db()
if confirm_payout and round_.payout_transaction_id:
ledger.confirm_payout(round_.pk)
lifecycle.tick(now=later, chain=chain)
round_.refresh_from_db()
return round_
def test_the_proof_recomputes_the_winner_from_public_data_alone():
"""WEB-12: with only the public proof, a stranger gets the same winner the platform paid."""
round_ = finished_round()
p = round_proof(round_)
assert round_.status == "closed" and p["checks"] == {
"commitment": True, "order": True, "fingerprint": True, "winner": True}
# Recompute from the proof dict only, using the documented steps (no database object).
assert hashlib.sha256(bytes.fromhex(p["server_seed"])).hexdigest() == p["server_seed_hash"]
rows = [(r["txid"], r["vout"], r["address"]) for r in p["participants"]]
assert participants_hash(rows) == p["participants_hash"]
seed = int.from_bytes(hashlib.sha256(
bytes.fromhex(p["server_seed"]) + bytes.fromhex(p["draw_block_hash"]) + bytes.fromhex(p["participants_hash"])
).digest(), "big")
assert p["seed"] == f"{seed:064x}"
winner = p["participants"][seed % len(rows)]
assert winner["address"] == p["winner_address"] == participant_address(round_.winner)
def test_the_proof_page_and_json_show_the_same_winner_without_any_username(client):
round_ = finished_round()
page = client.get(reverse("web:result", args=[round_.pk]))
data = client.get(reverse("web:result-proof", args=[round_.pk]))
assert page.status_code == data.status_code == 200
body = page.content.decode() + data.content.decode()
for name in NAMES:
assert name not in body # WEB-12: no username anywhere
assert data.json()["winner_address"] in page.content.decode()
assert "Pagamento <strong>confermato</strong>" in page.content.decode()
assert page.content.decode().count('data-ok="1"') == 4 and 'data-ok="0"' not in page.content.decode()
def test_results_list_shows_only_closed_rounds_and_no_username(client):
done = finished_round()
page = client.get(reverse("web:results")).content.decode()
assert f'href="{reverse("web:result", args=[done.pk])}"' in page
assert not any(n in page for n in NAMES)
open_round = lifecycle.open_new_round_if_needed(timezone.now() + timedelta(hours=1)) # past the cooldown
assert open_round is not None and f'href="{reverse("web:result", args=[open_round.pk])}"' not in client.get(reverse("web:results")).content.decode()
def test_the_payout_is_confirmed_only_when_it_is(client):
round_ = finished_round(confirm_payout=False)
assert round_.status == "paying_out"
html = client.get(reverse("web:result", args=[round_.pk])).content.decode()
assert "in attesa di conferma" in html and "Pagamento <strong>confermato</strong>" not in html
def test_an_open_round_publishes_only_the_commitment_and_never_the_secret(client):
"""RND-34, RND-37: before the draw the secret stays hidden; the missing fields say so."""
round_ = lifecycle.open_new_round_if_needed(timezone.now())
p = client.get(reverse("web:result-proof", args=[round_.pk])).json()
assert p["server_seed_hash"] == round_.server_seed_hash
assert p["server_seed"] is None and p["draw_block_hash"] is None and p["participants"] == [] and p["checks"] is None
assert round_.server_seed_enc not in str(p)
html = client.get(reverse("web:result", args=[round_.pk])).content.decode()
assert "non ancora disponibile" in html and "L'estrazione non è ancora avvenuta" in html
def test_a_round_nobody_joined_says_so(client):
round_ = finished_round(names=[])
assert round_.status == "closed" and round_.winner_id is None
html = client.get(reverse("web:result", args=[round_.pk])).content.decode()
assert "Nessun partecipante" in html and "Vincitore:" not in html
assert round_proof(round_)["checks"] == {"commitment": True}
def test_an_unknown_round_is_a_404(client):
assert client.get(reverse("web:result", args=[999])).status_code == 404
assert client.get(reverse("web:result-proof", args=[999])).status_code == 404
def test_tampering_with_the_stored_list_fails_the_recomputation():
"""The checks are real: a changed winner or fingerprint shows as failed instead of being rubber-stamped."""
round_ = finished_round()
other = get_user_model().objects.exclude(pk=round_.winner_id).first()
Round.objects.filter(pk=round_.pk).update(winner=other)
assert round_proof(Round.objects.get(pk=round_.pk))["checks"]["winner"] is False
Round.objects.filter(pk=round_.pk).update(participants_hash="00" * 32)
assert round_proof(Round.objects.get(pk=round_.pk))["checks"]["fingerprint"] is False
def test_public_pages_need_no_login_and_proof_is_not_cached(client):
round_ = finished_round()
for name, args in [("web:results", []), ("web:guide", []), ("web:rules", []), ("web:result", [round_.pk])]:
assert client.get(reverse(name, args=args)).status_code == 200
assert "no-store" in client.get(reverse("web:result-proof", args=[round_.pk]))["Cache-Control"]
def test_guide_and_rules_use_the_live_terms_and_do_not_promise_instant_credit(client):
"""WEB-13: figures come from the configuration; the wording matches the player area."""
LotteryConfig.get()
LotteryConfig.objects.filter(pk=1).update(bet_amount_sats=25 * 100_000_000, round_duration_seconds=900)
guide = client.get(reverse("web:guide")).content.decode()
rules = client.get(reverse("web:rules")).content.decode()
assert "25 PLM" in guide and "25 PLM" in rules and "15 minuti" in rules
assert "70%" in rules and "30%" in rules and "commissioni" in rules.lower() and "conferme" in rules
assert "l'accredito non è immediato" in guide
assert not re.search(r"accredito immediato|istantane", guide + rules, re.I)
def test_home_and_menu_link_to_the_public_pages(client):
html = client.get(reverse("web:home")).content.decode()
for name in ("web:results", "web:guide", "web:rules"):
assert f'href="{reverse(name)}"' in html