Files
plm-lottery/apps/lottery/simulation.py
T

70 lines
2.9 KiB
Python
Raw Normal View History

"""The simulated chain and its confirmations (ADR-59, roadmap A4).
A chain that exists only in time: block `h` is the one produced `h` block-intervals after a fixed epoch,
and its hash is a pure function of `h`. Nothing is stored, so a restart changes nothing. Bets, deposits and
payouts of the simulated ledger confirm a few seconds after they are made (`settle`).
"""
import hashlib
from datetime import datetime, timedelta, timezone
from django.conf import settings
from django.utils import timezone as dj_timezone
from .models import ChainTransaction, Movement, Participation, Round
EPOCH = datetime(2026, 1, 1, tzinfo=timezone.utc)
BASE_HEIGHT = 1000
def simulated_block_hash(height: int) -> str:
return hashlib.sha256(f"simulated-block:{height}".encode()).hexdigest()
class SimulatedChain:
"""What the round engine asks of a chain: where the tip is, and the hash of a block at a height."""
def tip_height(self, now: datetime | None = None) -> int:
now = now or dj_timezone.now()
return BASE_HEIGHT + int((now - EPOCH).total_seconds() // settings.SIMULATED_BLOCK_SECONDS)
def agreed_block_hash(self, height: int, now: datetime | None = None) -> str | None:
"""The hash of the block at exactly `height`, or None while it does not exist yet (RND-16)."""
if height > self.tip_height(now):
return None
return simulated_block_hash(height)
def settle(now: datetime | None = None) -> int:
"""Confirm what has been waiting long enough. Returns how many operations were confirmed."""
from .ledger import SimulatedLedger
now = now or dj_timezone.now()
cutoff = now - timedelta(seconds=settings.SIMULATED_CONFIRM_SECONDS)
ledger, confirmed = SimulatedLedger(), 0
for movement in Movement.objects.filter(
kind=Movement.Kind.DEPOSIT, status=Movement.Status.PENDING, created_at__lte=cutoff
):
ledger.confirm_deposit(movement)
confirmed += 1
for chain_tx in ChainTransaction.objects.filter(
status=ChainTransaction.Status.PENDING, broadcast_at__lte=cutoff
):
if chain_tx.kind == ChainTransaction.Kind.BET:
participation = Participation.objects.filter(bet_txid=chain_tx.current_txid).first()
if participation is not None:
ledger.confirm_bet(participation)
confirmed += 1
elif chain_tx.kind == ChainTransaction.Kind.PAYOUT:
round_ = Round.objects.filter(payout_transaction=chain_tx).first()
if round_ is not None:
ledger.confirm_payout(round_.pk)
confirmed += 1
return confirmed
def simulated_address(user) -> str:
"""A stable, pseudonymous address for a participant in the public proof (WEB-12): derived from the
account id, it reveals no username. The real HD address replaces it in phase B (roadmap B4)."""
return "rplm1sim" + hashlib.sha256(f"simulated-address:{user.pk}".encode()).hexdigest()[:32]