Compare commits

...
Author SHA1 Message Date
9qeklajc d12888e724 fix: audit auto-topup Cashu transactions 2026-07-12 14:52:41 +02:00
2 changed files with 154 additions and 2 deletions
+43 -2
View File
@@ -4,7 +4,12 @@ import json
from sqlmodel import select
from ..core import get_logger
from ..core.db import UpstreamProviderRow, create_session
from ..core.db import (
CashuTransaction,
UpstreamProviderRow,
create_session,
store_cashu_transaction,
)
from ..wallet import send_token
from .routstr import RoutstrUpstreamProvider
@@ -63,6 +68,26 @@ async def _run_auto_topup_cycle() -> None:
)
async def _mark_topup_collected(token: str) -> None:
"""Mark the outgoing auto-topup transaction as consumed by the provider."""
async with create_session() as session:
result = await session.exec(
select(CashuTransaction).where(
CashuTransaction.token == token,
CashuTransaction.type == "out",
)
)
transaction = result.first()
if transaction is None:
logger.critical(
"Auto top-up transaction disappeared before collection update"
)
return
transaction.collected = True
session.add(transaction)
await session.commit()
async def _check_and_topup(row: UpstreamProviderRow) -> None:
"""Check a single provider's balance and top up if below threshold."""
# Parse provider settings
@@ -123,7 +148,6 @@ async def _check_and_topup(row: UpstreamProviderRow) -> None:
},
)
print(amount, mint_url)
try:
token = await send_token(amount, "sat", mint_url)
except Exception as e:
@@ -138,6 +162,22 @@ async def _check_and_topup(row: UpstreamProviderRow) -> None:
)
return
transaction_stored = await store_cashu_transaction(
token=token,
amount=amount,
unit="sat",
mint_url=mint_url,
typ="out",
collected=False,
source="auto_topup",
)
if not transaction_stored:
logger.error(
"Aborting auto top-up because the token could not be persisted",
extra={"provider_id": row.id, "amount": amount, "mint_url": mint_url},
)
return
result = await provider.topup(token)
if "error" in result:
@@ -149,6 +189,7 @@ async def _check_and_topup(row: UpstreamProviderRow) -> None:
},
)
else:
await _mark_topup_collected(token)
logger.info(
"Auto top-up completed successfully",
extra={
+111
View File
@@ -0,0 +1,111 @@
import json
from unittest.mock import AsyncMock, Mock, call
import pytest
from routstr.core.db import UpstreamProviderRow
from routstr.upstream import auto_topup
def _row() -> UpstreamProviderRow:
return UpstreamProviderRow(
id=7,
provider_type="routstr",
base_url="https://provider.example",
api_key="secret",
provider_settings=json.dumps(
{
"auto_topup": True,
"topup_threshold": 100,
"topup_amount_limit": 250,
"topup_mint_url": "https://mint.example",
}
),
)
def _configure(
monkeypatch: pytest.MonkeyPatch, topup_result: object
) -> tuple[AsyncMock, AsyncMock, AsyncMock]:
provider = Mock()
provider.get_balance = AsyncMock(return_value=50_000)
if isinstance(topup_result, Exception):
provider.topup = AsyncMock(side_effect=topup_result)
else:
provider.topup = AsyncMock(return_value=topup_result)
send_token = AsyncMock(return_value="cashuBoutgoing")
store_transaction = AsyncMock(return_value=True)
mark_collected = AsyncMock()
monkeypatch.setattr(
auto_topup.RoutstrUpstreamProvider,
"from_db_row",
Mock(return_value=provider),
)
monkeypatch.setattr(auto_topup, "send_token", send_token)
monkeypatch.setattr(auto_topup, "store_cashu_transaction", store_transaction)
monkeypatch.setattr(auto_topup, "_mark_topup_collected", mark_collected)
return provider.topup, store_transaction, mark_collected
@pytest.mark.asyncio
async def test_auto_topup_marks_persisted_token_collected_after_success(
monkeypatch: pytest.MonkeyPatch,
) -> None:
topup, store_transaction, mark_collected = _configure(monkeypatch, {"ok": True})
await auto_topup._check_and_topup(_row())
store_transaction.assert_awaited_once_with(
token="cashuBoutgoing",
amount=250,
unit="sat",
mint_url="https://mint.example",
typ="out",
collected=False,
source="auto_topup",
)
topup.assert_awaited_once_with("cashuBoutgoing")
mark_collected.assert_awaited_once_with("cashuBoutgoing")
@pytest.mark.asyncio
async def test_auto_topup_leaves_persisted_token_uncollected_on_provider_failure(
monkeypatch: pytest.MonkeyPatch,
) -> None:
topup, store_transaction, mark_collected = _configure(
monkeypatch, {"error": "rejected"}
)
await auto_topup._check_and_topup(_row())
assert store_transaction.await_args_list == [
call(
token="cashuBoutgoing",
amount=250,
unit="sat",
mint_url="https://mint.example",
typ="out",
collected=False,
source="auto_topup",
)
]
topup.assert_awaited_once_with("cashuBoutgoing")
mark_collected.assert_not_awaited()
@pytest.mark.asyncio
async def test_auto_topup_leaves_persisted_token_uncollected_on_provider_exception(
monkeypatch: pytest.MonkeyPatch,
) -> None:
topup, store_transaction, mark_collected = _configure(
monkeypatch, RuntimeError("upstream unavailable")
)
with pytest.raises(RuntimeError, match="upstream unavailable"):
await auto_topup._check_and_topup(_row())
store_transaction.assert_awaited_once()
topup.assert_awaited_once_with("cashuBoutgoing")
mark_collected.assert_not_awaited()