Restructure bump_fee into three phases, drop float fee math (B-40)
bump_fee issued one get_transaction per input (up to 15s each) and then a broadcast, all with the caller's DB session held open - exactly the pattern already fixed elsewhere for the same reason (B-18's _trigger_payout, B-31's refresh_user). Also, _prevout_amount computed a prevout's satoshi value via round(value_coins * 100_000_000) on a float the server reported, in a codebase that is otherwise strictly integer-satoshi. bump_fee now takes a session_factory and a pending_id instead of a live session and row, with three phases: read what's needed (the signing key, current fee rate, raw tx) and close the session before any network call; do the chain reads, signing and broadcast with no session open; reopen a session only to persist the outcome. _prevout_amount now asks for the raw (non-verbose) transaction and reads embit's parsed TransactionOutput.value directly - already an exact integer, no float conversion involved at all. A pending_transaction that's no longer "pending" by the time bump_fee actually runs (it confirmed in the meantime, a normal race) is now a quiet no-op returning None, rather than being folded into RbfBumper's error-logging path. Suite grows from 214 to 217 tests. BUGS.md moves B-40 to Previously fixed, and trims its own now-stale claim that bump_fee still depended on verbose=True (B-41) - it no longer does.
This commit is contained in:
1 parent
97545ad91f
commit
08c566d547
3 files changed
+231
-99
No files matched your search
+139
-23
@@ -3,7 +3,7 @@ from datetime import datetime, timedelta, timezone
|
||||
import pytest
|
||||
from embit import script
|
||||
from embit.bip32 import HDKey
|
||||
from embit.transaction import Transaction
|
||||
from embit.transaction import Transaction, TransactionInput, TransactionOutput
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from app.config import settings
|
||||
@@ -58,12 +58,23 @@ def test_should_bump_measures_from_last_broadcast_not_first(monkeypatch):
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""B-40: _prevout_amount now asks for the raw (non-verbose) transaction and
|
||||
reads its output value as an integer via embit, rather than a verbose reply's
|
||||
float "value" field — so this fake must hand back a real, parseable raw tx
|
||||
whose vout[0] carries the requested amount (every test here spends vout 0 of
|
||||
its fixture UTXO)."""
|
||||
|
||||
def __init__(self, prevout_values: dict[str, int]):
|
||||
self._prevout_values = prevout_values
|
||||
self.broadcasted: list[str] = []
|
||||
|
||||
async def get_transaction(self, txid: str, verbose: bool = False) -> dict:
|
||||
return {"vout": {0: {"value": self._prevout_values[txid] / 100_000_000}}}
|
||||
async def get_transaction(self, txid: str, verbose: bool = False) -> str:
|
||||
assert verbose is False
|
||||
fake_prevout_tx = Transaction(
|
||||
vin=[TransactionInput(b"\x00" * 32, 0)],
|
||||
vout=[TransactionOutput(self._prevout_values[txid], script.Script(b"\x00\x14" + b"\x00" * 20))],
|
||||
)
|
||||
return fake_prevout_tx.serialize().hex()
|
||||
|
||||
async def broadcast(self, raw_tx_hex: str) -> str:
|
||||
self.broadcasted.append(raw_tx_hex)
|
||||
@@ -130,9 +141,7 @@ async def test_bump_fee_shrinks_change_and_rebroadcasts(session_factory):
|
||||
|
||||
client = FakeClient({utxo_txid: utxo_amount})
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
new_txid = await bump_fee(session, client, row)
|
||||
new_txid = await bump_fee(session_factory, client, pending_id)
|
||||
|
||||
assert client.broadcasted
|
||||
assert new_txid != built.txid
|
||||
@@ -197,9 +206,7 @@ async def test_bump_fee_leaves_broadcast_at_untouched(session_factory):
|
||||
client = FakeClient({utxo_txid: utxo_amount})
|
||||
before_bump = datetime.now(timezone.utc)
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
await bump_fee(session, client, row)
|
||||
await bump_fee(session_factory, client, pending_id)
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
@@ -246,10 +253,8 @@ async def test_bump_fee_raises_when_no_change_output(session_factory):
|
||||
|
||||
client = FakeClient({utxo_txid: utxo_amount})
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
with pytest.raises(RbfError):
|
||||
await bump_fee(session, client, row)
|
||||
with pytest.raises(RbfError):
|
||||
await bump_fee(session_factory, client, pending_id)
|
||||
|
||||
|
||||
async def test_bump_fee_retargets_every_stored_txid(session_factory):
|
||||
@@ -303,9 +308,7 @@ async def test_bump_fee_retargets_every_stored_txid(session_factory):
|
||||
await session.commit()
|
||||
pending_id = pending.id
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
new_txid = await bump_fee(session, FakeClient({utxo_txid: utxo_amount}), row)
|
||||
new_txid = await bump_fee(session_factory, FakeClient({utxo_txid: utxo_amount}), pending_id)
|
||||
|
||||
async with session_factory() as session:
|
||||
from sqlalchemy import select
|
||||
@@ -378,9 +381,7 @@ async def test_bump_fee_meets_bip125_minimum_when_old_fee_already_exceeds_target
|
||||
inflated_excess = 50_000
|
||||
client = FakeClient({utxo_txid: utxo_amount + inflated_excess})
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
new_txid = await bump_fee(session, client, row)
|
||||
new_txid = await bump_fee(session_factory, client, pending_id)
|
||||
|
||||
assert client.broadcasted
|
||||
new_tx = Transaction.parse(bytes.fromhex(client.broadcasted[0]))
|
||||
@@ -442,9 +443,124 @@ async def test_bump_fee_refuses_once_at_the_max_fee_rate(session_factory):
|
||||
|
||||
client = FakeClient({utxo_txid: utxo_amount})
|
||||
|
||||
async with session_factory() as session:
|
||||
row = await session.get(PendingTransaction, pending_id)
|
||||
with pytest.raises(RbfError):
|
||||
await bump_fee(session, client, row)
|
||||
with pytest.raises(RbfError):
|
||||
await bump_fee(session_factory, client, pending_id)
|
||||
|
||||
assert not client.broadcasted
|
||||
|
||||
|
||||
# --- B-40: bump_fee must not hold a DB session open across its network calls,
|
||||
# and a row that's no longer pending by the time it runs is a quiet no-op. -------
|
||||
|
||||
|
||||
async def test_bump_fee_holds_no_session_open_during_network_calls(session_factory):
|
||||
"""The get_transaction-per-input reads and the broadcast must happen with no
|
||||
DB session held open — the same shape used elsewhere for this reason (B-18,
|
||||
electrum/listener.py's refresh_user for B-31) — otherwise a session sits
|
||||
idle in the pool for the whole duration of what can be several slow network
|
||||
round-trips."""
|
||||
from app.wallet.hd import derive_user_address, derive_user_key
|
||||
|
||||
signer = derive_user_key(0)
|
||||
my_address = derive_user_address(0)
|
||||
from_script = script.p2wpkh(signer.to_public())
|
||||
to_address = script.p2wpkh(_key(94).to_public()).address(network=PLM_MAINNET)
|
||||
|
||||
utxo_amount = 150_000_000
|
||||
utxo_txid = "77" * 32
|
||||
built = build_signed_transaction(
|
||||
signing_key=signer,
|
||||
from_script=from_script,
|
||||
utxos=[Utxo(utxo_txid, 0, utxo_amount)],
|
||||
to_address=to_address,
|
||||
amount_sats=10_000_000,
|
||||
change_address=my_address,
|
||||
fee_rate_sat_vb=1,
|
||||
)
|
||||
|
||||
async with session_factory() as session:
|
||||
user = User(username="frank", password_hash="x", derivation_index=0, address=my_address)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
pending = PendingTransaction(
|
||||
kind="bet",
|
||||
user_id=user.id,
|
||||
current_txid=built.txid,
|
||||
fee_rate_sat_vb=1,
|
||||
raw_tx_hex=built.raw_hex,
|
||||
status="pending",
|
||||
broadcast_at=datetime.now(timezone.utc) - timedelta(seconds=1000),
|
||||
)
|
||||
session.add(pending)
|
||||
await session.commit()
|
||||
pending_id = pending.id
|
||||
|
||||
open_count = {"n": 0}
|
||||
|
||||
class _TrackedSession:
|
||||
def __init__(self, inner):
|
||||
self._inner = inner
|
||||
|
||||
async def __aenter__(self):
|
||||
result = await self._inner.__aenter__()
|
||||
open_count["n"] += 1
|
||||
return result
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
open_count["n"] -= 1
|
||||
return await self._inner.__aexit__(*exc)
|
||||
|
||||
def tracking_session_factory():
|
||||
return _TrackedSession(session_factory())
|
||||
|
||||
class TrackingClient(FakeClient):
|
||||
async def get_transaction(self, txid, verbose=False):
|
||||
assert open_count["n"] == 0, "a session was held open during a network call"
|
||||
return await super().get_transaction(txid, verbose)
|
||||
|
||||
async def broadcast(self, raw_tx_hex):
|
||||
assert open_count["n"] == 0, "a session was held open during the broadcast"
|
||||
return await super().broadcast(raw_tx_hex)
|
||||
|
||||
client = TrackingClient({utxo_txid: utxo_amount})
|
||||
await bump_fee(tracking_session_factory, client, pending_id)
|
||||
|
||||
assert client.broadcasted
|
||||
assert open_count["n"] == 0 # nothing left open afterwards either
|
||||
|
||||
|
||||
async def test_bump_fee_is_a_noop_when_no_longer_pending(session_factory):
|
||||
"""A row can legitimately confirm (or otherwise leave "pending") between
|
||||
being read as due and RbfBumper actually attempting the bump — a normal
|
||||
race, not an error. Must return quietly rather than raising or touching
|
||||
the network."""
|
||||
async with session_factory() as session:
|
||||
user = User(username="grace", password_hash="x", derivation_index=0, address="plm1qxxx")
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
pending = PendingTransaction(
|
||||
kind="bet",
|
||||
user_id=user.id,
|
||||
current_txid="already-confirmed-txid",
|
||||
fee_rate_sat_vb=1,
|
||||
raw_tx_hex="00",
|
||||
status="confirmed",
|
||||
broadcast_at=datetime.now(timezone.utc) - timedelta(seconds=1000),
|
||||
)
|
||||
session.add(pending)
|
||||
await session.commit()
|
||||
pending_id = pending.id
|
||||
|
||||
client = FakeClient({})
|
||||
|
||||
result = await bump_fee(session_factory, client, pending_id)
|
||||
|
||||
assert result is None
|
||||
assert not client.broadcasted
|
||||
|
||||
|
||||
async def test_bump_fee_is_a_noop_when_the_row_is_gone(session_factory):
|
||||
client = FakeClient({})
|
||||
result = await bump_fee(session_factory, client, 999_999)
|
||||
assert result is None
|
||||
assert not client.broadcasted
|
||||
Reference in new issue
Block a user