fix: probe Blink fee before paying to avoid max-fee reserve (#4076)
What changed, and why it matters
This change updates LNbits so that when using the Blink Bitcoin Lightning wallet, it first asks Blink's backend to estimate the routing fee before sending a payment. Previously, Blink would reserve the maximum possible fee and later refund any overpayment. The new behavior helps avoid tying up extra funds in fee reserves. It also adds a safety check that cancels the payment if the estimated fee exceeds the user's fee limit, and provides a fallback setting to send anyway when fee probing is not possible (for example, with certain invoice types).
Review and merge if the fee-limit logic and fallback behavior match project expectations. Operators using Blink should consider whether the default send-without-probe fallback is acceptable for their risk model, and may disable it if they require strict fee estimation before every payment.
Security signals we found
Adds pre-payment fee validation to prevent spending more in routing fees than configured
Introduces a configurable fallback that can fail closed (blink_send_without_probe=false) when fee estimation is unavailable
Prevents unnecessary max-fee reserve lockups with Blink, improving wallet liquidity
Adds test coverage for fee-exceeds-limit, probe failure, and zero-amount invoice paths
Evidence from the diff
The commit adds a fee-probe step to BlinkWallet.pay_invoice() using Blink’s lnInvoiceFeeProbe GraphQL mutation. For amount-carrying BOLT11 invoices, the wallet now probes the route fee before calling lnInvoicePaymentSend. If the probed fee in satoshis exceeds fee_limit_msat, the payment is rejected early. If probing fails or the invoice has no amount, behavior is controlled by a new setting blink_send_without_probe (default true). When true, payments proceed without a probe; when false, they fail. The change also exposes this setting in the admin UI and adds unit tests with mocked GraphQL responses.
Changed components
lnbits/wallets/blink.pylnbits/settings.pylnbits/static/js/components/admin/lnbits-admin-funding-sources.jstests/wallets/test_blink.pyInspect captured patch +248 / −3
diff --git a/lnbits/settings.py b/lnbits/settings.py
index 4b89cb5..9b68514 100644
--- a/lnbits/settings.py
+++ b/lnbits/settings.py
@@ -620,6 +620,10 @@ class BlinkFundingSource(LNbitsSettings):
blink_api_endpoint: str | None = Field(default="https://api.blink.sv/graphql")
blink_ws_endpoint: str | None = Field(default="wss://ws.blink.sv/graphql")
blink_token: str | None = Field(default=None)
+ # If probing fails or is unsupported by the destination (e.g. fedimints),
+ # send the payment anyway. Blink reserves its max fee and reconciles any
+ # excess separately. If disabled, payments that cannot be probed will fail.
+ blink_send_without_probe: bool = Field(default=True)
class ZBDFundingSource(LNbitsSettings):
diff --git a/lnbits/static/js/components/admin/lnbits-admin-funding-sources.js b/lnbits/static/js/components/admin/lnbits-admin-funding-sources.js
index 827c103..9a97f59 100644
--- a/lnbits/static/js/components/admin/lnbits-admin-funding-sources.js
+++ b/lnbits/static/js/components/admin/lnbits-admin-funding-sources.js
@@ -154,7 +154,12 @@ window.app.component('lnbits-admin-funding-sources', {
{
blink_api_endpoint: 'Endpoint',
blink_ws_endpoint: 'WebSocket',
- blink_token: 'Key'
+ blink_token: 'Key',
+ blink_send_without_probe: {
+ advanced: true,
+ label: 'Send payment if fee probe fails',
+ hint: 'If enabled (default), payments to destinations that cannot be probed (e.g. fedimints) are still sent. If disabled, such payments fail.'
+ }
}
],
[
diff --git a/lnbits/wallets/blink.py b/lnbits/wallets/blink.py
index b43e90f..b2f05e0 100644
--- a/lnbits/wallets/blink.py
+++ b/lnbits/wallets/blink.py
@@ -164,9 +164,82 @@ class BlinkWallet(Wallet):
ok=False, error_message=f"Unable to connect to {self.endpoint}."
)
+ async def _fee_probe(self, bolt11: str) -> tuple[int | None, str | None]:
+ """
+ Probe the route for the fee of an amount lightning invoice.
+
+ Probing caches the route on the Blink backend so that the subsequent
+ payment settles with the exact fee instead of Blink's max fee reserve.
+ Only invoices that carry an amount can be probed here, since the
+ pay_invoice interface does not provide a separate amount for
+ zero-amount invoices.
+
+ Returns a tuple of (fee_sat, error_message). On success the fee in
+ satoshis is returned; on failure an error message is returned.
+ """
+ probe_input = {
+ "paymentRequest": bolt11,
+ "walletId": self.wallet_id,
+ }
+ data = {"query": q.fee_probe_query, "variables": {"input": probe_input}}
+ response = await self._graphql_query(data)
+
+ errors = response.get("errors") or []
+ if len(errors) > 0:
+ return None, errors[0].get("message") or "Fee probe failed."
+
+ result = (response.get("data") or {}).get("lnInvoiceFeeProbe") or {}
+
+ errors = result.get("errors") or []
+ if len(errors) > 0:
+ return None, errors[0].get("message") or "Fee probe failed."
+
+ fee_sat = result.get("amount")
+ if fee_sat is None:
+ return None, "Server error: 'missing fee probe amount'"
+
+ return fee_sat, None
+
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
# https://dev.blink.sv/api/btc-ln-send
- # Future: add check fee estimate is < fee_limit_msat before paying invoice
+
+ invoice = bolt11_lib.decode(bolt11)
+
+ # Only amount invoices can be probed: lnInvoiceFeeProbe takes no amount,
+ # and zero-amount invoices have no amount to probe with (pay_invoice
+ # does not receive a separate amount). Zero-amount invoices skip the
+ # probe and fall back to the send-without-probe behaviour.
+ try:
+ if invoice.amount_msat:
+ fee_sat, probe_error = await self._fee_probe(bolt11)
+ if probe_error is not None:
+ if not settings.blink_send_without_probe:
+ logger.info(f"Fee probe failed for invoice {bolt11}")
+ return PaymentResponse(ok=False, error_message=probe_error)
+ logger.warning(
+ f"Fee probe failed ('{probe_error}'), "
+ "sending payment without probe."
+ )
+ elif fee_sat is not None and fee_sat * 1000 > fee_limit_msat:
+ error_message = (
+ f"fee of {fee_sat * 1000} msat exceeds "
+ f"limit of {fee_limit_msat} msat"
+ )
+ return PaymentResponse(ok=False, error_message=error_message)
+ elif not settings.blink_send_without_probe:
+ logger.info(f"Cannot probe zero-amount invoice {bolt11}")
+ return PaymentResponse(
+ ok=False,
+ error_message="Cannot probe fee for zero-amount invoice.",
+ )
+ except Exception as exc:
+ if not settings.blink_send_without_probe:
+ logger.info(f"Failed to probe fee for invoice {bolt11}")
+ logger.warning(exc)
+ return PaymentResponse(
+ ok=False, error_message=f"Unable to connect to {self.endpoint}."
+ )
+ logger.warning(f"Fee probe errored ('{exc}'), sending without probe.")
payment_variables = {
"input": {
@@ -189,7 +262,7 @@ class BlinkWallet(Wallet):
error_message=error_message,
)
- checking_id = bolt11_lib.decode(bolt11).payment_hash
+ checking_id = invoice.payment_hash
payment_status = await self.get_payment_status(checking_id)
fee_msat = payment_status.fee_msat
@@ -369,6 +442,7 @@ class BlinkGrafqlQueries(BaseModel):
balance_query: str
invoice_query: str
payment_query: str
+ fee_probe_query: str
status_query: str
wallet_query: str
tx_query: str
@@ -417,6 +491,16 @@ q = BlinkGrafqlQueries(
}
}
""",
+ fee_probe_query="""
+ mutation LnInvoiceFeeProbe($input: LnInvoiceFeeProbeInput!) {
+ lnInvoiceFeeProbe(input: $input) {
+ amount
+ errors {
+ message
+ }
+ }
+ }
+ """,
status_query="""
query InvoiceByPaymentHash($walletId: WalletId!, $paymentHash: PaymentHash!) {
me {
diff --git a/tests/wallets/test_blink.py b/tests/wallets/test_blink.py
index 8a6ae65..f9ba016 100644
--- a/tests/wallets/test_blink.py
+++ b/tests/wallets/test_blink.py
@@ -1,11 +1,13 @@
import os
from typing import cast
+from unittest.mock import AsyncMock
import pytest
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
settings.lnbits_backend_wallet_class = "BlinkWallet"
settings.blink_token = "mock"
@@ -147,3 +149,153 @@ async def test_get_payment_status(payhash):
logger.info(f"test_get_payment_status: payment_status: {payment_status.paid}")
else:
assert True, "BLINK_TOKEN is not set. Skipping test using mock api"
+
+
+# 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)
+AMOUNT_BOLT11 = (
+ "lnbc10u1pj48ugqpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqsp5"
+ "zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygsdq8w3jhxaqxq8zals8squ"
+ "qsakyemlpj9guae3a9havssjcjewgr24hedxkq6t978jk99srrxx9azy6k0cs66a757cfdc43"
+ "vkfhmlexyzdqtytzzteh2n4qngapgpesavte"
+)
+# zero-amount (amountless) invoice
+ZERO_BOLT11 = (
+ "lnbc1pj48ugqpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqsp5zyg"
+ "3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygsdq8w3jhxaqxq8zals8sq3c00"
+ "hc6end9u8pafqge29y690e2x0kztq0l9z4dfd2yg8au9xuwxz9a2hy2hn2jqzq2mpy43tx9td"
+ "wxcy6yuc9ghuqkzj3kruh4tpcgp7n84qu"
+)
+
+
+def _make_blink_wallet_with_mock(graphql_side_effect):
+ """Build a BlinkWallet with a mocked GraphQL layer for pay_invoice tests."""
+ settings.blink_api_endpoint = "https://api.blink.sv/graphql"
+ settings.blink_ws_endpoint = "wss://ws.blink.sv/graphql"
+ settings.blink_token = settings.blink_token or "mock"
+ wallet = BlinkWallet()
+ wallet._wallet_id = "mock_wallet_id"
+ wallet._graphql_query = graphql_side_effect # type: ignore[method-assign]
+ wallet.get_payment_status = AsyncMock( # type: ignore[method-assign]
+ return_value=PaymentStatus(paid=True, fee_msat=1000, preimage="preimage")
+ )
+ return wallet
+
+
+@pytest.mark.anyio
+async def test_pay_invoice_amount_invoice_probes_and_sends():
+ """Amount invoices are probed via lnInvoiceFeeProbe then sent."""
+ calls = {"probe": 0, "send": 0}
+
+ async def graphql(payload):
+ query = payload["query"]
+ if "lnInvoiceFeeProbe" in query:
+ calls["probe"] += 1
+ return {"data": {"lnInvoiceFeeProbe": {"amount": 1, "errors": []}}}
+ if "lnNoAmountInvoiceFeeProbe" in query:
+ raise AssertionError("must not probe amount invoice as no-amount")
+ if "lnInvoicePaymentSend" in query:
+ calls["send"] += 1
+ return {
+ "data": {"lnInvoicePaymentSend": {"status": "SUCCESS", "errors": []}}
+ }
+ return {"data": {}}
+
+ wallet = _make_blink_wallet_with_mock(graphql)
+ response = await wallet.pay_invoice(AMOUNT_BOLT11, fee_limit_msat=5000)
+
+ assert calls["probe"] == 1
+ assert calls["send"] == 1
+ assert response.ok is True
+ assert response.fee_msat == 1000
+
+
+@pytest.mark.anyio
+async def test_pay_invoice_rejects_when_probed_fee_exceeds_limit():
+ """A probed fee above the fee limit rejects the payment before sending."""
+ calls = {"send": 0}
+
+ async def graphql(payload):
+ query = payload["query"]
+ if "lnInvoiceFeeProbe" in query:
+ # 1 sat = 1000 msat, above the 500 msat limit below
+ return {"data": {"lnInvoiceFeeProbe": {"amount": 1, "errors": []}}}
+ if "lnInvoicePaymentSend" in query:
+ calls["send"] += 1
+ return {
+ "data": {"lnInvoicePaymentSend": {"status": "SUCCESS", "errors": []}}
+ }
+ return {"data": {}}
+
+ wallet = _make_blink_wallet_with_mock(graphql)
+ response = await wallet.pay_invoice(AMOUNT_BOLT11, fee_limit_msat=500)
+
+ assert calls["send"] == 0
+ assert response.ok is False
+ assert response.error_message is not None
+ assert "exceeds" in response.error_message
+
+
+@pytest.mark.parametrize(
+ ("probe_response", "expected_error"),
+ [
+ ({"errors": [{"message": "probe unavailable"}]}, "probe unavailable"),
+ (
+ {"data": {"lnInvoiceFeeProbe": {"errors": []}}},
+ "missing fee probe amount",
+ ),
+ ],
+)
+@pytest.mark.anyio
+async def test_pay_invoice_strict_probe_failure_rejects_without_sending(
+ probe_response, expected_error
+):
+ """Strict mode rejects malformed probe responses before sending."""
+ settings.blink_send_without_probe = False
+ calls = {"send": 0}
+
+ async def graphql(payload):
+ query = payload["query"]
+ if "lnInvoiceFeeProbe" in query:
+ return probe_response
+ if "lnInvoicePaymentSend" in query:
+ calls["send"] += 1
+ return {
+ "data": {"lnInvoicePaymentSend": {"status": "SUCCESS", "errors": []}}
+ }
+ return {"data": {}}
+
+ wallet = _make_blink_wallet_with_mock(graphql)
+ response = await wallet.pay_invoice(AMOUNT_BOLT11, fee_limit_msat=5000)
+
+ assert calls["send"] == 0
+ assert response.ok is False
+ assert response.error_message is not None
+ assert expected_error in response.error_message
+
+
+@pytest.mark.anyio
+async def test_pay_invoice_zero_amount_skips_probe_and_sends():
+ """Zero-amount invoices cannot be probed and fall back to sending."""
+ settings.blink_send_without_probe = True
+ calls = {"probe": 0, "send": 0}
+
+ async def graphql(payload):
+ query = payload["query"]
+ if "FeeProbe" in query:
+ calls["probe"] += 1
+ raise AssertionError("zero-amount invoices must not be probed")
+ if "lnInvoicePaymentSend" in query:
+ calls["send"] += 1
+ return {
+ "data": {"lnInvoicePaymentSend": {"status": "SUCCESS", "errors": []}}
+ }
+ return {"data": {}}
+
+ wallet = _make_blink_wallet_with_mock(graphql)
+ response = await wallet.pay_invoice(ZERO_BOLT11, fee_limit_msat=5000)
+
+ assert calls["probe"] == 0
+ assert calls["send"] == 1
+ assert response.ok is True
Why this scored 36/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.