fix: preserve pending CLN and NWC payment status (#4361)
What changed, and why it matters
This commit fixes a bug where LNbits would incorrectly mark certain Lightning payments as failed when they might still be pending. For Core Lightning (CLN) backends, error code 203 ('permanent failure') can sometimes occur even though parts of a multi-part payment are still in flight, so the code now double-checks the actual payment status before declaring failure. For Nostr Wallet Connect (NWC) backends, outgoing payments were wrongly being treated as failed just because the invoice expired, even though the payment itself may still succeed. The fix prevents users from being incorrectly refunded or shown a failed status for payments that could still complete.
Review payment reconciliation logic in other wallet backends for similar premature failure classification, and ensure that refunds or status updates are only triggered after definitive terminal states are confirmed.
Security signals we found
Incorrect payment status classification could lead to double-spend or erroneous refund
Error code 203 treated as unconditionally terminal despite upstream xpay behavior leaving parts pending
Outgoing NWC payments marked failed on invoice expiry, conflating invoice state with payment outcome
Fix adds secondary status verification before marking CLN payment failed
Test cases added/updated to enforce ambiguous-error handling
Evidence from the diff
The patch changes payment failure classification in three CLN wallet backends (corelightning.py, clnrest.py, corelightningrest.py) and one NWC backend (nwc.py). Error code 203 is removed from the unconditional failure list; instead, corelightning.py now queries get_payment_status() and only marks the payment failed if that status reports failed. The two REST-based CLN wallets inherit this behavior indirectly through shared error classification. In nwc.py, _payment_data_is_failed() no longer treats ‘expired’ state as a failure for outgoing payments, since invoice expiry is independent of whether an outgoing payment attempt has completed. Tests are updated to assert that code 203 is non-definitive and that NWC outgoing expiry does not imply failure.
Changed components
lnbits/wallets/corelightning.pylnbits/wallets/clnrest.pylnbits/wallets/corelightningrest.pylnbits/wallets/nwc.pyInspect captured patch +136 / −20
### lnbits/wallets/clnrest.py
@@ -102,14 +102,14 @@ def __init__(self):
# -32602: Invalid bolt11: Prefix bc is not for regtest
# -1: Catchall nonspecific error.
## 201: Already paid
- # 203: Permanent failure at destination.
+ # 203 can leave xpay parts pending; resolve it through payment status.
# 205: Unable to find a route.
# 206: Route too expensive.
# 207: Invoice expired.
# 210: Payment timed out without a payment in progress.
# 401: Unauthorized. Probably a rune issue
- self.pay_failure_error_codes = [-32602, 203, 205, 206, 207, 210, 401]
+ self.pay_failure_error_codes = [-32602, 205, 206, 207, 210, 401]
self.client = self._create_client()
self.last_pay_index = settings.clnrest_last_pay_index
self.statuses = {
### lnbits/wallets/corelightning.py
@@ -73,12 +73,12 @@ def __init__(self):
# -32602: Invalid bolt11: Prefix bc is not for regtest
# -1: Catchall nonspecific error.
# 201: Already paid
- # 203: Permanent failure at destination.
+ # 203 can leave xpay parts pending; resolve it through payment status.
# 205: Unable to find a route.
# 206: Route too expensive.
# 207: Invoice expired.
# 210: Payment timed out without a payment in progress.
- self.pay_failure_error_codes = [-32602, 201, 203, 205, 206, 207, 210]
+ self.pay_failure_error_codes = [-32602, 201, 205, 206, 207, 210]
# check last payindex so we can listen from that point on
self.last_pay_index = 0
@@ -200,8 +200,13 @@ async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse
logger.warning(exc)
try:
error_code = exc.error.get("code") # type: ignore
- if error_code in self.pay_failure_error_codes or (
- _all_payment_attempts_failed(exc.error)
+ if (
+ error_code in self.pay_failure_error_codes
+ or _all_payment_attempts_failed(exc.error)
+ or (
+ error_code == 203
+ and (await self.get_payment_status(invoice.payment_hash)).failed
+ )
):
error_message = exc.error.get("message", error_code) # type: ignore
return PaymentResponse(
### lnbits/wallets/corelightningrest.py
@@ -55,12 +55,12 @@ def __init__(self):
# -32602: Invalid bolt11: Prefix bc is not for regtest
# -1: Catchall nonspecific error.
# 201: Already paid
- # 203: Permanent failure at destination.
+ # 203 can leave xpay parts pending; resolve it through payment status.
# 205: Unable to find a route.
# 206: Route too expensive.
# 207: Invoice expired.
# 210: Payment timed out without a payment in progress.
- self.pay_failure_error_codes = [-32602, 201, 203, 205, 206, 207, 210]
+ self.pay_failure_error_codes = [-32602, 201, 205, 206, 207, 210]
self.cert = settings.corelightning_rest_cert or False
self.client = httpx.AsyncClient(verify=self.cert, headers=headers)
### lnbits/wallets/nwc.py
@@ -418,6 +418,9 @@ def _payment_data_is_settled(self, payment_data: dict[str, Any]) -> bool:
def _payment_data_is_failed(self, payment_data: dict[str, Any]) -> bool:
state = payment_data.get("state")
+ # Invoice expiry does not determine the outcome of an outgoing payment.
+ if payment_data.get("type") != "incoming":
+ return state == "failed"
if state in {"expired", "failed"}:
return True
created_at = int(payment_data.get("created_at", time.time()))
### tests/unit/test_bolt12_clnrest_errors.py
@@ -42,7 +42,7 @@ def handler(request):
"body,definitive",
[
({"error": {"code": -32602, "message": "Invalid parameters"}}, True),
- ({"error": {"code": 203, "message": "Permanent failure"}}, True),
+ ({"error": {"code": 203, "message": "Permanent failure"}}, False),
({"error": {"code": 205, "message": "No route"}}, True),
({"error": {"code": 206, "message": "Route too expensive"}}, True),
({"error": {"code": 207, "message": "Invoice expired"}}, True),
@@ -78,7 +78,9 @@ async def test_bolt12_clnrest_http_failure_classification(
@pytest.mark.anyio
@pytest.mark.parametrize("stage", ["fetchinvoice", "payment"])
-@pytest.mark.parametrize("error", ["http", "invalid_json", "timeout", "no_route"])
+@pytest.mark.parametrize(
+ "error", ["http", "invalid_json", "timeout", "destination", "no_route"]
+)
async def test_bolt12_clnrest_ambiguous_errors_do_not_refund(
app, clnrest_offer_backend, monkeypatch, stage, error
):
@@ -92,6 +94,7 @@ async def test_bolt12_clnrest_ambiguous_errors_do_not_refund(
"http": httpx.Response(500, json={"error": {"message": "Response lost"}}),
"invalid_json": httpx.Response(500, text="Invalid response"),
"timeout": httpx.ReadTimeout("Response lost"),
+ "destination": httpx.Response(500, json={"error": {"code": 203}}),
"no_route": httpx.Response(500, json={"error": {"code": 205}}),
}[error]
monkeypatch.setattr(
### tests/unit/test_wallet_payment_ambiguity.py
@@ -10,11 +10,13 @@
import lnbits.wallets.breez as breez_wallet_module
import lnbits.wallets.breez_liquid as breez_liquid_wallet_module
from lnbits.wallets.alby import AlbyWallet
-from lnbits.wallets.base import PaymentPendingStatus
+from lnbits.wallets.base import PaymentPendingStatus, PaymentStatus
from lnbits.wallets.blink import BlinkWallet
from lnbits.wallets.boltz import BoltzWallet
from lnbits.wallets.boltz_grpc_files import boltzrpc_pb2
+from lnbits.wallets.clnrest import CLNRestWallet
from lnbits.wallets.corelightning import CoreLightningWallet
+from lnbits.wallets.corelightningrest import CoreLightningRestWallet
from lnbits.wallets.eclair import EclairWallet
from lnbits.wallets.lnd_grpc_files.lightning_pb2 import Payment as LndPayment
from lnbits.wallets.lndgrpc import LndWallet
@@ -258,14 +260,15 @@ async def test_lndgrpc_in_flight_payment_is_pending(mocker: MockerFixture, setti
@pytest.mark.anyio
@pytest.mark.parametrize(
- ("error", "expected"),
+ ("error", "status_after_error", "expected"),
[
(
{
"code": 0,
"message": "destination is not reachable",
"attempts": [{"status": "failed"}],
},
+ None,
False,
),
(
@@ -275,22 +278,31 @@ async def test_lndgrpc_in_flight_payment_is_pending(mocker: MockerFixture, setti
"attempts": [{"status": "pending"}],
},
None,
+ None,
),
- ({"code": 0, "message": "unclassified RPC error"}, None),
- ({"code": 205, "message": "unable to find a route"}, False),
+ ({"code": 0, "message": "unclassified RPC error"}, None, None),
+ ({"code": 203, "message": "permanent failure at destination"}, None, None),
+ ({"code": 203, "message": "permanent failure at destination"}, False, False),
+ ({"code": 205, "message": "unable to find a route"}, None, False),
],
)
async def test_corelightning_only_terminal_rpc_errors_are_failed(
mocker: MockerFixture,
+ settings,
error: dict,
+ status_after_error: bool | None,
expected: bool | None,
):
- wallet = object.__new__(CoreLightningWallet)
- wallet.pay = "pay"
- wallet.pay_failure_error_codes = [-32602, 201, 203, 205, 206, 207, 210]
- cast(Any, wallet).ln = SimpleNamespace(
- call=mocker.Mock(side_effect=RpcError("pay", {}, cast(Any, error)))
+ settings.corelightning_rpc = "lightning-rpc"
+ mocker.patch(
+ "lnbits.wallets.corelightning.LightningRpc",
+ return_value=SimpleNamespace(
+ help=mocker.Mock(return_value={"help": [{"command": "invoice"}]}),
+ listinvoices=mocker.Mock(return_value={"invoices": []}),
+ call=mocker.Mock(side_effect=RpcError("pay", {}, cast(Any, error))),
+ ),
)
+ wallet = CoreLightningWallet()
mocker.patch(
"lnbits.wallets.corelightning.bolt11_decode",
return_value=SimpleNamespace(
@@ -300,14 +312,53 @@ async def test_corelightning_only_terminal_rpc_errors_are_failed(
),
)
mocker.patch.object(
- wallet, "get_payment_status", return_value=PaymentPendingStatus()
+ wallet,
+ "get_payment_status",
+ side_effect=[PaymentPendingStatus(), PaymentStatus(paid=status_after_error)],
)
response = await wallet.pay_invoice("bolt11", 1_000)
assert response.ok is expected
+@pytest.mark.anyio
+@pytest.mark.parametrize("wallet_class", [CLNRestWallet, CoreLightningRestWallet])
+@pytest.mark.parametrize(("code", "expected"), [(203, None), (205, False)])
+async def test_cln_rest_payment_error_classification(
+ mocker: MockerFixture, settings, wallet_class, code, expected
+):
+ settings.clnrest_url = "https://wallet.test"
+ settings.clnrest_readonly_rune = "read"
+ settings.clnrest_pay_rune = "pay"
+ settings.clnrest_renepay_rune = None
+ settings.corelightning_rest_url = "https://wallet.test"
+ settings.corelightning_rest_macaroon = "test-macaroon"
+ client = SimpleNamespace(
+ post=mocker.AsyncMock(
+ return_value=_response(
+ 500, json={"error": {"code": code, "message": "payment error"}}
+ )
+ )
+ )
+ mocker.patch.object(CLNRestWallet, "_create_client", return_value=client)
+ mocker.patch(
+ "lnbits.wallets.corelightningrest.httpx.AsyncClient", return_value=client
+ )
+ mocker.patch(
+ "lnbits.wallets.corelightningrest.load_macaroon", return_value="test-macaroon"
+ )
+ for module in ("clnrest", "corelightningrest"):
+ mocker.patch(
+ f"lnbits.wallets.{module}.decode",
+ return_value=SimpleNamespace(amount_msat=1_000, description=""),
+ )
+
+ response = await wallet_class().pay_invoice("bolt11", 1_000)
+
+ assert response.ok is expected
+
+
@pytest.mark.anyio
@pytest.mark.parametrize(
("status_code", "expected"),
### tests/wallets/test_nwc_wallets.py
@@ -322,6 +322,60 @@ def nwc_payment_wallet(mocker):
return NWCWallet()
+@pytest.mark.anyio
+@pytest.mark.parametrize("transaction_type", ["outgoing", None])
+@pytest.mark.parametrize(
+ "payment_data,expected",
+ [
+ ({"state": "expired"}, None),
+ ({"state": "pending", "expires_at": 1}, None),
+ ({"state": "pending", "created_at": 1}, None),
+ ({"state": "pending", "expires_at": 4_000_000_000}, None),
+ ({"state": "failed", "expires_at": 1}, False),
+ ({"state": "settled", "expires_at": 1, "fees_paid": 0}, True),
+ ],
+)
+async def test_nwc_outgoing_status_ignores_invoice_expiry(
+ nwc_payment_wallet, mocker, transaction_type, payment_data, expected
+):
+ wallet = nwc_payment_wallet
+ clock = mocker.patch("lnbits.wallets.nwc.time.time", return_value=1_000_000)
+ data = dict(payment_data)
+ if transaction_type:
+ data["type"] = transaction_type
+ wallet.conn.call.return_value = data
+
+ status = await wallet.get_payment_status("payment-hash")
+
+ assert status.paid is expected
+ if expected is None:
+ # Pending results should be refreshed using the shorter cache lifetime.
+ clock.return_value += wallet.payment_status_cache_pending_ttl + 1
+ wallet.conn.call.return_value = {
+ "type": "outgoing",
+ "state": "settled",
+ "preimage": "01" * 32,
+ "fees_paid": 123,
+ }
+ status = await wallet.get_payment_status("payment-hash")
+ assert status.paid is True
+ assert status.fee_msat == 123
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "payment_data",
+ [{"state": "expired"}, {"state": "pending", "expires_at": 1}],
+)
+async def test_nwc_incoming_invoice_expiry(nwc_payment_wallet, payment_data):
+ wallet = nwc_payment_wallet
+ wallet.conn.call.return_value = {"type": "incoming", **payment_data}
+
+ status = await wallet.get_invoice_status("payment-hash")
+
+ assert status.paid is False
+
+
@pytest.mark.anyio
@pytest.mark.parametrize("fee_msat", [0, 123])
@pytest.mark.parametrize(Why this scored 62/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.