Blink funding source: Reduce payment-status polling, add caching and backoff (#4042)
What changed, and why it matters
This commit rewrites how LNbits talks to the Blink Bitcoin Lightning wallet provider. It adds a rate limiter (to avoid hammering Blink's API), caches payment-status answers, spaces out repeated status checks with increasing delays, and fixes a bug where a failed BOLT11 invoice decode could crash a payment. The changes are defensive: they reduce API load and make payment handling more robust, but they also introduce new concurrency and caching logic that could hide edge-case bugs.
Review the new caching and lock cleanup paths for memory leaks or stale-state bugs; verify that _status_locks entries are always removed when terminal status is reached or on cache expiry; run the new unit tests and integration tests against a real Blink environment; monitor for stuck pending invoices after this change.
Security signals we found
New rate limiter reduces risk of API abuse / self-DoS against Blink GraphQL endpoint
Caching of terminal payment status may mask stale or incorrect state if cache invalidation is incomplete
Concurrent status-check coalescing with per-checking_id lock could leak memory if locks are not removed on all paths
pay_invoice now catches BOLT11 decode failures and returns a structured error rather than raising
pay_invoice now returns pending PaymentResponse with checking_id on API exception, improving idempotency but relying on caller to retry
WebSocket listener runs in a background task and is cancelled on stream exit; shutdown flag added
Evidence from the diff
The patch refactors lnbits/wallets/blink.py: introduces a TokenBucket (120 req/60s) around GraphQL queries, adds a PaymentStatus cache with separate TTLs for pending (30s) and terminal (24h) states, tracks pending invoices with an exponential backoff lookup schedule, coalesces concurrent status checks per checking_id with asyncio.Lock, and restructures paid_invoices_stream to use a background WebSocket listener feeding an asyncio.Queue plus a maintenance loop. It also hardens pay_invoice by catching bolt11 decode exceptions and returning a pending PaymentResponse with checking_id on API failure instead of a misleading connection error. Tests are added for the new components.
Changed components
lnbits/wallets/blink.pytests/wallets/test_blink.pyBlinkWallet classTokenBucket rate limiterpayment status cachepending invoice trackerpaid_invoices_stream WebSocket listenerInspect captured patch +485 / −37
diff --git a/lnbits/wallets/blink.py b/lnbits/wallets/blink.py
index b2f05e0..97cd3cf 100644
--- a/lnbits/wallets/blink.py
+++ b/lnbits/wallets/blink.py
@@ -1,6 +1,8 @@
import asyncio
import hashlib
import json
+import random
+import time
from collections.abc import AsyncGenerator
import httpx
@@ -21,6 +23,47 @@ from .base import (
)
+class TokenBucket:
+ """Token bucket rate limiter for Blink GraphQL API."""
+
+ def __init__(self, rate: int, period_seconds: int) -> None:
+ self.rate = rate
+ self.period = period_seconds
+ self.tokens = rate
+ self.last_refill = time.monotonic()
+ self.lock = asyncio.Lock()
+
+ async def consume(self) -> None:
+ async with self.lock:
+ now = time.monotonic()
+ elapsed = now - self.last_refill
+ if elapsed > 0:
+ new_tokens = int((elapsed / self.period) * self.rate)
+ self.tokens = min(self.rate, self.tokens + new_tokens)
+ self.last_refill = now
+ if self.tokens < 1:
+ wait_time = (self.period / self.rate) * (1 - self.tokens)
+ await asyncio.sleep(wait_time)
+ self.last_refill = time.monotonic()
+ self.tokens = 1
+ self.tokens -= 1
+
+
+_INVOICE_STATUS_MAP = {
+ "EXPIRED": False,
+ "PENDING": None,
+ "PAID": True,
+}
+
+_PAYMENT_STATUS_MAP = {
+ "FAILURE": False,
+ "EXPIRED": False,
+ "PENDING": None,
+ "PAID": True,
+ "SUCCESS": True,
+}
+
+
class BlinkWallet(Wallet):
"""https://dev.blink.sv/"""
@@ -34,6 +77,8 @@ class BlinkWallet(Wallet):
if not settings.blink_token:
raise ValueError("cannot initialize BlinkWallet: missing blink_token")
+ super().__init__()
+
self.endpoint = normalize_endpoint(settings.blink_api_endpoint)
self.auth = {
@@ -48,6 +93,27 @@ class BlinkWallet(Wallet):
self.client = httpx.AsyncClient(base_url=self.endpoint, headers=self.auth)
self.ws = None
self._wallet_id = None
+ self._shutdown = False
+
+ # Rate limiter: 120 requests per 60 seconds for GraphQL
+ self._graphql_limiter = TokenBucket(120, 60)
+
+ # Payment status cache
+ self.payment_status_cache: dict[str, dict] = {}
+ self.payment_status_cache_pending_ttl = 30
+ self.payment_status_cache_terminal_ttl = 60 * 60 * 24
+
+ # Pending invoice tracking
+ self.pending_invoice_details: dict[str, dict] = {}
+ self.pending_invoices_lookup_cooldown = 1.0
+ self.pending_invoices_maintenance_interval = 5
+ self.lookup_backoff_schedule = [30, 60, 120, 300, 600, 1200, 1800]
+
+ # Paid invoice queue for paid_invoices_stream
+ self.paid_invoices_queue: asyncio.Queue[str] = asyncio.Queue()
+
+ # Locks for coalescing concurrent status checks
+ self._status_locks: dict[str, asyncio.Lock] = {}
@property
def wallet_id(self):
@@ -56,6 +122,7 @@ class BlinkWallet(Wallet):
raise ValueError("Wallet id not initialized.")
async def cleanup(self):
+ self._shutdown = True
try:
await self.client.aclose()
except RuntimeError as e:
@@ -90,7 +157,6 @@ class BlinkWallet(Wallet):
if btc_balance is None:
return StatusResponse("No BTC balance", 0)
- # multiply balance by 1000 to get msats balance
return StatusResponse(None, btc_balance * 1000)
except ValueError as exc:
return StatusResponse(str(exc), 0)
@@ -106,8 +172,6 @@ class BlinkWallet(Wallet):
unhashed_description: bytes | None = None,
**kwargs,
) -> InvoiceResponse:
- # https://dev.blink.sv/api/btc-ln-receive
-
invoice_variables = {
"input": {
"amount": amount,
@@ -150,7 +214,12 @@ class BlinkWallet(Wallet):
.get("paymentHash", None)
)
- # TODO: add preimage to response
+ if checking_id:
+ created_at = int(time.time())
+ expiry = kwargs.get("expiry", 3600)
+ expires_at = created_at + expiry
+ self._track_pending_invoice(checking_id, created_at, expires_at)
+
return InvoiceResponse(
ok=True, checking_id=checking_id, payment_request=payment_request
)
@@ -203,7 +272,12 @@ class BlinkWallet(Wallet):
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
# https://dev.blink.sv/api/btc-ln-send
- invoice = bolt11_lib.decode(bolt11)
+ try:
+ invoice = bolt11_lib.decode(bolt11)
+ payment_hash = invoice.payment_hash
+ except Exception as e:
+ logger.warning(f"Failed to decode bolt11: {e}")
+ return PaymentResponse(ok=False, error_message=f"Invalid bolt11: {e}")
# Only amount invoices can be probed: lnInvoiceFeeProbe takes no amount,
# and zero-amount invoices have no amount to probe with (pay_invoice
@@ -262,7 +336,7 @@ class BlinkWallet(Wallet):
error_message=error_message,
)
- checking_id = invoice.payment_hash
+ checking_id = payment_hash
payment_status = await self.get_payment_status(checking_id)
fee_msat = payment_status.fee_msat
@@ -276,18 +350,18 @@ class BlinkWallet(Wallet):
except Exception as exc:
logger.info(f"Failed to pay invoice {bolt11}")
logger.warning(exc)
- return PaymentResponse(
- error_message=f"Unable to connect to {self.endpoint}."
- )
+ return PaymentResponse(checking_id=payment_hash)
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
+ cached = self._get_cached_payment_status(checking_id)
+ if cached is not None:
+ return cached
- statuses = {
- "EXPIRED": False,
- "PENDING": None,
- "PAID": True,
- }
+ status = await self._fetch_invoice_status(checking_id)
+ self._cache_payment_status(checking_id, status)
+ return status
+ async def _fetch_invoice_status(self, checking_id: str) -> PaymentStatus:
variables = {"paymentHash": checking_id, "walletId": self.wallet_id}
data = {"query": q.status_query, "variables": variables}
@@ -300,27 +374,41 @@ class BlinkWallet(Wallet):
status = response["data"]["me"]["defaultAccount"]["walletById"][
"invoiceByPaymentHash"
]["paymentStatus"]
- return PaymentStatus(statuses[status])
+ return PaymentStatus(_INVOICE_STATUS_MAP[status])
except Exception as e:
logger.warning(f"Error getting invoice status: {e}")
return PaymentStatus(None)
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
+ cached = self._get_cached_payment_status(checking_id)
+ if cached is not None:
+ return cached
+
+ lock = self._status_locks.get(checking_id)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._status_locks[checking_id] = lock
+
+ async with lock:
+ cached = self._get_cached_payment_status(checking_id)
+ if cached is not None:
+ return cached
+
+ status = await self._fetch_payment_status(checking_id)
+ self._cache_payment_status(checking_id, status)
+ if status.paid is not None:
+ self._status_locks.pop(checking_id, None)
+
+ return status
+
+ async def _fetch_payment_status(self, checking_id: str) -> PaymentStatus:
variables = {
"walletId": self.wallet_id,
"transactionsByPaymentHash": checking_id,
}
data = {"query": q.tx_query, "variables": variables}
- statuses = {
- "FAILURE": False,
- "EXPIRED": False,
- "PENDING": None,
- "PAID": True,
- "SUCCESS": True,
- }
-
try:
response = await self._graphql_query(data)
@@ -341,18 +429,40 @@ class BlinkWallet(Wallet):
status = tx_data.get("status")
return PaymentStatus(
- paid=statuses[status], fee_msat=fee * 1000, preimage=preimage
+ paid=_PAYMENT_STATUS_MAP[status],
+ fee_msat=fee * 1000,
+ preimage=preimage,
)
except Exception as e:
logger.error(f"Error getting payment status: {e}")
return PaymentStatus(None)
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
+ ws_task = asyncio.create_task(self._ws_payment_listener())
+ try:
+ while settings.lnbits_running:
+ try:
+ value = await asyncio.wait_for(
+ self.paid_invoices_queue.get(),
+ timeout=self.pending_invoices_maintenance_interval,
+ )
+ yield value
+ except asyncio.TimeoutError:
+ await self._maintain_pending_invoices()
+ finally:
+ ws_task.cancel()
+ try:
+ await ws_task
+ except asyncio.CancelledError:
+ pass
+
+ async def _ws_payment_listener(self):
subscription_id = "blink_payment_stream"
- while settings.lnbits_running:
+ while settings.lnbits_running and not self._shutdown:
try:
async with connect(
- self.ws_endpoint, subprotocols=[Subprotocol("graphql-transport-ws")]
+ self.ws_endpoint,
+ subprotocols=[Subprotocol("graphql-transport-ws")],
) as ws:
logger.info("Connected to blink invoices stream.")
self.ws = ws
@@ -366,11 +476,14 @@ class BlinkWallet(Wallet):
subscription_req = {
"id": subscription_id,
"type": "subscribe",
- "payload": {"query": q.my_updates_query, "variables": {}},
+ "payload": {
+ "query": q.my_updates_query,
+ "variables": {},
+ },
}
await ws.send(json.dumps(subscription_req))
- while settings.lnbits_running:
+ while settings.lnbits_running and not self._shutdown:
message = await ws.recv()
resp = json.loads(message)
if resp.get("id") != subscription_id:
@@ -390,25 +503,81 @@ class BlinkWallet(Wallet):
payment_hash = tx.get("initiationVia").get("paymentHash")
if payment_hash:
- yield payment_hash
+ self._remove_pending_invoice(payment_hash)
+ self.paid_invoices_queue.put_nowait(payment_hash)
except Exception as exc:
logger.error(
f"lost connection to blink invoices stream: '{exc}'"
- "retrying in 5 seconds"
+ " retrying in 5 seconds"
)
await asyncio.sleep(5)
+ async def _maintain_pending_invoices(self):
+ if not self.pending_invoices:
+ return
+
+ now = time.time()
+ self._expire_pending_invoices(now)
+ if not self.pending_invoices:
+ return
+
+ due = self._get_due_pending_invoices(now)
+ if not due:
+ return
+
+ await self._process_due_invoices(due, now)
+
+ def _get_due_pending_invoices(self, now: float) -> list[dict]:
+ due = []
+ for cid in list(self.pending_invoices):
+ invoice = self.pending_invoice_details.get(cid)
+ if invoice and invoice.get("next_lookup_at", 0) <= now:
+ due.append(invoice)
+ due.sort(key=lambda inv: inv.get("next_lookup_at", 0))
+ return due
+
+ async def _process_due_invoices(self, due: list[dict], now: float) -> None:
+ for index, invoice in enumerate(due):
+ cid = invoice["checking_id"]
+ if cid not in self.pending_invoices:
+ continue
+ settled = await self._lookup_single_pending_invoice(cid, now)
+ if (
+ not settled
+ and index < len(due) - 1
+ and self.pending_invoices_lookup_cooldown > 0
+ ):
+ await asyncio.sleep(self.pending_invoices_lookup_cooldown)
+
+ async def _lookup_single_pending_invoice(self, cid: str, now: float) -> bool:
+ try:
+ status = await self.get_invoice_status(cid)
+ if status.paid:
+ self._remove_pending_invoice(cid)
+ self.paid_invoices_queue.put_nowait(cid)
+ return True
+ if status.failed:
+ self._remove_pending_invoice(cid)
+ return True
+ invoice = self.pending_invoice_details.get(cid)
+ if invoice:
+ invoice["lookup_attempts"] = int(invoice.get("lookup_attempts", 0)) + 1
+ self._schedule_next_lookup(invoice, now)
+ except Exception:
+ invoice = self.pending_invoice_details.get(cid)
+ if invoice:
+ invoice["lookup_attempts"] = int(invoice.get("lookup_attempts", 0)) + 1
+ self._schedule_next_lookup(invoice, now)
+ return False
+
async def _graphql_query(self, payload) -> dict:
+ await self._graphql_limiter.consume()
response = await self.client.post(self.endpoint, json=payload, timeout=10)
response.raise_for_status()
return response.json()
async def _init_wallet_id(self) -> str:
- """
- Get the defaultAccount wallet id, required for payments.
- """
-
if self._wallet_id:
return self._wallet_id
@@ -437,6 +606,71 @@ class BlinkWallet(Wallet):
logger.warning(exc)
raise ValueError(f"Unable to connect to '{self.endpoint}'") from exc
+ # ── Cache helpers ──────────────────────────────────────────────
+
+ def _cache_payment_status(self, checking_id: str, status: PaymentStatus) -> None:
+ ttl = (
+ self.payment_status_cache_terminal_ttl
+ if status.paid is not None
+ else self.payment_status_cache_pending_ttl
+ )
+ self.payment_status_cache[checking_id] = {
+ "status": status,
+ "expires_at": time.time() + ttl,
+ }
+
+ def _get_cached_payment_status(self, checking_id: str) -> PaymentStatus | None:
+ cached = self.payment_status_cache.get(checking_id)
+ if not cached:
+ return None
+ if cached["expires_at"] <= time.time():
+ self.payment_status_cache.pop(checking_id, None)
+ return None
+ return cached["status"]
+
+ # ── Pending invoice helpers ────────────────────────────────────
+
+ def _track_pending_invoice(
+ self, checking_id: str, created_at: int, expires_at: int
+ ) -> None:
+ invoice = self.pending_invoice_details.get(checking_id, {})
+ invoice["checking_id"] = checking_id
+ invoice["created_at"] = created_at
+ invoice["expires_at"] = expires_at
+ invoice.setdefault("lookup_attempts", 0)
+ invoice.setdefault("last_lookup_at", 0.0)
+ self.pending_invoice_details[checking_id] = invoice
+ if checking_id not in self.pending_invoices:
+ self.pending_invoices.append(checking_id)
+ if "next_lookup_at" not in invoice:
+ self._schedule_next_lookup(invoice, created_at)
+
+ def _remove_pending_invoice(self, checking_id: str) -> bool:
+ self.pending_invoice_details.pop(checking_id, None)
+ if checking_id in self.pending_invoices:
+ self.pending_invoices.remove(checking_id)
+ return True
+ return False
+
+ def _schedule_next_lookup(self, invoice: dict, now: float | None = None) -> None:
+ now = now or time.time()
+ attempt = int(invoice.get("lookup_attempts", 0))
+ delay = self.lookup_backoff_schedule[
+ min(attempt, len(self.lookup_backoff_schedule) - 1)
+ ]
+ jitter = random.uniform(0, min(15, max(1, delay * 0.1))) # noqa: S311
+ invoice["next_lookup_at"] = now + delay + jitter
+
+ def _expire_pending_invoices(self, now: float) -> None:
+ expired = []
+ for cid in list(self.pending_invoices):
+ invoice = self.pending_invoice_details.get(cid, {})
+ expires_at = int(invoice.get("expires_at", 0) or 0)
+ if expires_at and now > expires_at:
+ expired.append(cid)
+ for cid in expired:
+ self._remove_pending_invoice(cid)
+
class BlinkGrafqlQueries(BaseModel):
balance_query: str
diff --git a/tests/wallets/test_blink.py b/tests/wallets/test_blink.py
index f9ba016..170a4cc 100644
--- a/tests/wallets/test_blink.py
+++ b/tests/wallets/test_blink.py
@@ -1,6 +1,8 @@
+import asyncio
import os
+import time
from typing import cast
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from loguru import logger
@@ -8,6 +10,7 @@ from loguru import logger
from lnbits.settings import settings
from lnbits.wallets import BlinkWallet, get_funding_source, set_funding_source
from lnbits.wallets.base import PaymentStatus
+from lnbits.wallets.blink import TokenBucket
settings.lnbits_backend_wallet_class = "BlinkWallet"
settings.blink_token = "mock"
@@ -38,18 +41,19 @@ assert isinstance(funding_source, BlinkWallet)
@pytest.fixture(scope="session")
def payhash():
- # put your external payment hash here
payment_hash = "14d7899c3456bcd78f7f18a70d782b8eadb2de974e80dc5120e133032423dcda"
return payment_hash
@pytest.fixture(scope="session")
def outbound_bolt11():
- # put your outbound bolt11 here
bolt11 = "lnbc1u1pjl0uhypp5yxvdqq923atm9ywkpgtu3yxv9w2n44ensrkwfyagvmzqhml2x9gqdpv2phhwetjv4jzqcneypqyc6t8dp6xu6twva2xjuzzda6qcqzzsxqrrsssp5h3qlnnlfqekquacwwj9yu7fhujyzxhzqegpxenscw45pgv6xakfq9qyyssqqjruygw0jrcg3365jksxn6yhsxx7c5pdjrjdlyvuhs7xh8r409h4e3kucc54kgh34pscaq3mg7hn55l8a0qszgzex80amwrp4gkdgqcpkse88y" # noqa: E501
return bolt11
+# ── Integration tests (require BLINK_TOKEN) ─────────────────────────
+
+
@pytest.mark.anyio
async def test_environment_variables():
if use_real_api:
@@ -151,6 +155,215 @@ async def test_get_payment_status(payhash):
assert True, "BLINK_TOKEN is not set. Skipping test using mock api"
+
+# ── Unit tests for internal components (no API needed) ──────────────
+
+
+class TestTokenBucket:
+ @pytest.mark.anyio
+ async def test_consume_allows_within_rate(self):
+ bucket = TokenBucket(10, 60)
+ for _ in range(10):
+ await bucket.consume()
+ # All consumed without blocking - tokens should be 0
+ assert bucket.tokens == 0
+
+ @pytest.mark.anyio
+ async def test_consume_blocks_when_exhausted(self):
+ bucket = TokenBucket(2, 10)
+ await bucket.consume()
+ await bucket.consume()
+ assert bucket.tokens == 0
+ # Next consume should wait - time it
+ start = time.monotonic()
+ await bucket.consume()
+ elapsed = time.monotonic() - start
+ assert elapsed >= 4.5 # ~5s per token at 2/10s rate
+
+ @pytest.mark.anyio
+ async def test_refills_over_time(self):
+ bucket = TokenBucket(60, 60)
+ for _ in range(60):
+ await bucket.consume()
+ assert bucket.tokens <= 0
+ # Manually advance time by 30 seconds
+ bucket.last_refill = time.monotonic() - 30
+ # Refill happens on next consume
+ await bucket.consume()
+ assert bucket.tokens >= 29 # should have refilled ~30 tokens
+
+ @pytest.mark.anyio
+ async def test_initial_tokens_full(self):
+ bucket = TokenBucket(100, 60)
+ assert bucket.tokens == 100
+
+
+class TestPaymentStatusCache:
+ @pytest.fixture
+ def wallet(self):
+ w = MagicMock(spec=BlinkWallet)
+ w.payment_status_cache = {}
+ w.payment_status_cache_pending_ttl = 30
+ w.payment_status_cache_terminal_ttl = 60 * 60 * 24
+ w._cache_payment_status = BlinkWallet._cache_payment_status.__get__(w)
+ w._get_cached_payment_status = BlinkWallet._get_cached_payment_status.__get__(w)
+ return w
+
+ def test_cache_terminal_status(self, wallet):
+ status = PaymentStatus(paid=True, fee_msat=1000, preimage="abc")
+ wallet._cache_payment_status("hash1", status)
+ cached = wallet._get_cached_payment_status("hash1")
+ assert cached is not None
+ assert cached.paid is True
+ assert cached.fee_msat == 1000
+ assert cached.preimage == "abc"
+
+ def test_cache_pending_status(self, wallet):
+ status = PaymentStatus(paid=None)
+ wallet._cache_payment_status("hash2", status)
+ cached = wallet._get_cached_payment_status("hash2")
+ assert cached is not None
+ assert cached.paid is None
+
+ def test_cache_expires_terminal_after_ttl(self, wallet):
+ status = PaymentStatus(paid=False)
+ wallet._cache_payment_status("hash3", status)
+ # Manually expire it
+ wallet.payment_status_cache["hash3"]["expires_at"] = time.time() - 1
+ cached = wallet._get_cached_payment_status("hash3")
+ assert cached is None
+
+ def test_cache_returns_none_for_missing(self, wallet):
+ cached = wallet._get_cached_payment_status("nonexistent")
+ assert cached is None
+
+ def test_terminal_ttl_longer_than_pending(self, wallet):
+ wallet._cache_payment_status("pending", PaymentStatus(paid=None))
+ wallet._cache_payment_status("terminal", PaymentStatus(paid=True))
+
+ pending_ttl = wallet.payment_status_cache["pending"]["expires_at"] - time.time()
+ terminal_ttl = (
+ wallet.payment_status_cache["terminal"]["expires_at"] - time.time()
+ )
+ assert terminal_ttl > pending_ttl
+
+
+class TestPendingInvoiceTracking:
+ @pytest.fixture
+ def wallet(self):
+ w = MagicMock(spec=BlinkWallet)
+ w.pending_invoices = []
+ w.pending_invoice_details = {}
+ w.pending_invoices_lookup_cooldown = 1.0
+ w.lookup_backoff_schedule = [30, 60, 120, 300, 600, 1200, 1800]
+ w._track_pending_invoice = BlinkWallet._track_pending_invoice.__get__(w)
+ w._remove_pending_invoice = BlinkWallet._remove_pending_invoice.__get__(w)
+ w._schedule_next_lookup = BlinkWallet._schedule_next_lookup.__get__(w)
+ w._expire_pending_invoices = BlinkWallet._expire_pending_invoices.__get__(w)
+ return w
+
+ def test_track_pending_invoice(self, wallet):
+ now = int(time.time())
+ wallet._track_pending_invoice("hash1", now, now + 3600)
+ assert "hash1" in wallet.pending_invoices
+ assert "hash1" in wallet.pending_invoice_details
+ assert wallet.pending_invoice_details["hash1"]["created_at"] == now
+ assert wallet.pending_invoice_details["hash1"]["lookup_attempts"] == 0
+
+ def test_track_pending_invoice_sets_next_lookup(self, wallet):
+ now = int(time.time())
+ wallet._track_pending_invoice("hash2", now, now + 3600)
+ assert "next_lookup_at" in wallet.pending_invoice_details["hash2"]
+ next_at = wallet.pending_invoice_details["hash2"]["next_lookup_at"]
+ # First backoff is 30s, so next_lookup_at should be ~now + 30
+ assert next_at >= now + 30
+
+ def test_remove_pending_invoice(self, wallet):
+ now = int(time.time())
+ wallet._track_pending_invoice("hash3", now, now + 3600)
+ result = wallet._remove_pending_invoice("hash3")
+ assert result is True
+ assert "hash3" not in wallet.pending_invoices
+ assert "hash3" not in wallet.pending_invoice_details
+
+ def test_remove_nonexistent_returns_false(self, wallet):
+ result = wallet._remove_pending_invoice("nonexistent")
+ assert result is False
+
+ def test_expire_pending_invoices(self, wallet):
+ now = int(time.time())
+ wallet._track_pending_invoice("expired1", now - 7200, now - 3600)
+ wallet._track_pending_invoice("valid1", now, now + 3600)
+ wallet._expire_pending_invoices(now)
+ assert "expired1" not in wallet.pending_invoices
+ assert "valid1" in wallet.pending_invoices
+
+ def test_schedule_next_lookup_backoff_increases(self, wallet):
+ now = float(time.time())
+ invoice = {"checking_id": "test", "lookup_attempts": 0}
+ wallet._schedule_next_lookup(invoice, now)
+ first_delay = invoice["next_lookup_at"] - now
+
+ invoice["lookup_attempts"] = 5
+ wallet._schedule_next_lookup(invoice, now)
+ fifth_delay = invoice["next_lookup_at"] - now
+
+ assert fifth_delay > first_delay
+
+
+class TestPayInvoiceDecodeFix:
+ @pytest.mark.anyio
+ async def test_pay_invoice_returns_pending_on_api_error(self):
+ w = MagicMock(spec=BlinkWallet)
+ w.pay_invoice = BlinkWallet.pay_invoice.__get__(w)
+ w._graphql_query = AsyncMock(side_effect=Exception("Connection failed"))
+ w.get_payment_status = AsyncMock()
+ w.wallet_id = "test_wallet"
+
+ with patch("lnbits.wallets.blink.bolt11_lib.decode") as mock_decode:
+ mock_decode.return_value.payment_hash = "test_payment_hash"
+ result = await w.pay_invoice("lnbc1...", fee_limit_msat=1000)
+
+ # Should be pending (ok=None) with checking_id set, not failed
+ assert result.ok is None
+ assert result.checking_id == "test_payment_hash"
+ assert result.error_message is None
+
+
+class TestConcurrentRequestCoalescing:
+ @pytest.mark.anyio
+ async def test_coalesces_concurrent_calls(self):
+ wallet = cast(BlinkWallet, funding_source)
+ wallet._status_locks = {}
+
+ fetch_count = 0
+
+ async def slow_fetch(checking_id):
+ nonlocal fetch_count
+ fetch_count += 1
+ await asyncio.sleep(0.05)
+ from lnbits.wallets.base import PaymentStatus
+
+ return PaymentStatus(paid=True)
+
+ wallet._fetch_payment_status = slow_fetch
+ wallet._cache_payment_status = BlinkWallet._cache_payment_status.__get__(wallet)
+ wallet._get_cached_payment_status = (
+ BlinkWallet._get_cached_payment_status.__get__(wallet)
+ )
+ wallet.get_payment_status = BlinkWallet.get_payment_status.__get__(wallet)
+
+ # Clear cache for the test hash
+ wallet.payment_status_cache.pop("concurrent_test", None)
+
+ # Fire 5 concurrent calls
+ tasks = [wallet.get_payment_status("concurrent_test") for _ in range(5)]
+ results = await asyncio.gather(*tasks)
+
+ assert all(r.paid is True for r in results)
+ assert fetch_count == 1
+
+
# Reproducible bolt11 invoices (fixed timestamp, long expiry) used to test the
# fee probing logic in pay_invoice without hitting the live Blink API.
# amount invoice: 1000 sat (1_000_000 msat)
@@ -299,3 +512,4 @@ async def test_pay_invoice_zero_amount_skips_probe_and_sends():
assert calls["probe"] == 0
assert calls["send"] == 1
assert response.ok is True
+
Why this scored 27/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.