53 lines
2.6 KiB
Python
53 lines
2.6 KiB
Python
"""The versions of a pending transaction (B-77, DAT-70, DAT-71, TX-19).
|
|||
|
|
|
||
|
|
A bumped transaction has several txids and any of them may be the one that confirms.
|
||
|
|
Everything that looks a transaction up on the chain asks for all of them."""
|
||
|
|
|
||
|
|
from sqlalchemy import delete, select
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from app.db.models import PendingTransaction, PendingTransactionTxid
|
||
|
|
|
||
|
|
|
||
|
|
async def record_version(session: AsyncSession, pending: PendingTransaction, txid: str, raw_hex: str) -> None:
|
||
|
|
"""Write `txid` as a version of `pending` in the caller's transaction. Idempotent for
|
||
|
|
the same pair (a bump retried after an uncertain broadcast rebuilds the same
|
||
|
|
transaction); a txid already held by another row is an error — it is unique across
|
||
|
|
the platform."""
|
||
|
|
if pending.id is None:
|
||
|
|
await session.flush()
|
||
|
|
existing = await session.scalar(select(PendingTransactionTxid).where(PendingTransactionTxid.txid == txid))
|
||
|
|
if existing is not None:
|
||
|
|
if existing.pending_transaction_id != pending.id:
|
||
|
|
raise ValueError(f"txid {txid} already belongs to pending_transaction {existing.pending_transaction_id}")
|
||
|
|
return
|
||
|
|
session.add(PendingTransactionTxid(pending_transaction_id=pending.id, txid=txid, raw_hex=raw_hex))
|
||
|
|
|
||
|
|
|
||
|
|
async def txids_of(session: AsyncSession, pending: PendingTransaction) -> set[str]:
|
||
|
|
"""Every txid of the row: all its recorded versions plus `current_txid` (a row
|
||
|
|
written before the table existed, or by a test, may have no version row for it)."""
|
||
|
|
rows = await session.scalars(
|
||
|
|
select(PendingTransactionTxid.txid).where(PendingTransactionTxid.pending_transaction_id == pending.id)
|
||
|
|
)
|
||
|
|
return {pending.current_txid, *rows.all()}
|
||
|
|
|
||
|
|
|
||
|
|
async def txids_by_row(session: AsyncSession, current: dict[int, str]) -> dict[int, set[str]]:
|
||
|
|
"""`txids_of` for many rows at once; `current` maps row id -> current_txid."""
|
||
|
|
result = {row_id: {txid} for row_id, txid in current.items()}
|
||
|
|
if not result:
|
||
|
|
return result
|
||
|
|
rows = await session.execute(
|
||
|
|
select(PendingTransactionTxid.pending_transaction_id, PendingTransactionTxid.txid).where(
|
||
|
|
PendingTransactionTxid.pending_transaction_id.in_(list(result))
|
||
|
|
)
|
||
|
|
)
|
||
|
|
for row_id, txid in rows.all():
|
||
|
|
result[row_id].add(txid)
|
||
|
|
return result
|
||
|
|
|
||
|
|
|
||
|
|
async def delete_versions(session: AsyncSession, pending_id: int) -> None:
|
||
|
|
"""The versions go with a `bet` row that a verified refusal deletes (DAT-38)."""
|
||
|
|
await session.execute(delete(PendingTransactionTxid).where(PendingTransactionTxid.pending_transaction_id == pending_id))
|