Files
plm-lottery/config/settings.py
T
davideandClaude Sonnet 5.5 1d4b53d778 A4: round lifecycle, commit-reveal draw and simulated chain (RND-41..44, ADR-57, ADR-59)
lifecycle.tick runs the round from open to closed one write-locked step at a
time, resumable from the database (an interrupted draw gives the same
winner). Draw primitives move to plm_engine.draw and are shared with the old
module. SimulatedChain and settle() stand in for blocks and confirmations;
the worker runs both every tick and opens the first round. The round secret
is stored encrypted and revealed with the winner; the proof exposes no
usernames. Mutation checks confirmed the wait for in-flight bets and the
txid ordering are caught by the tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 13:43:09 +01:00

162 lines
6.2 KiB
Python

"""Django settings (ADR-54, ADR-55, WEB-07).
Everything environment-specific comes from environment variables, so the same image
serves `http://localhost` today and a real domain later with configuration only.
"""
import os
from pathlib import Path
from django.core.exceptions import ImproperlyConfigured
BASE_DIR = Path(__file__).resolve().parent.parent
def _env_list(name: str) -> list[str]:
return [item.strip() for item in os.environ.get(name, "").split(",") if item.strip()]
DEBUG = os.environ.get("DJANGO_DEBUG", "false").lower() == "true"
# Like ADR-11 for the old server: refuse to start with an inadequate secret instead of
# running with a guessable one. DEBUG (local development without Docker) is exempt.
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "")
if not DEBUG and len(SECRET_KEY) < 50:
raise ImproperlyConfigured(
"DJANGO_SECRET_KEY must be at least 50 characters. Generate one with: "
"python -c \"import secrets; print(secrets.token_urlsafe(64))\""
)
if DEBUG and not SECRET_KEY:
SECRET_KEY = "insecure-development-key-" + "x" * 40
# WEB-07: `localhost` works out of the box; a domain is added by configuration only.
SITE_ADDRESS = os.environ.get("SITE_ADDRESS", "localhost")
ALLOWED_HOSTS = sorted({"localhost", "127.0.0.1", "[::1]", "web", SITE_ADDRESS, *_env_list("DJANGO_ALLOWED_HOSTS")})
CSRF_TRUSTED_ORIGINS = sorted(
{f"https://{SITE_ADDRESS}", *_env_list("DJANGO_CSRF_TRUSTED_ORIGINS")}
)
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"apps.accounts",
"apps.lottery",
"apps.web",
"apps.ops",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "config.urls"
WSGI_APPLICATION = "config.wsgi.application"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
# ADR-55: one SQLite file in WAL mode shared by the web and the worker processes. Every write
# transaction takes the write lock up front (`BEGIN IMMEDIATE`), so two processes never deadlock
# upgrading a read lock, and durability matches the old server (`synchronous=FULL`).
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.environ.get("DJANGO_DB_PATH", str(BASE_DIR / "data" / "db" / "site.sqlite3")),
"OPTIONS": {
"transaction_mode": "IMMEDIATE",
"timeout": 20,
"init_command": "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;",
},
}
}
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# The model is defined before the first migration (ADR-54): changing it later is painful.
AUTH_USER_MODEL = "accounts.User"
# Argon2 first, as in ADR-36; the others only keep Django's own tooling working.
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
]
AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 8}},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
# ADR-60: Italian only for the pilot; gettext is on so other languages can be added later.
LANGUAGE_CODE = "it"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STORAGES = {
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
}
# Caddy terminates TLS (even for localhost) and tells us so (WEB-02, WEB-07). Secure cookies
# apply wherever there is HTTPS: that is every Docker run, and not `runserver` in DEBUG.
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SESSION_COOKIE_SECURE = not DEBUG
CSRF_COOKIE_SECURE = not DEBUG
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
CSRF_COOKIE_SAMESITE = "Lax"
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = "DENY"
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
LOGIN_URL = "/accedi/"
LOGIN_REDIRECT_URL = "/app/"
LOGOUT_REDIRECT_URL = "/"
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"root": {"handlers": ["console"], "level": os.environ.get("LOG_LEVEL", "INFO")},
}
# ADR-58, ADR-59: the network profile and how money moves. The alpha runs on regtest with a
# simulated ledger; the simulated ledger can never run on mainnet (B2 adds the full profile).
PLM_NETWORK = os.environ.get("PLM_NETWORK", "regtest")
if PLM_NETWORK not in ("regtest", "mainnet"):
raise ImproperlyConfigured(f"PLM_NETWORK must be 'regtest' or 'mainnet', not {PLM_NETWORK!r}")
LEDGER_BACKEND = os.environ.get("LEDGER_BACKEND", "simulated")
if LEDGER_BACKEND not in ("simulated", "chain"):
raise ImproperlyConfigured(f"LEDGER_BACKEND must be 'simulated' or 'chain', not {LEDGER_BACKEND!r}")
if LEDGER_BACKEND == "simulated" and PLM_NETWORK == "mainnet":
raise ImproperlyConfigured("the simulated ledger cannot run on mainnet (ADR-59)")
# The simulated chain (ADR-59): a block every N seconds and a confirmation after M, so a whole round
# runs in a few minutes on localhost. Real chains ignore both.
SIMULATED_BLOCK_SECONDS = int(os.environ.get("SIMULATED_BLOCK_SECONDS", "20"))
SIMULATED_CONFIRM_SECONDS = int(os.environ.get("SIMULATED_CONFIRM_SECONDS", "5"))