Cap participants per round and give the payout its own input limit (B-52)
The payout has to spend one pool UTXO per bet, so reusing MAX_TX_INPUTS (50) for it made any round past ~50 players unpayable: select_utxos raised too_many_inputs, the round stayed "paying_out" retrying every 60s forever, and since no new round may open while one is active, the whole lottery stopped with the pool stuck. The cap was being enforced on the payout side, i.e. discovered once the money was already committed and there was no way back. Two halves: - select_utxos takes the cap as a parameter. Bets and withdrawals keep MAX_TX_INPUTS = 50, which protects a user from a fee that eats into the amount they are moving; the payout uses MAX_PAYOUT_TX_INPUTS = 500, where that argument doesn't apply — 400 inputs at 1 sat/vB cost ~0.00027 PLM out of the winner's 70% share. What actually bounds it is relay policy: 500 inputs is ~34 kvB against the 100 kvB standardness limit, and signing that many measures ~0.4s, once per round, inside a background task. - place_bet refuses the 401st bet with a new round_full error (translated into all 7 languages), so "a round can always be paid out" is an invariant checked before any money moves. MAX_PARTICIPANTS_PER_ROUND sits below the input cap to leave the payout headroom for pool change from earlier rounds, and counts every participant row rather than only confirmed ones, since a failed bet frees a slot. A round already wedged past the old cap now pays out on the next retry tick. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
99d7a1ee00
commit
025754c860
10 files changed
+311
-28
No files matched your search
+70
-2
@@ -1,7 +1,7 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.bets.service import BetError, place_bet
|
||||
@@ -11,7 +11,7 @@ from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, Roun
|
||||
from app.rounds.events import broadcaster
|
||||
from app.rounds.service import open_new_round_if_needed
|
||||
from app.wallet.hd import derive_user_address
|
||||
from app.wallet.psbt_builder import MAX_TX_INPUTS
|
||||
from app.wallet.psbt_builder import MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS
|
||||
|
||||
|
||||
class FakeElectrumClient:
|
||||
@@ -122,6 +122,74 @@ async def test_place_bet_reports_a_too_fragmented_balance_distinctly(session_fac
|
||||
assert not client.broadcasted
|
||||
|
||||
|
||||
async def _fill_round_with_participants(session_factory, round_id: int, count: int) -> None:
|
||||
"""Participant rows only, no real bets: what the cap counts is rows, and building
|
||||
`count` genuine transactions would just make the test slow without exercising
|
||||
anything the other tests don't already cover."""
|
||||
async with session_factory() as session:
|
||||
for i in range(count):
|
||||
session.add(
|
||||
RoundParticipant(
|
||||
round_id=round_id,
|
||||
user_id=10_000 + i, # placeholder ids; the cap check never joins users
|
||||
bet_amount_sats=1_000_000_000,
|
||||
bet_txid=f"{i:064x}",
|
||||
status="confirmed",
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def test_place_bet_rejects_the_bet_past_the_participant_cap(session_factory): # B-52
|
||||
"""The payout has to spend one pool UTXO per bet, so a round is only ever allowed
|
||||
to grow to what a single payout transaction can drain. Enforced here, before the
|
||||
player's money moves — not discovered at payout time, when the bets are already in
|
||||
the pool and the round can no longer be paid at all."""
|
||||
user_id = await _make_funded_user(session_factory, 30, 3_000_000_000)
|
||||
client = FakeElectrumClient()
|
||||
|
||||
async with session_factory() as session:
|
||||
round_ = await open_new_round_if_needed(session)
|
||||
await session.commit()
|
||||
round_id = round_.id
|
||||
await _fill_round_with_participants(session_factory, round_id, MAX_PARTICIPANTS_PER_ROUND)
|
||||
|
||||
async with session_factory() as session:
|
||||
user = await session.get(User, user_id)
|
||||
with pytest.raises(BetError) as excinfo:
|
||||
await place_bet(session, client, user)
|
||||
|
||||
assert excinfo.value.code == "round_full"
|
||||
assert excinfo.value.params == {"max_participants": MAX_PARTICIPANTS_PER_ROUND}
|
||||
assert not client.broadcasted
|
||||
|
||||
# Refused cleanly: no participant row, and the user's UTXO is still spendable.
|
||||
async with session_factory() as session:
|
||||
assert await session.scalar(
|
||||
select(func.count()).select_from(RoundParticipant).where(RoundParticipant.round_id == round_id)
|
||||
) == MAX_PARTICIPANTS_PER_ROUND
|
||||
utxo = (await session.scalars(select(UtxoEvent).where(UtxoEvent.user_id == user_id))).one()
|
||||
assert utxo.spent_txid is None
|
||||
|
||||
|
||||
async def test_place_bet_still_accepts_the_last_slot_under_the_cap(session_factory): # B-52
|
||||
user_id = await _make_funded_user(session_factory, 31, 3_000_000_000)
|
||||
client = FakeElectrumClient()
|
||||
|
||||
async with session_factory() as session:
|
||||
round_ = await open_new_round_if_needed(session)
|
||||
await session.commit()
|
||||
round_id = round_.id
|
||||
await _fill_round_with_participants(session_factory, round_id, MAX_PARTICIPANTS_PER_ROUND - 1)
|
||||
|
||||
async with session_factory() as session:
|
||||
user = await session.get(User, user_id)
|
||||
participant = await place_bet(session, client, user)
|
||||
|
||||
assert participant.status == "broadcast"
|
||||
assert client.broadcasted
|
||||
|
||||
|
||||
async def test_place_bet_rejects_second_bet_same_round(session_factory):
|
||||
user_id = await _make_funded_user(session_factory, 2, 3_000_000_000)
|
||||
client = FakeElectrumClient()
|
||||
|
||||
@@ -4,7 +4,15 @@ from embit.bip32 import HDKey
|
||||
from embit.transaction import Transaction
|
||||
|
||||
from app.wallet.plm_network import PLM_MAINNET
|
||||
from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_payout_transaction, estimate_vsize
|
||||
from app.wallet.psbt_builder import (
|
||||
MAX_PARTICIPANTS_PER_ROUND,
|
||||
MAX_PAYOUT_TX_INPUTS,
|
||||
MAX_TX_INPUTS,
|
||||
InsufficientFundsError,
|
||||
Utxo,
|
||||
build_payout_transaction,
|
||||
estimate_vsize,
|
||||
)
|
||||
|
||||
|
||||
def _key(seed_byte: int) -> HDKey:
|
||||
@@ -75,6 +83,55 @@ def test_payout_adds_change_output_when_pool_utxos_exceed_target():
|
||||
assert len(parsed.vout) == 3
|
||||
|
||||
|
||||
def test_payout_spends_more_utxos_than_a_user_transaction_may(): # B-52
|
||||
"""The pool holds one UTXO per bet, so a round with more participants than
|
||||
MAX_TX_INPUTS used to be impossible to pay out: select_utxos raised
|
||||
too_many_inputs, the round stayed "paying_out" retrying every 60s forever, and
|
||||
since no new round may open while one is active, the lottery stopped for good.
|
||||
The payout gets its own, far higher cap for exactly this reason."""
|
||||
pool_key = _key(40)
|
||||
pool_script = script.p2wpkh(pool_key.to_public())
|
||||
pool_address = pool_script.address(network=PLM_MAINNET)
|
||||
winner_address = script.p2wpkh(_key(41).to_public()).address(network=PLM_MAINNET)
|
||||
fee_address = script.p2wpkh(_key(42).to_public()).address(network=PLM_MAINNET)
|
||||
|
||||
# One 10 PLM bet per participant, one UTXO each, just past the user-facing cap.
|
||||
participants = MAX_TX_INPUTS + 1
|
||||
bet_sats = 1_000_000_000
|
||||
pool_amount = bet_sats * participants
|
||||
winner_share = pool_amount * 70 // 100
|
||||
commission = pool_amount - winner_share
|
||||
utxos = [Utxo(f"{i:064x}", 0, bet_sats) for i in range(participants)]
|
||||
|
||||
built = build_payout_transaction(
|
||||
signing_key=pool_key,
|
||||
from_script=pool_script,
|
||||
utxos=utxos,
|
||||
winner_address=winner_address,
|
||||
winner_share_sats=winner_share,
|
||||
fee_address=fee_address,
|
||||
commission_sats=commission,
|
||||
change_address=pool_address,
|
||||
fee_rate_sat_vb=1,
|
||||
)
|
||||
|
||||
assert len(built.spent_utxos) == participants # every bet had to be spent
|
||||
parsed = Transaction.parse(bytes.fromhex(built.raw_hex))
|
||||
assert len(parsed.vin) == participants
|
||||
assert built.fee_sats == estimate_vsize(participants, 3)
|
||||
assert built.winner_sats == winner_share - built.fee_sats
|
||||
assert built.commission_sats == commission # still untouched by the fee
|
||||
|
||||
|
||||
def test_payout_at_the_participant_cap_stays_well_inside_relay_limits(): # B-52
|
||||
"""MAX_PARTICIPANTS_PER_ROUND is only safe if the payout it implies is still a
|
||||
standard transaction. A full round is one input per bet plus the pool's own
|
||||
change, and relay policy refuses anything past 100 kvB."""
|
||||
inputs_needed = MAX_PARTICIPANTS_PER_ROUND + 1 # + one accumulated pool change UTXO
|
||||
assert inputs_needed <= MAX_PAYOUT_TX_INPUTS # headroom for pool change exists
|
||||
assert estimate_vsize(MAX_PAYOUT_TX_INPUTS, 3) < 100_000
|
||||
|
||||
|
||||
def test_payout_raises_when_winner_share_too_small():
|
||||
pool_key = _key(30)
|
||||
pool_script = script.p2wpkh(pool_key.to_public())
|
||||
|
||||
@@ -5,6 +5,7 @@ from embit.transaction import Transaction
|
||||
|
||||
from app.wallet.plm_network import PLM_MAINNET
|
||||
from app.wallet.psbt_builder import (
|
||||
MAX_PAYOUT_TX_INPUTS,
|
||||
MAX_TX_INPUTS,
|
||||
InsufficientFundsError,
|
||||
Utxo,
|
||||
@@ -53,6 +54,33 @@ def test_select_utxos_allows_exactly_the_input_cap():
|
||||
assert total == 100_000 * MAX_TX_INPUTS
|
||||
|
||||
|
||||
def test_select_utxos_honours_a_caller_supplied_cap(): # B-52
|
||||
"""The cap is per-caller: MAX_TX_INPUTS protects a user from a fee eating into
|
||||
their own bet/withdrawal, while the payout needs MAX_PAYOUT_TX_INPUTS to be able
|
||||
to drain a pool holding one UTXO per bet at all."""
|
||||
utxos = [Utxo(f"{i:064x}", 0, 100_000) for i in range(MAX_TX_INPUTS + 10)]
|
||||
target = 100_000 * (MAX_TX_INPUTS + 10)
|
||||
|
||||
with pytest.raises(InsufficientFundsError):
|
||||
select_utxos(utxos, target_sats=target) # default cap: too fragmented
|
||||
|
||||
selected, total = select_utxos(utxos, target_sats=target, max_inputs=MAX_PAYOUT_TX_INPUTS)
|
||||
assert len(selected) == MAX_TX_INPUTS + 10
|
||||
assert total == target
|
||||
|
||||
|
||||
def test_select_utxos_still_caps_at_the_payout_limit(): # B-52
|
||||
utxos = [Utxo(f"{i:064x}", 0, 100_000) for i in range(MAX_PAYOUT_TX_INPUTS + 5)]
|
||||
with pytest.raises(InsufficientFundsError) as excinfo:
|
||||
select_utxos(
|
||||
utxos,
|
||||
target_sats=100_000 * (MAX_PAYOUT_TX_INPUTS + 1),
|
||||
max_inputs=MAX_PAYOUT_TX_INPUTS,
|
||||
)
|
||||
assert excinfo.value.code == "too_many_inputs"
|
||||
assert excinfo.value.params == {"max_inputs": MAX_PAYOUT_TX_INPUTS}
|
||||
|
||||
|
||||
def test_build_signed_transaction_deducts_fee_from_amount_not_change():
|
||||
signer = _key(1)
|
||||
from_script = script.p2wpkh(signer.to_public())
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from embit.transaction import Transaction
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
@@ -8,6 +9,7 @@ from app.config import settings
|
||||
from app.db.base import Base
|
||||
from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, User
|
||||
from app.rounds.scheduler import RoundScheduler, _reserved_payout_outpoints
|
||||
from app.wallet.psbt_builder import MAX_TX_INPUTS
|
||||
|
||||
|
||||
class FakeListener:
|
||||
@@ -155,6 +157,40 @@ async def test_trigger_payout_persists_before_broadcasting(payout_session_factor
|
||||
assert "payout_sent" in events
|
||||
|
||||
|
||||
async def test_trigger_payout_pays_a_round_with_more_participants_than_max_tx_inputs(
|
||||
payout_session_factory,
|
||||
): # B-52
|
||||
"""End-to-end shape of the deadlock this fixes: the pool holds one UTXO per bet,
|
||||
so a round past MAX_TX_INPUTS participants could not be paid at all — the build
|
||||
failed with too_many_inputs, the round stayed "paying_out" retrying every 60s,
|
||||
and no new round could ever open behind it. It must now broadcast normally."""
|
||||
await _seed_paying_out_round(payout_session_factory)
|
||||
|
||||
participants = MAX_TX_INPUTS + 1
|
||||
bet_sats = _POOL_AMOUNT_SATS // participants
|
||||
entries = [
|
||||
{"tx_hash": f"{i:064x}", "tx_pos": 0, "height": 10, "value": bet_sats}
|
||||
for i in range(participants)
|
||||
]
|
||||
# The pool's total must cover the round's recorded pool_amount_sats, exactly as
|
||||
# on-chain: integer division above leaves a remainder, so top the last one up.
|
||||
entries[-1]["value"] += _POOL_AMOUNT_SATS - bet_sats * participants
|
||||
client = FakePayoutClient(entries)
|
||||
scheduler = RoundScheduler(payout_session_factory, FakePayoutListener(client))
|
||||
|
||||
await scheduler._trigger_payout(1)
|
||||
|
||||
assert client.broadcasted
|
||||
async with payout_session_factory() as session:
|
||||
pending = (await session.scalars(select(PendingTransaction))).one()
|
||||
assert pending.status == "pending"
|
||||
assert len(Transaction.parse(bytes.fromhex(pending.raw_tx_hex)).vin) == participants
|
||||
|
||||
events = [e.event_type for e in (await session.scalars(select(AuditLog))).all()]
|
||||
assert "payout_sent" in events
|
||||
assert "payout_failed" not in events
|
||||
|
||||
|
||||
async def test_trigger_payout_broadcast_failure_leaves_a_recoverable_row(payout_session_factory):
|
||||
"""Before B-25, a broadcast rejection here left nothing behind — no payout_txid,
|
||||
no PendingTransaction — because everything was persisted only after the
|
||||
|
||||
Reference in new issue
Block a user