Files
plm-lottery/migrations/versions/d3e8b15a7c42_commit_reveal_draw_columns.py
davideandClaude Sonnet 5.5 db24287ea5 Make the draw a commit-reveal at a fixed, confirmed, quorum-agreed height with a public proof (B-73, RND-14 … RND-20, RND-33 … RND-37, DAT-61 … DAT-66, API-25, API-45, AUD-24 … AUD-27, AUD-37, ELC-15, SEC-56, ADR-24, ADR-25)
The seed was the hash of the first block seen after the close, so a miner holding tickets
could withhold blocks until one made them win, the active Electrum server could pick which
real block was used by not announcing another (a failed corroboration even moved the draw to
the next block), and the participant order was the server-only `broadcast_at` with no
tie-break, so nobody could recompute the result.

- Open: every round gets a 32-byte `server_seed`, stored only Fernet-encrypted with the
  master-xprv key (`server_seed_enc`), with its published `server_seed_hash`;
  `draw_confirmations` is copied from round_config. The plaintext column is written only by
  the reveal.
- Entering `drawing` (one transaction, `draw_committed` audit row): participants ordered by
  bet txid, each `draw_position`, `participants_hash` (sha256 of `txid:vout:address\n`
  lines; new `bet_vout`), `draw_height = tip_at_close + 1`. A tip of 0 keeps the round
  `closing` (`draw_baseline_tip_unknown`, once per round). All persisted, so a resumed draw
  reads rather than recomputes (the `_tick` branch itself is B-81).
- `_complete_draw` / `_wait_for_draw_block` replace `_wait_for_next_block`: wait for
  `draw_confirmations` blocks from `draw_height`, then `ElectrumListener.agreed_block_hash`
  asks every server, the active one included, for the header at that exact height (valid
  work, >= 2 other answers, strict majority of all); no agreement means the same height is
  asked again and `draw_header_corroboration_failed` is written once per distinct reported
  hash. `draw_stalled` now counts from the last tip advance, or from when the quorum started
  to fail. Seed = sha256(server_seed || block_hash || participants_hash), index = seed mod n.
- The winner, the seed and the reveal (`server_seed`, `winner_drawn` payload) are written in
  one transaction; a round closing with no participants reveals too. A round opened before
  this change (no commitment) is given a secret as it enters `drawing`.
- `GET /rounds/{id}/proof` (public, 404 `round_not_found`, translated in all 7 languages) and
  the new fields on `GET /rounds/current`; `draw_confirmations` in `/admin/config` and the
  /admin form; `server_seed_hash`/`draw_height` in `/admin/rounds`, never the secret.
- Alembic d3e8b15a7c42 (plain add_column / create_index, expression indexes untouched).
- Docs: the B-73 `*Stato:*`/`*Oggi:*` lines are gone, guides and CLAUDE.md describe the new
  draw. Ambiguities resolved in api.md: the proof's participants also carry `amount_sats`
  (RND-37 lists it); `seed` is decimal in the proof and hex in the audit row, as specified.

Tests changed because the spec changed: ElectrumListener.corroborate_header (asked only the
other servers about the block the active one announced) is replaced by agreed_block_hash and
its quorum tests ported; draw_winner takes the secret and the list fingerprint; the four
_wait_for_next_block scheduler tests are replaced by _wait_for_draw_block ones (fixed height,
confirmations, same-height retry, stall clock). New: test_draw_proof.py recomputes the winner
independently from the public proof, checks the plaintext secret is nowhere in the database,
the API or the log before the reveal, and that a second pass over a `drawing` round yields
the same winner. Mutation-checked: ordering by broadcast_at, an early reveal and asking the
tip instead of the draw height each fail tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 16:29:09 +02:00

69 lines
3.1 KiB
Python

"""commit-reveal draw: round secret, participant order and draw height (B-73)
Revision ID: d3e8b15a7c42
Revises: b7d2e41c9a05
Create Date: 2026-10-14 16:40:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd3e8b15a7c42'
down_revision: Union[str, Sequence[str], None] = 'b7d2e41c9a05'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
_ACTIVE = "'open', 'closing', 'drawing', 'paying_out'"
def upgrade() -> None:
"""Upgrade schema.
B-73 (DAT-61 … DAT-66): the round's secret (`server_seed_enc`, `server_seed`,
`server_seed_hash`), the fixed participant list (`participants_hash`, `draw_height`,
`round_participants.draw_position`) and the number of confirmations the draw block
needs (`draw_confirmations` on the round, copied from `round_config` at open).
`bet_vout` records which output of a bet pays the pool; every existing bet pays it
with its first output.
Rounds that already exist keep NULL in the three secret columns (they were drawn,
or are drawn, on the block hash alone) and take the default of 3 confirmations.
Plain add_column / create_index calls — never batch_alter_table, which on SQLite
rebuilds the table and silently drops the expression indexes (B-97, DAT-56).
"""
op.add_column("rounds", sa.Column("draw_confirmations", sa.Integer(), server_default="3", nullable=False))
op.add_column("rounds", sa.Column("server_seed_enc", sa.Text(), nullable=True))
op.add_column("rounds", sa.Column("server_seed", sa.String(length=64), nullable=True))
op.add_column("rounds", sa.Column("server_seed_hash", sa.String(length=64), nullable=True))
op.add_column("rounds", sa.Column("participants_hash", sa.String(length=64), nullable=True))
op.add_column("rounds", sa.Column("draw_height", sa.Integer(), nullable=True))
op.add_column("round_participants", sa.Column("bet_vout", sa.Integer(), server_default="0", nullable=False))
op.add_column("round_participants", sa.Column("draw_position", sa.Integer(), nullable=True))
op.create_index(
"ux_round_participants_round_draw_position",
"round_participants",
["round_id", "draw_position"],
unique=True,
)
op.add_column("round_config", sa.Column("draw_confirmations", sa.Integer(), server_default="3", nullable=False))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column("round_config", "draw_confirmations")
op.drop_index("ux_round_participants_round_draw_position", table_name="round_participants")
op.drop_column("round_participants", "draw_position")
op.drop_column("round_participants", "bet_vout")
for column in ("draw_height", "participants_hash", "server_seed_hash", "server_seed", "server_seed_enc", "draw_confirmations"):
op.drop_column("rounds", column)
# drop_column on SQLite is a table rebuild: recreate the expression index (B-97).
op.execute("DROP INDEX IF EXISTS ix_rounds_single_active")
op.execute(f"CREATE UNIQUE INDEX ix_rounds_single_active ON rounds ((1)) WHERE status IN ({_ACTIVE})")