Give every round its own pool address (B-80, RND-35, DAT-60, DAT-11, REG-14, SEC-08, BET-12, RND-22, WDR-14, SEC-43, API-23, API-36)
All bets of all rounds paid one address (m/84'/746'/0'/1/0), so its history grew forever, other rounds' money and stray coins mixed with a round's own, and the payout picked from everything it held. - hd.py: derive_pool_key/derive_pool_address(round_id) on branch 2 (m/84'/746'/0'/2/<round_id>); no argument is the reserve address 1/0. derive_round_pool_key checks the key against the address stored on the round, so a payout can never be signed for money its key does not control. - rounds.pool_address (migration 477bddae1a84, existing rounds backfilled with the reserve address since that is where their bets went; add_column, not a batch alter, so the expression indexes stay): written in the transaction that inserts the round, once its id exists. - place_bet pays round.pool_address; the payout reads, signs and takes change at the round's own address; own_address_for and bump_fee's _signing_context follow the round (confirmation poller and reconciler pass round_id). - Withdrawals to any round pool address, the reserve address or fee_address are refused (withdrawal_to_platform_address, 400, all seven languages). - GET /rounds/current and GET /admin/rounds expose pool_address. - RND-22/DAT-11 stay "da implementare" for B-82: the payout still spends every confirmed coin at the round's address, not only the participants' outpoints (participants carry no bet_vout yet). - tests/unit/conftest.py: every test now gets a throwaway master key. Opening a round derives an address, and tests that merely opened a round were silently reading the real key from the local .env. - Existing tests changed because the spec changed: payout fixtures give their round a pool_address; the reconciler's address-cache test uses two payouts of one round (rows of different rounds no longer share an address); own_address_for now takes the round id. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cc63753439
commit
fd6a91e93d
37 files changed
+673
-144
No files matched your search
@@ -241,6 +241,7 @@ class AdminRoundResponse(BaseModel):
|
||||
winner_amount_sats: int | None
|
||||
fee_amount_sats: int | None
|
||||
payout_txid: str | None
|
||||
pool_address: str | None # B-80
|
||||
|
||||
|
||||
@router.get("/rounds", response_model=list[AdminRoundResponse], dependencies=[Depends(require_admin)])
|
||||
@@ -268,6 +269,7 @@ async def list_rounds(
|
||||
winner_amount_sats=r.winner_amount_sats,
|
||||
fee_amount_sats=r.fee_amount_sats,
|
||||
payout_txid=r.payout_txid,
|
||||
pool_address=r.pool_address or None,
|
||||
)
|
||||
for r in rounds
|
||||
]
|
||||
|
||||
@@ -89,6 +89,9 @@ class CurrentRoundResponse(BaseModel):
|
||||
server_time: str
|
||||
round_id: int | None = None
|
||||
status: str | None = None
|
||||
# B-80 (RND-35): this round's own pool address, so anyone can verify its money on
|
||||
# an explorer; null when there is no active round.
|
||||
pool_address: str | None = None
|
||||
opened_at: str | None = None
|
||||
closes_at: str | None = None
|
||||
# B-65: confirmed participants only — the ones the draw actually picks from and
|
||||
@@ -205,6 +208,7 @@ async def current_round(
|
||||
server_time=datetime.now(timezone.utc).isoformat(),
|
||||
round_id=round_.id,
|
||||
status=round_.status,
|
||||
pool_address=round_.pool_address or None,
|
||||
opened_at=opened_at.isoformat(),
|
||||
closes_at=closes_at.isoformat(),
|
||||
participant_count=participant_count,
|
||||
|
||||
+7
-2
@@ -15,7 +15,7 @@ from app.rounds.config import get_round_config
|
||||
from app.rounds.events import broadcaster
|
||||
from app.rounds.service import open_new_round_if_needed, round_accepts_bets
|
||||
from app.wallet.balance import recompute_balance
|
||||
from app.wallet.hd import derive_pool_address, derive_user_key
|
||||
from app.wallet.hd import derive_user_key
|
||||
from app.wallet.psbt_builder import (
|
||||
MAX_PARTICIPANTS_PER_ROUND,
|
||||
BuiltTransaction,
|
||||
@@ -85,6 +85,11 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
|
||||
max_participants=MAX_PARTICIPANTS_PER_ROUND,
|
||||
)
|
||||
|
||||
if not round_.pool_address:
|
||||
# B-80: open_new_round_if_needed always writes it; a row without one cannot
|
||||
# take money that would then have nowhere verifiable to go.
|
||||
raise RuntimeError(f"round {round_.id} has no pool address")
|
||||
|
||||
bet_amount = config.bet_amount_sats
|
||||
|
||||
unspent = (
|
||||
@@ -104,7 +109,7 @@ async def place_bet(session: AsyncSession, client: ElectrumClient, user: User) -
|
||||
signing_key=user_key,
|
||||
from_script=from_script,
|
||||
utxos=utxos,
|
||||
to_address=derive_pool_address(),
|
||||
to_address=round_.pool_address, # B-80: this round's own pool address
|
||||
amount_sats=bet_amount,
|
||||
change_address=user.address,
|
||||
fee_rate_sat_vb=config.fee_rate_sat_vb,
|
||||
|
||||
@@ -92,6 +92,12 @@ class Round(Base):
|
||||
# the gap it announced is the gap that's honoured.
|
||||
duration_seconds: Mapped[int] = mapped_column(default=600, server_default="600")
|
||||
cooldown_seconds: Mapped[int] = mapped_column(default=30, server_default="30")
|
||||
# B-80 (DAT-60, RND-35): this round's own pool address, m/84'/746'/0'/2/<id>. The id
|
||||
# only exists once the row is flushed, so the row is inserted with "" and the real
|
||||
# address is written in the same transaction (rounds/service.py:open_new_round_if_needed)
|
||||
# — "" is never visible outside it, and every consumer refuses it. Rounds opened before
|
||||
# B-80 hold the reserve address (m/84'/746'/0'/1/0), their old shared pool.
|
||||
pool_address: Mapped[str] = mapped_column(String(128), default="", server_default="")
|
||||
# Set once, when status flips to "drawing" (rounds/scheduler.py:_close_and_draw).
|
||||
# Lets both the audit log (B-36's draw_stalled entries) and GET /rounds/current
|
||||
# (draw_waiting_since) measure how long a round has been waiting on a block,
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.rounds.config import get_round_config
|
||||
from app.rounds.draw import draw_winner, header_hex_to_block_hash
|
||||
from app.rounds.events import broadcaster
|
||||
from app.rounds.service import open_new_round_if_needed, round_deadline, winner_share
|
||||
from app.wallet.hd import derive_pool_key
|
||||
from app.wallet.hd import derive_round_pool_key
|
||||
from app.wallet.plm_network import PLM_MAINNET
|
||||
from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_payout_transaction
|
||||
|
||||
@@ -400,6 +400,7 @@ class RoundScheduler:
|
||||
fee_address = config.fee_address
|
||||
fee_rate = config.fee_rate_sat_vb
|
||||
pool_amount_sats = round_.pool_amount_sats
|
||||
round_pool_address = round_.pool_address # B-80 ("" fails in derive_round_pool_key below)
|
||||
winner_user_id = round_.winner_user_id
|
||||
winner = await session.get(User, winner_user_id)
|
||||
winner_address = winner.address if winner is not None else None
|
||||
@@ -421,7 +422,10 @@ class RoundScheduler:
|
||||
|
||||
# --- Phase 2: build (network read only, no DB write yet) -----------------
|
||||
try:
|
||||
pool_key = derive_pool_key()
|
||||
# B-80 (RND-22): the round's own key and address — only the coins at this
|
||||
# round's pool address are ever read, so no other round's money (and no
|
||||
# stray coin sent to another address) can end up among the inputs.
|
||||
pool_key = derive_round_pool_key(round_id, round_pool_address)
|
||||
pool_script_obj = script.p2wpkh(pool_key.to_public())
|
||||
pool_address = pool_script_obj.address(network=PLM_MAINNET)
|
||||
entries = await client.listunspent(address_to_scripthash(pool_address))
|
||||
|
||||
@@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.db.models import Round, RoundConfig
|
||||
from app.rounds.config import get_round_config
|
||||
from app.rounds.events import broadcaster
|
||||
from app.wallet.hd import derive_pool_address
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -152,6 +153,9 @@ async def open_new_round_if_needed(session: AsyncSession) -> Round | None:
|
||||
# only tells subscribers "go refetch", and by the time an SSE client's
|
||||
# refetch request actually lands, this in-process commit (microseconds
|
||||
# away) has essentially always already happened.
|
||||
# B-80 (RND-35, DAT-60): the round's own pool address, now that its id exists —
|
||||
# still inside the caller's transaction, so no committed round ever lacks one.
|
||||
round_.pool_address = derive_pool_address(round_.id)
|
||||
broadcaster.publish()
|
||||
return round_
|
||||
|
||||
|
||||
@@ -163,6 +163,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': 'The amount is too small to be sent.',
|
||||
'error.too_many_inputs': 'Your balance is split across too many small deposits to be spent in a single transaction (max {max_inputs}). Please contact support to consolidate it.',
|
||||
'error.withdrawal_to_own_address': 'That is your own deposit address — withdraw to an external wallet.',
|
||||
'error.withdrawal_to_platform_address': 'That is an address of this platform — withdraw to an external wallet.',
|
||||
'error.internal_error': 'Unexpected server error. Please try again shortly.',
|
||||
'error.guide_unavailable': 'The guide is not available right now.',
|
||||
'error.rate_limited': 'Too many attempts, please try again in {retry_after_seconds} seconds.',
|
||||
@@ -329,6 +330,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': "L'importo è troppo basso per essere inviato.",
|
||||
'error.too_many_inputs': 'Il tuo saldo è suddiviso in troppi piccoli depositi per essere speso in una sola transazione (max {max_inputs}). Contatta l\'assistenza per consolidarlo.',
|
||||
'error.withdrawal_to_own_address': 'Questo è il tuo indirizzo di deposito — preleva verso un wallet esterno.',
|
||||
'error.withdrawal_to_platform_address': 'Questo è un indirizzo della piattaforma — preleva verso un wallet esterno.',
|
||||
'error.internal_error': 'Errore inatteso del server. Riprova tra poco.',
|
||||
'error.guide_unavailable': 'La guida non è disponibile in questo momento.',
|
||||
'error.rate_limited': 'Troppi tentativi, riprova tra {retry_after_seconds} secondi.',
|
||||
@@ -495,6 +497,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': 'El importe es demasiado pequeño para enviarse.',
|
||||
'error.too_many_inputs': 'Tu saldo está repartido en demasiados depósitos pequeños para gastarse en una sola transacción (máx. {max_inputs}). Contacta con soporte para consolidarlo.',
|
||||
'error.withdrawal_to_own_address': 'Esa es tu propia dirección de depósito — retira a una cartera externa.',
|
||||
'error.withdrawal_to_platform_address': 'Esa es una dirección de la propia plataforma — retira a una cartera externa.',
|
||||
'error.internal_error': 'Error inesperado del servidor. Inténtalo de nuevo en un momento.',
|
||||
'error.guide_unavailable': 'La guía no está disponible en este momento.',
|
||||
'error.rate_limited': 'Demasiados intentos, inténtalo de nuevo en {retry_after_seconds} segundos.',
|
||||
@@ -661,6 +664,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': "Le montant est trop faible pour être envoyé.",
|
||||
'error.too_many_inputs': 'Votre solde est réparti sur trop de petits dépôts pour être dépensé en une seule transaction (max {max_inputs}). Contactez le support pour le consolider.',
|
||||
'error.withdrawal_to_own_address': "C'est votre propre adresse de dépôt — retirez vers un portefeuille externe.",
|
||||
'error.withdrawal_to_platform_address': "C'est une adresse de la plateforme elle-même — retirez vers un portefeuille externe.",
|
||||
'error.internal_error': 'Erreur inattendue du serveur. Veuillez réessayer dans un instant.',
|
||||
'error.guide_unavailable': "Le guide n'est pas disponible pour le moment.",
|
||||
'error.rate_limited': 'Trop de tentatives, réessayez dans {retry_after_seconds} secondes.',
|
||||
@@ -827,6 +831,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': 'Der Betrag ist zu klein, um gesendet zu werden.',
|
||||
'error.too_many_inputs': 'Ihr Guthaben ist auf zu viele kleine Einzahlungen verteilt, um in einer einzigen Transaktion ausgegeben zu werden (max. {max_inputs}). Bitte wenden Sie sich an den Support, um es zusammenzufassen.',
|
||||
'error.withdrawal_to_own_address': 'Das ist deine eigene Einzahlungsadresse — zahle auf eine externe Wallet aus.',
|
||||
'error.withdrawal_to_platform_address': 'Das ist eine Adresse der Plattform selbst — zahle auf eine externe Wallet aus.',
|
||||
'error.internal_error': 'Unerwarteter Serverfehler. Bitte versuche es in Kürze erneut.',
|
||||
'error.guide_unavailable': 'Die Anleitung ist derzeit nicht verfügbar.',
|
||||
'error.rate_limited': 'Zu viele Versuche, bitte versuche es in {retry_after_seconds} Sekunden erneut.',
|
||||
@@ -993,6 +998,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': 'Сумма слишком мала для отправки.',
|
||||
'error.too_many_inputs': 'Ваш баланс разбит на слишком много мелких депозитов, чтобы потратить его одной транзакцией (максимум {max_inputs}). Обратитесь в поддержку для консолидации.',
|
||||
'error.withdrawal_to_own_address': 'Это ваш собственный адрес для депозита — выводите на внешний кошелёк.',
|
||||
'error.withdrawal_to_platform_address': 'Это адрес самой платформы — выводите на внешний кошелёк.',
|
||||
'error.internal_error': 'Непредвиденная ошибка сервера. Попробуйте ещё раз через минуту.',
|
||||
'error.guide_unavailable': 'Руководство сейчас недоступно.',
|
||||
'error.rate_limited': 'Слишком много попыток, повторите через {retry_after_seconds} сек.',
|
||||
@@ -1159,6 +1165,7 @@ const TRANSLATIONS = {
|
||||
'error.amount_below_dust_limit': '金额过小,无法发送。',
|
||||
'error.too_many_inputs': '您的余额分散在过多的小额存款中,无法在一笔交易中花费(最多 {max_inputs} 笔)。请联系客服进行归集。',
|
||||
'error.withdrawal_to_own_address': '这是你自己的充值地址 — 请提现到外部钱包。',
|
||||
'error.withdrawal_to_platform_address': '这是平台自己的地址 — 请提现到外部钱包。',
|
||||
'error.internal_error': '服务器发生意外错误,请稍后重试。',
|
||||
'error.guide_unavailable': '指南当前不可用。',
|
||||
'error.rate_limited': '尝试次数过多,请在 {retry_after_seconds} 秒后重试。',
|
||||
|
||||
+11
-5
@@ -13,7 +13,7 @@ from app.db.base import begin_immediate
|
||||
from app.db.models import PendingTransaction, Round, RoundParticipant, User, UtxoEvent, Withdrawal
|
||||
from app.electrum.client import ElectrumClient
|
||||
from app.rounds.config import get_round_config
|
||||
from app.wallet.hd import derive_pool_key, derive_user_key
|
||||
from app.wallet.hd import derive_round_pool_key, derive_user_key
|
||||
from app.wallet.plm_network import PLM_MAINNET
|
||||
from app.wallet.psbt_builder import MAX_FEE_RATE_SAT_VB, RBF_SEQUENCE, estimate_vsize
|
||||
|
||||
@@ -49,12 +49,18 @@ def should_bump(pending: PendingTransaction, now: datetime, timeout_seconds: int
|
||||
return now >= pending.last_broadcast_at.replace(tzinfo=timezone.utc) + timedelta(seconds=timeout_seconds)
|
||||
|
||||
|
||||
async def _signing_context(session: AsyncSession, kind: str, user_id: int | None) -> tuple:
|
||||
async def _signing_context(
|
||||
session: AsyncSession, kind: str, user_id: int | None, round_id: int | None = None
|
||||
) -> tuple:
|
||||
"""Returns (signing_key, own_script, own_address) for the single sender that
|
||||
controls every input of this tx — a user for bet/withdrawal, the pool for
|
||||
payout. All our builders only ever spend one address's UTXOs per tx."""
|
||||
payout (the round's own pool key, B-80). All our builders only ever spend one
|
||||
address's UTXOs per tx."""
|
||||
if kind == "payout":
|
||||
key = derive_pool_key()
|
||||
round_ = await session.get(Round, round_id) if round_id is not None else None
|
||||
if round_ is None or not round_.pool_address:
|
||||
raise RbfError(f"payout of round {round_id}: the round has no pool address")
|
||||
key = derive_round_pool_key(round_.id, round_.pool_address)
|
||||
else:
|
||||
user = await session.get(User, user_id)
|
||||
key = derive_user_key(user.derivation_index)
|
||||
@@ -125,7 +131,7 @@ async def bump_fee(
|
||||
kind = pending.kind
|
||||
current_fee_rate = pending.fee_rate_sat_vb
|
||||
raw_tx_hex = pending.raw_tx_hex
|
||||
signing_key, own_script, own_address = await _signing_context(session, kind, pending.user_id)
|
||||
signing_key, own_script, own_address = await _signing_context(session, kind, pending.user_id, pending.round_id)
|
||||
|
||||
# --- Phase 2: chain reads, signing, and the broadcast — no DB session open ----
|
||||
old_tx = Transaction.parse(bytes.fromhex(raw_tx_hex))
|
||||
|
||||
@@ -38,24 +38,25 @@ async def poll_once(session_factory: async_sessionmaker, client: ElectrumClient)
|
||||
PendingTransaction.current_txid,
|
||||
PendingTransaction.kind,
|
||||
PendingTransaction.user_id,
|
||||
PendingTransaction.round_id,
|
||||
).where(PendingTransaction.status == "pending")
|
||||
)
|
||||
).all()
|
||||
|
||||
# Resolved once per candidate while the session is still open, and cached
|
||||
# by scripthash below — every "payout" row shares the same pool address,
|
||||
# so this also avoids asking the server the same history twice per tick.
|
||||
# by scripthash below — the payout rows of one round share its pool
|
||||
# address (B-80), so this also avoids asking the server the same history twice.
|
||||
scripthash_by_id: dict[int, str] = {}
|
||||
for pending_id, _txid, kind, user_id in candidates:
|
||||
for pending_id, _txid, kind, user_id, round_id in candidates:
|
||||
try:
|
||||
address = await own_address_for(session, kind, user_id)
|
||||
address = await own_address_for(session, kind, user_id, round_id)
|
||||
scripthash_by_id[pending_id] = address_to_scripthash(address)
|
||||
except Exception:
|
||||
logger.exception("could not derive the address for pending_transaction %s", pending_id)
|
||||
|
||||
confirmed = 0
|
||||
history_cache: dict[str, list[dict]] = {}
|
||||
for pending_id, txid, kind, _user_id in candidates:
|
||||
for pending_id, txid, kind, _user_id, _round_id in candidates:
|
||||
scripthash = scripthash_by_id.get(pending_id)
|
||||
if scripthash is None:
|
||||
continue # address derivation failed above; already logged
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.models import User
|
||||
from app.wallet.hd import derive_pool_address, derive_user_address
|
||||
from app.db.models import Round, User
|
||||
from app.wallet.hd import derive_user_address
|
||||
|
||||
|
||||
async def own_address_for(session: AsyncSession, kind: str, user_id: int | None) -> str:
|
||||
async def own_address_for(
|
||||
session: AsyncSession, kind: str, user_id: int | None, round_id: int | None = None
|
||||
) -> str:
|
||||
"""The address that owns every input of a PendingTransaction of this kind —
|
||||
a user's own address for a bet/withdrawal, the pool address for a payout.
|
||||
a user's own address for a bet/withdrawal, the pool address of the round for a
|
||||
payout (B-80: each round has its own, stored on the round).
|
||||
All our builders only ever spend one address's UTXOs per tx (see
|
||||
tx/broadcast.py:_signing_context, which derives the same address alongside
|
||||
the signing key it also needs).
|
||||
@@ -17,6 +20,9 @@ async def own_address_for(session: AsyncSession, kind: str, user_id: int | None)
|
||||
different addresses for the same row.
|
||||
"""
|
||||
if kind == "payout":
|
||||
return derive_pool_address()
|
||||
round_ = await session.get(Round, round_id) if round_id is not None else None
|
||||
if round_ is None or not round_.pool_address:
|
||||
raise ValueError(f"payout of round {round_id}: the round has no pool address")
|
||||
return round_.pool_address
|
||||
user = await session.get(User, user_id)
|
||||
return derive_user_address(user.derivation_index)
|
||||
+3
-3
@@ -87,8 +87,8 @@ async def reconcile_once(session_factory: async_sessionmaker, client: ElectrumCl
|
||||
a decision that releases funds. A transport failure fetching history still
|
||||
raises and leaves the row alone until next time — get_history not
|
||||
returning our txid is the only thing that means "gone". History is cached
|
||||
per scripthash within one pass, since every "payout" row shares the same
|
||||
pool address.
|
||||
per scripthash within one pass, since the payout rows of one round share its
|
||||
pool address (B-80).
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
async with session_factory() as session:
|
||||
@@ -102,7 +102,7 @@ async def reconcile_once(session_factory: async_sessionmaker, client: ElectrumCl
|
||||
if not _is_due(row, now):
|
||||
continue
|
||||
try:
|
||||
address = await own_address_for(session, row.kind, row.user_id)
|
||||
address = await own_address_for(session, row.kind, row.user_id, row.round_id)
|
||||
scripthash = address_to_scripthash(address)
|
||||
except Exception:
|
||||
logger.exception("could not derive the address for pending_transaction %s", row.id)
|
||||
|
||||
+31
-8
@@ -50,14 +50,37 @@ def derive_user_wif(derivation_index: int) -> str:
|
||||
return PrivateKey(key.secret, compressed=True, network=PLM_MAINNET).wif(network=PLM_MAINNET)
|
||||
|
||||
|
||||
def derive_pool_key() -> HDKey:
|
||||
"""The pool key ("indirizzo padre"): all bets are sent here, and
|
||||
payouts are signed with this key. Reserved on branch 1 of the account (branch 0
|
||||
is user addresses), index 0 — not a spec requirement, an implementation choice
|
||||
to keep it in the same encrypted master key rather than a separate secret."""
|
||||
return _load_account_key().derive("1/0")
|
||||
def derive_pool_key(round_id: int | None = None) -> HDKey:
|
||||
"""A pool key. With a `round_id`, that round's own key on branch 2 of the account
|
||||
(`m/84'/746'/0'/2/<round_id>`, B-80, RND-35): its bets are paid to it and its
|
||||
payout is signed with it, so one round's money and history never mix with another's.
|
||||
Without one, the **reserve** key at branch 1, index 0 — the single pool address every
|
||||
round used before B-80, still the pool of the rounds opened back then and the
|
||||
destination of the payout's bump reserve. Branch 0 is users. Not a spec requirement
|
||||
of the coin, an implementation choice to keep every key under the one encrypted
|
||||
master key rather than in separate secrets."""
|
||||
if round_id is None:
|
||||
return _load_account_key().derive("1/0")
|
||||
if round_id < 1:
|
||||
raise ValueError(f"invalid round id {round_id}")
|
||||
return _load_account_key().derive(f"2/{round_id}")
|
||||
|
||||
|
||||
def derive_pool_address() -> str:
|
||||
pub = derive_pool_key().to_public()
|
||||
def derive_pool_address(round_id: int | None = None) -> str:
|
||||
"""The pool address of a round (B-80), or the reserve address without a `round_id`."""
|
||||
pub = derive_pool_key(round_id).to_public()
|
||||
return script.p2wpkh(pub).address(network=PLM_MAINNET)
|
||||
|
||||
|
||||
def derive_round_pool_key(round_id: int, pool_address: str) -> HDKey:
|
||||
"""The key that controls `pool_address`, the address stored on round `round_id`.
|
||||
|
||||
A round opened before B-80 stores the reserve address and is signed with the reserve
|
||||
key; every other round with its own. Checking the derived address against the stored
|
||||
one means a key can never be used for money it does not control, and a mismatch (a
|
||||
different master key, a corrupted row) fails loudly instead of building a transaction
|
||||
that spends someone else's coins."""
|
||||
for key in (derive_pool_key(round_id), derive_pool_key()):
|
||||
if script.p2wpkh(key.to_public()).address(network=PLM_MAINNET) == pool_address:
|
||||
return key
|
||||
raise ValueError(f"round {round_id}: no pool key controls the stored address {pool_address!r}")
|
||||
@@ -8,13 +8,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.api.errors import ApiError
|
||||
from app.audit.log import write_audit_log
|
||||
from app.db.base import begin_immediate
|
||||
from app.db.models import PendingTransaction, User, UtxoEvent, Withdrawal
|
||||
from app.db.models import PendingTransaction, Round, User, UtxoEvent, Withdrawal
|
||||
from app.electrum.client import ElectrumClient
|
||||
from app.rounds.config import get_round_config
|
||||
from app.rounds.events import broadcaster
|
||||
from app.wallet.address import is_valid_plm_address
|
||||
from app.wallet.balance import compute_pending_balance, recompute_balance
|
||||
from app.wallet.hd import derive_user_key
|
||||
from app.wallet.hd import derive_pool_address, derive_user_key
|
||||
from app.wallet.psbt_builder import (
|
||||
BuiltTransaction,
|
||||
InsufficientFundsError,
|
||||
@@ -63,6 +63,22 @@ async def request_withdrawal(
|
||||
) from exc
|
||||
|
||||
config = await get_round_config(session)
|
||||
|
||||
# B-80 (WDR-14): never to an address of the platform itself. Coins sent to a round's
|
||||
# pool address land among that round's UTXOs, and to the reserve or fee address they
|
||||
# leave the user's balance for good; the amount would be spent from the balance and
|
||||
# then belong to nobody. Compared lower-cased, since bech32 is case-insensitive.
|
||||
platform_addresses = {derive_pool_address().lower(), config.fee_address.strip().lower()}
|
||||
platform_addresses.update(
|
||||
address.lower() for address in await session.scalars(select(Round.pool_address).distinct()) if address
|
||||
)
|
||||
platform_addresses.discard("")
|
||||
if external_address.strip().lower() in platform_addresses:
|
||||
raise WithdrawalError(
|
||||
"withdrawal_to_platform_address",
|
||||
"that is an address of the platform itself — withdraw to an external wallet instead",
|
||||
)
|
||||
|
||||
if amount_sats < config.bet_amount_sats:
|
||||
raise WithdrawalError(
|
||||
"amount_below_minimum",
|
||||
|
||||
Reference in new issue
Block a user