fix(nwc): prevent false payment failures on NWC provider sync delay (#4066)
What changed, and why it matters
This commit fixes a bug in LNbits' NWC (Nostr Wallet Connect) wallet integration where payments could be incorrectly marked as failed due to delays in the NWC provider updating its records. The fix makes the wallet wait longer and use cached proof of payment before declaring a payment failed. It also adds better handling for missing fee information and lost payment responses. The bug could have caused users' successful payments to be reported as failed, potentially leading to duplicate payments or accounting errors, but it does not appear to allow an external attacker to steal funds directly.
Review and merge if not already deployed. Monitor for any continued reports of false payment failures with NWC providers. Consider whether the pending-state timeout behavior needs explicit upper bounds to avoid payments remaining in limbo indefinitely.
Security signals we found
Incorrect payment failure state could lead to duplicate payment attempts or inconsistent accounting
Race condition / synchronization delay between wallet action and provider state indexing
Missing fee data could cause premature finalization of payment status
Lost pay_invoice responses previously could leave payments without checking_id, now preserved
NOT_FOUND errors from provider were previously treated as final failure, now treated as pending
Evidence from the diff
The patch modifies lnbits/wallets/nwc.py to address payment status ambiguity caused by NWC provider synchronization delays. Key changes: (1) pay_invoice now caches successful pay_invoice responses immediately and returns a pending PaymentResponse when the preimage is missing or lookup fails, rather than assuming failure. (2) get_payment_status now treats NOT_FOUND and lookup errors as pending rather than failed, and falls back to cached settlement data. (3) A new _payment_data_needs_fees helper returns an indeterminate PaymentStatus when an outgoing payment is settled but fees are missing, preventing the core from finalizing with fee=0. (4) _cache_payment_data prevents delayed lookups from overwriting cached proof of settlement. (5) Tests are added covering delayed fee reconciliation, lost responses, explicit failures, and incoming payment handling. The commit title and message describe this as preventing ‘false payment failures on NWC provider sync delay.’
Changed components
lnbits/wallets/nwc.pytests/unit/test_wallet_payment_ambiguity.pytests/wallets/fixtures/json/fixtures_nwc.jsontests/wallets/test_nwc_wallets.pyInspect captured patch +280 / −46
diff --git a/lnbits/wallets/nwc.py b/lnbits/wallets/nwc.py
index 928ea65..a875f39 100644
--- a/lnbits/wallets/nwc.py
+++ b/lnbits/wallets/nwc.py
@@ -10,6 +10,7 @@ from collections.abc import AsyncGenerator, Awaitable, Callable
from typing import Any, cast
from urllib.parse import parse_qs, unquote, urlparse
+from bolt11 import Bolt11Exception
from bolt11 import decode as bolt11_decode
from coincurve import PrivateKey, PublicKey
from Cryptodome.Cipher import ChaCha20
@@ -85,6 +86,7 @@ class NWCWallet(Wallet):
nwc_data["relay"],
notification_handler=self._handle_notification,
)
+ self.pending_invoices: list[str] = []
self.pending_invoice_details: dict[str, dict[str, Any]] = {}
self.payment_status_cache: dict[str, dict[str, Any]] = {}
self.payment_status_cache_pending_ttl = 30
@@ -243,7 +245,6 @@ class NWCWallet(Wallet):
"until": int(now),
"limit": limit,
"offset": offset,
- "type": "incoming",
"unpaid": unpaid,
},
)
@@ -405,7 +406,7 @@ class NWCWallet(Wallet):
await self._reconcile_pending_invoices(now)
await self._run_fallback_lookups(now)
- self._prune_payment_status_cache(self._cache_ids())
+ self._prune_payment_status_cache()
def _payment_data_is_settled(self, payment_data: dict[str, Any]) -> bool:
state = payment_data.get("state")
@@ -430,12 +431,26 @@ class NWCWallet(Wallet):
def _payment_data_to_status(self, payment_data: dict[str, Any]) -> PaymentStatus:
fee_msat = payment_data.get("fees_paid", None)
preimage = payment_data.get("preimage", None)
+ if self._payment_data_needs_fees(payment_data):
+ # The core finalizes missing fees as zero and stops checking success.
+ return PaymentStatus(None, fee_msat=None, preimage=preimage)
if self._payment_data_is_settled(payment_data):
return PaymentStatus(True, fee_msat=fee_msat, preimage=preimage)
if self._payment_data_is_failed(payment_data):
return PaymentStatus(False, fee_msat=fee_msat, preimage=preimage)
return PaymentStatus(None, fee_msat=fee_msat, preimage=preimage)
+ def _payment_data_needs_fees(self, payment_data: dict[str, Any]) -> bool:
+ return (
+ payment_data.get("type") == "outgoing"
+ and self._payment_data_is_settled(payment_data)
+ and payment_data.get("fees_paid") is None
+ and (
+ self.conn.supports_method("lookup_invoice")
+ or self.conn.supports_method("list_transactions")
+ )
+ )
+
def _cache_payment_data(
self,
checking_id: str,
@@ -443,6 +458,24 @@ class NWCWallet(Wallet):
cached_at: float | None = None,
) -> None:
cached_at = cached_at or time.time()
+ cached = self._get_cached_payment_data(checking_id)
+ if (
+ cached
+ and cached.get("type") == "outgoing"
+ and self._payment_data_is_settled(cached)
+ ):
+ # Delayed lookups must not overwrite proof of settlement. Enrich it
+ # with fees and other details once the provider catches up.
+ if not self._payment_data_is_settled(payment_data):
+ return
+ payment_data = {
+ **cached,
+ **{
+ key: value
+ for key, value in payment_data.items()
+ if value is not None
+ },
+ }
ttl = (
self.payment_status_cache_terminal_ttl
if self._payment_data_is_settled(payment_data)
@@ -580,42 +613,43 @@ class NWCWallet(Wallet):
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
try:
- resp = await self.conn.call("pay_invoice", {"invoice": bolt11})
- preimage = resp.get("preimage", None)
invoice_data = bolt11_decode(bolt11)
payment_hash = invoice_data.payment_hash
- # pay_invoice doesn't return payment data, so we need
- # to call lookup_invoice too (if supported)
- await self.conn.get_info()
+ except Bolt11Exception as exc:
+ logger.error("Error decoding invoice: " + str(exc))
+ return PaymentResponse(
+ ok=False,
+ checking_id=None,
+ error_message="Invalid invoice: " + str(exc),
+ )
+ try:
+ resp = await self.conn.call("pay_invoice", {"invoice": bolt11})
+ preimage = resp.get("preimage", None)
+ if not preimage:
+ return PaymentResponse(checking_id=payment_hash)
- if not self.conn.supports_method("lookup_invoice"):
- # if not supported, we assume it succeeded
- return PaymentResponse(
- ok=True, checking_id=payment_hash, preimage=preimage, fee_msat=0
- )
+ # Cache the successful pay_invoice response so status checks
+ # can use it if lookup_invoice is not yet consistent.
+ self._cache_payment_data(
+ payment_hash,
+ {
+ "payment_hash": payment_hash,
+ "preimage": preimage,
+ "settled_at": int(time.time()),
+ "state": "settled",
+ "amount": invoice_data.amount_msat,
+ "fees_paid": resp.get("fees_paid", None),
+ "type": "outgoing",
+ },
+ )
- try:
- payment_data = await self.conn.call(
- "lookup_invoice", {"invoice": bolt11}
- )
- settled = payment_data.get("settled_at", None) and payment_data.get(
- "preimage", None
- )
- if not settled:
- return PaymentResponse(checking_id=payment_hash)
- else:
- fee_msat = payment_data.get("fees_paid", None)
- return PaymentResponse(
- ok=True,
- checking_id=payment_hash,
- fee_msat=fee_msat,
- preimage=preimage,
- )
- except Exception:
- # Workaround: some nwc service providers might not store the invoice
- # right away, so this call may raise an exception.
- # We will assume the payment is pending anyway
- return PaymentResponse(checking_id=payment_hash)
+ status = await self.get_payment_status(payment_hash)
+ return PaymentResponse(
+ ok=status.paid,
+ checking_id=payment_hash,
+ fee_msat=(status.fee_msat or 0) if status.success else None,
+ preimage=status.preimage,
+ )
except NWCError as e:
logger.error("Error paying invoice: " + str(e))
failure_codes = [
@@ -630,13 +664,15 @@ class NWCWallet(Wallet):
failed = e.code in failure_codes
return PaymentResponse(
ok=None if not failed else False,
+ checking_id=payment_hash,
error_message=e.message if failed else None,
)
except Exception as e:
msg = "Error paying invoice: " + str(e)
logger.error(msg)
- # assume pending
- return PaymentResponse(error_message=msg)
+ # assume pending so the core keeps the payment record
+ # and can settle it later via get_payment_status
+ return PaymentResponse(checking_id=payment_hash)
async def _get_status_via_transactions(
self, checking_id: str, unpaid_filters: list[bool]
@@ -644,7 +680,7 @@ class NWCWallet(Wallet):
keep_ids = self._cache_ids(checking_id)
self._prune_payment_status_cache()
payment_data = self._get_cached_payment_data(checking_id)
- if payment_data:
+ if payment_data and not self._payment_data_needs_fees(payment_data):
return self._payment_data_to_status(payment_data)
if self.conn.supports_method("list_transactions"):
@@ -664,7 +700,7 @@ class NWCWallet(Wallet):
unpaid=unpaid,
)
payment_data = self._get_cached_payment_data(checking_id)
- if payment_data:
+ if payment_data and not self._payment_data_needs_fees(payment_data):
return self._payment_data_to_status(payment_data)
if self.conn.supports_method("lookup_invoice"):
@@ -672,6 +708,7 @@ class NWCWallet(Wallet):
"lookup_invoice", {"payment_hash": checking_id}
)
self._cache_payment_data(checking_id, payment_data)
+ payment_data = self._get_cached_payment_data(checking_id) or payment_data
return self._payment_data_to_status(payment_data)
return None
@@ -698,14 +735,14 @@ class NWCWallet(Wallet):
return status or PaymentStatus(None, fee_msat=None, preimage=None)
except NWCError as e:
logger.error("Error getting payment status: " + str(e))
- failed = e.code == "NOT_FOUND"
- return PaymentStatus(
- None if not failed else False, fee_msat=None, preimage=None
- )
except Exception as e:
logger.error("Error getting payment status: " + str(e))
- # assume pending (eg. exception due to network error)
- return PaymentStatus(None, fee_msat=None, preimage=None)
+ # NOT_FOUND can mean the payment has not been indexed yet, including
+ # when the pay_invoice response was lost. Only explicit failure is final.
+ cached = self._get_cached_payment_data(checking_id)
+ if cached and self._payment_data_is_settled(cached):
+ return self._payment_data_to_status(cached)
+ return PaymentStatus(None, fee_msat=None, preimage=None)
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
while not self._is_shutting_down():
diff --git a/tests/unit/test_wallet_payment_ambiguity.py b/tests/unit/test_wallet_payment_ambiguity.py
index d4c4bc5..3c8724a 100644
--- a/tests/unit/test_wallet_payment_ambiguity.py
+++ b/tests/unit/test_wallet_payment_ambiguity.py
@@ -449,6 +449,10 @@ async def test_nwc_only_explicit_payment_failure_is_failed(
cast(Any, wallet).conn = SimpleNamespace(
call=mocker.AsyncMock(side_effect=NWCError(code, "error"))
)
+ mocker.patch(
+ "lnbits.wallets.nwc.bolt11_decode",
+ return_value=SimpleNamespace(payment_hash="payment-hash"),
+ )
response = await wallet.pay_invoice("bolt11", 1_000)
diff --git a/tests/wallets/fixtures/json/fixtures_nwc.json b/tests/wallets/fixtures/json/fixtures_nwc.json
index ad7659e..059bc01 100644
--- a/tests/wallets/fixtures/json/fixtures_nwc.json
+++ b/tests/wallets/fixtures/json/fixtures_nwc.json
@@ -230,7 +230,7 @@
"request_body": {
"method": "lookup_invoice",
"params": {
- "invoice": "lnbc210n1pjlgal5sp5xr3uwlfm7ltumdjyukhys0z2rw6grgm8me9k4w9vn05zt9svzzjspp5ud2jdfpaqn5c2k2vphatsjypfafyk8rcvkvwexnrhmwm94ex4jtqdqu24hxjapq23jhxapqf9h8vmmfvdjscqpjrzjqta942048v7qxh5x7pxwplhmtwfl0f25cq23jh87rhx7lgrwwvv86r90guqqnwgqqqqqqqqqqqqqqpsqyg9qxpqysgqylngsyg960lltngzy90e8n22v4j2hvjs4l4ttuy79qqefjv8q87q9ft7uhwdjakvnsgk44qyhalv6ust54x98whl3q635hkwgsyw8xgqjl7jwu"
+ "payment_hash": "e35526a43d04e985594c0dfab848814f524b1c786598ec9a63beddb2d726ac96"
}
},
"response_type": "json",
diff --git a/tests/wallets/test_nwc_wallets.py b/tests/wallets/test_nwc_wallets.py
index 35fc36b..ad954d5 100644
--- a/tests/wallets/test_nwc_wallets.py
+++ b/tests/wallets/test_nwc_wallets.py
@@ -3,6 +3,7 @@ import base64
import hashlib
import json
import time
+from types import SimpleNamespace
from typing import cast
import pytest
@@ -13,7 +14,7 @@ from Cryptodome.Util.Padding import pad, unpad
from websockets import ServerConnection
from websockets import serve as ws_serve
-from lnbits.wallets.nwc import NWCConnection, NWCWallet
+from lnbits.wallets.nwc import NWCConnection, NWCError, NWCWallet
from tests.wallets.helpers import (
WalletTest,
build_test_id,
@@ -303,6 +304,198 @@ async def test_nwc_spreads_fallback_lookups_with_cooldown(mocker):
sleep_mock.assert_awaited_once_with(1.0)
+@pytest.fixture
+def nwc_payment_wallet(mocker):
+ conn = mocker.Mock(spec=NWCConnection)
+ conn.get_info = mocker.AsyncMock(return_value={})
+ conn.call = mocker.AsyncMock()
+ conn.supports_method.side_effect = lambda method: method == "lookup_invoice"
+ mocker.patch("lnbits.wallets.nwc.NWCConnection", return_value=conn)
+ mocker.patch(
+ "lnbits.wallets.nwc.parse_nwc",
+ return_value={"pubkey": "pubkey", "secret": "secret", "relay": "relay"},
+ )
+ mocker.patch(
+ "lnbits.wallets.nwc.bolt11_decode",
+ return_value=SimpleNamespace(payment_hash="payment-hash", amount_msat=1000),
+ )
+ return NWCWallet()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("fee_msat", [0, 123])
+@pytest.mark.parametrize(
+ "delayed_lookup",
+ [
+ NWCError("NOT_FOUND", "Not indexed yet"),
+ {"type": "outgoing", "state": "pending", "fees_paid": 0},
+ {"type": "outgoing", "state": "settled", "preimage": "01" * 32},
+ ],
+)
+async def test_nwc_waits_for_payment_fees(nwc_payment_wallet, delayed_lookup, fee_msat):
+ wallet = nwc_payment_wallet
+ preimage = "01" * 32
+ wallet.conn.call.side_effect = [
+ {"preimage": preimage},
+ delayed_lookup,
+ delayed_lookup,
+ {"type": "outgoing", "state": "settled", "fees_paid": fee_msat},
+ ]
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+ assert response.ok is None
+ assert response.checking_id == "payment-hash"
+
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is None
+ assert status.preimage == preimage
+
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is True
+ assert status.fee_msat == fee_msat
+ assert status.preimage == preimage
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("preimage", [None, ""])
+async def test_nwc_missing_preimage_stays_pending(nwc_payment_wallet, preimage):
+ wallet = nwc_payment_wallet
+ wallet.conn.call.side_effect = [
+ {"preimage": preimage},
+ {"type": "outgoing", "state": "pending"},
+ ]
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+
+ assert response.ok is None
+ assert response.checking_id == "payment-hash"
+ assert wallet._get_cached_payment_data("payment-hash") is None
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is None
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "error",
+ [
+ TimeoutError("Payment response lost"),
+ NWCError("INTERNAL", "Payment response lost"),
+ NWCError("OTHER", "Payment response lost"),
+ ],
+)
+async def test_nwc_reconciles_payment_after_lost_response(nwc_payment_wallet, error):
+ wallet = nwc_payment_wallet
+ wallet.conn.call.side_effect = [
+ error,
+ NWCError("NOT_FOUND", "Not indexed yet"),
+ {
+ "type": "outgoing",
+ "state": "settled",
+ "fees_paid": 123,
+ "preimage": "01" * 32,
+ },
+ ]
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+ assert response.ok is None
+ assert response.checking_id == "payment-hash"
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is None
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is True
+ assert status.fee_msat == 123
+
+
+@pytest.mark.anyio
+async def test_nwc_reconciles_explicit_payment_failure(nwc_payment_wallet):
+ wallet = nwc_payment_wallet
+ wallet.conn.call.side_effect = [
+ TimeoutError("Payment response lost"),
+ {"type": "outgoing", "state": "failed"},
+ ]
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+ assert response.ok is None
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is False
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("fee_msat", [0, 123])
+async def test_nwc_uses_payment_response_with_fees(nwc_payment_wallet, fee_msat):
+ wallet = nwc_payment_wallet
+ preimage = "01" * 32
+ wallet.conn.call.side_effect = [
+ {"preimage": preimage, "fees_paid": fee_msat},
+ NWCError("NOT_FOUND", "Not indexed yet"),
+ ]
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+ status = await wallet.get_payment_status("payment-hash")
+
+ assert response.ok is True
+ assert response.fee_msat == fee_msat
+ assert status.paid is True
+ assert status.fee_msat == fee_msat
+ assert status.preimage == preimage
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("preimage", [None, "01" * 32])
+async def test_nwc_pay_only_provider_requires_preimage(nwc_payment_wallet, preimage):
+ wallet = nwc_payment_wallet
+ wallet.conn.supports_method.side_effect = lambda method: False
+ wallet.conn.call.return_value = {"preimage": preimage}
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+
+ assert response.ok is (True if preimage else None)
+ assert response.checking_id == "payment-hash"
+ if preimage:
+ assert response.fee_msat == 0
+
+
+@pytest.mark.anyio
+async def test_nwc_reconciles_fees_via_transactions(nwc_payment_wallet):
+ wallet = nwc_payment_wallet
+ wallet.conn.supports_method.side_effect = (
+ lambda method: method == "list_transactions"
+ )
+ wallet.transactions_refresh_interval = 0
+ wallet.conn.call.side_effect = [
+ {"preimage": "01" * 32},
+ {"transactions": []},
+ {
+ "transactions": [
+ {
+ "payment_hash": "payment-hash",
+ "type": "outgoing",
+ "state": "settled",
+ "fees_paid": 123,
+ }
+ ]
+ },
+ ]
+
+ response = await wallet.pay_invoice("bolt11", 1000)
+ assert response.ok is None
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is True
+ assert status.fee_msat == 123
+ assert status.preimage == "01" * 32
+ assert wallet.conn.call.call_args.args[0] == "list_transactions"
+
+
+@pytest.mark.anyio
+async def test_nwc_incoming_settlement_does_not_wait_for_fees(nwc_payment_wallet):
+ wallet = nwc_payment_wallet
+ wallet.conn.call.return_value = {"type": "incoming", "state": "settled"}
+
+ status = await wallet.get_invoice_status("payment-hash")
+
+ assert status.paid is True
+
+
@pytest.mark.anyio
@pytest.mark.parametrize(
"test_data",
Why this scored 57/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.