feat: support hold invoices with the LNbits funding source (#4216)
What changed, and why it matters
This commit adds support for 'hold invoices' when LNbits uses another LNbits instance as its funding source. Hold invoices are a normal Lightning feature where payment is accepted but not immediately settled. The change is a feature addition with no obvious security bug in the diff itself, but it touches payment-handling code and adds new API endpoints for settle/cancel operations.
Review the new hold invoice settle/cancel endpoints for proper authorization and race-condition handling in production. Ensure upstream LNbits instances cannot be tricked into settling or canceling invoices they should not control. Consider whether hold invoice state transitions are idempotent and protected against replay.
Security signals we found
New payment settle/cancel API calls introduced in wallet adapter
Hold invoice state handling added to invoice status checks
Extensive test coverage added for create/settle/cancel flows and error handling
No authentication or authorization changes visible in the diff
No vendor disclosure of security relevance
Evidence from the diff
The patch implements hold invoice support for the LNbitsWallet funding source. It adds create_hold_invoice, settle_hold_invoice, and cancel_hold_invoice methods in lnbits/wallets/lnbits.py, forwards expiry/unhashed_description/description_hash in lnbits/core/services/payments.py and lnbits/wallets/lndrest.py, and adds extensive regtest/unit tests. The upstream LNbits instance is now backed by LND in the regtest docker setup. No vulnerability is directly visible in the diff.
Changed components
lnbits/wallets/lnbits.pylnbits/core/services/payments.pylnbits/wallets/lndrest.pydocker/regtest/docker-compose.ymldocker/regtest/docker-scripts.shtests/regtest/test_real_lnbits_hold_invoice.pytests/unit/test_lnbits_wallet_holdinvoice.pytests/unit/test_lndrest_holdinvoice.pytests/unit/test_services_hold_invoice.pyInspect captured patch +955 / −3
diff --git a/.github/workflows/regtest.yml b/.github/workflows/regtest.yml
index 1e7f7fa..5546cb2 100644
--- a/.github/workflows/regtest.yml
+++ b/.github/workflows/regtest.yml
@@ -89,3 +89,4 @@ jobs:
if: ${{ inputs.backend-wallet-class == 'LNbitsWallet' }}
run: |
docker logs lnbits-lnbits-1
+ docker logs lnbits-lnbits-lnd-1
diff --git a/docker/regtest/README.md b/docker/regtest/README.md
index bf3ef79..63d6d0a 100644
--- a/docker/regtest/README.md
+++ b/docker/regtest/README.md
@@ -4,7 +4,7 @@
- lnd-1: for locally testing your current lnbits
- lnd-2: used for boltz backend
-- lnd-3: used for LND funding-source tests
+- lnd-3: used for LND funding-source tests and backing lnbits-lnd inside docker
- cln-1: for locally testing your current lnbits and backing lnbits inside docker
- cln-2: used for clightning-REST
- cln-3: receives BOLT12 offer payments
diff --git a/docker/regtest/docker-compose.yml b/docker/regtest/docker-compose.yml
index 3b366d3..37b7910 100644
--- a/docker/regtest/docker-compose.yml
+++ b/docker/regtest/docker-compose.yml
@@ -21,6 +21,29 @@ services:
- lnbits-data:/app/data
- ./data/clightning-1:/app/clightning:uid=1000,gid=1000
+ # LNbits funded by LND, upstream for LNbitsWallet hold invoice tests
+ lnbits-lnd:
+ hostname: lnbits-lnd
+ depends_on:
+ - lnd-3
+ image: lnbits/lnbits
+ restart: on-failure
+ user: "0:0"
+ environment:
+ LNBITS_PORT: 5002
+ DEBUG: true
+ LNBITS_ADMIN_UI: false
+ LNBITS_BACKEND_WALLET_CLASS: "LndRestWallet"
+ LNBITS_DATA_FOLDER: "./data"
+ LND_REST_ENDPOINT: "https://lnd-3:8081/"
+ LND_REST_CERT: "./lnd/tls.cert"
+ LND_REST_MACAROON: "./lnd/data/chain/bitcoin/regtest/admin.macaroon"
+ ports:
+ - 5002:5002
+ volumes:
+ - lnbits-lnd-data:/app/data
+ - ./data/lnd-3:/app/lnd:ro
+
boltz:
hostname: boltz
depends_on:
@@ -422,6 +445,7 @@ services:
volumes:
lnbits-data:
+ lnbits-lnd-data:
bitcoin-data:
elements-data:
nginx-data:
diff --git a/docker/regtest/docker-scripts.sh b/docker/regtest/docker-scripts.sh
index 0beb5c2..e0aad7c 100644
--- a/docker/regtest/docker-scripts.sh
+++ b/docker/regtest/docker-scripts.sh
@@ -145,6 +145,17 @@ lnbits-elements-init(){
lnbits-init(){
echo "init_lnbits..."
docker exec lnbits-lnbits-1 uv run python tools/create_fake_admin.py
+ # restart now that the lnd-3 credentials exist
+ docker restart lnbits-lnbits-lnd-1 > /dev/null
+ wait-for-lnbits-lnd
+ docker exec lnbits-lnbits-lnd-1 uv run python tools/create_fake_admin.py
+}
+
+wait-for-lnbits-lnd(){
+ while ! curl -s -o /dev/null "http://localhost:5002/api/v1/health"; do
+ echo "waiting for lnbits-lnd..."
+ sleep 1
+ done
}
lnbits-regtest-init(){
diff --git a/docker/regtest/start-regtest b/docker/regtest/start-regtest
index 3ef66c2..9c17c7b 100755
--- a/docker/regtest/start-regtest
+++ b/docker/regtest/start-regtest
@@ -61,6 +61,7 @@ done
run "eclair-1 openchannels" 3 $(docker exec lnbits-eclair-1 curl -s http://localhost:8080/channels -X POST -u :lnbits| jq '. | length')
run "eclair-1 blockHeight" $blockheight $(docker exec lnbits-eclair-1 curl -s http://localhost:8080/getinfo -X POST -u :lnbits| jq '.blockHeight')
run "lnbits service status" "200" $(curl -s -o /dev/null -w "%{http_code}" "http://localhost:5001/")
+run "lnbits-lnd service status" "200" $(curl -s -o /dev/null -w "%{http_code}" "http://localhost:5002/")
run "boltz service status" "200" $(curl -s -o /dev/null --head -w "%{http_code}" "http://localhost:9001/version")
# return non-zero exit code if a test fails
diff --git a/lnbits/core/services/payments.py b/lnbits/core/services/payments.py
index 24648b9..ca4ae79 100644
--- a/lnbits/core/services/payments.py
+++ b/lnbits/core/services/payments.py
@@ -361,6 +361,8 @@ async def create_invoice(
memo=invoice_memo,
payment_hash=payment_hash,
description_hash=description_hash,
+ unhashed_description=unhashed_description,
+ expiry=expiry or settings.lightning_invoice_expiry,
)
extra["hold_invoice"] = True
except UnsupportedError as exc:
diff --git a/lnbits/wallets/lnbits.py b/lnbits/wallets/lnbits.py
index c1f5600..2cfe2f0 100644
--- a/lnbits/wallets/lnbits.py
+++ b/lnbits/wallets/lnbits.py
@@ -1,4 +1,5 @@
import asyncio
+import hashlib
import json
from collections.abc import AsyncGenerator
@@ -25,7 +26,7 @@ from .base import (
class LNbitsWallet(Wallet):
"""https://github.com/lnbits/lnbits"""
- features = [Feature.bolt12]
+ features = [Feature.bolt12, Feature.holdinvoice]
def __init__(self):
if not settings.lnbits_endpoint:
@@ -253,6 +254,8 @@ class LNbitsWallet(Wallet):
if data.get("paid", False) is True:
return PaymentSuccessStatus()
+ if data.get("status") == "failed":
+ return PaymentFailedStatus()
return PaymentPendingStatus()
except Exception:
return PaymentPendingStatus()
@@ -304,3 +307,101 @@ class LNbitsWallet(Wallet):
"retrying in 5 seconds"
)
await asyncio.sleep(5)
+
+ async def create_hold_invoice(
+ self,
+ amount: int,
+ payment_hash: str,
+ memo: str | None = None,
+ description_hash: bytes | None = None,
+ unhashed_description: bytes | None = None,
+ **kwargs,
+ ) -> InvoiceResponse:
+ data: dict = {
+ "out": False,
+ "amount": amount,
+ "memo": memo or "",
+ "payment_hash": payment_hash,
+ }
+ if kwargs.get("expiry"):
+ data["expiry"] = kwargs["expiry"]
+ if description_hash:
+ data["description_hash"] = description_hash.hex()
+ elif unhashed_description:
+ # Upstream versions may not forward unhashed_description for holds.
+ data["description_hash"] = hashlib.sha256(unhashed_description).hexdigest()
+ if unhashed_description:
+ data["unhashed_description"] = unhashed_description.hex()
+
+ try:
+ r = await self.client.post(url="/api/v1/payments", json=data)
+ r.raise_for_status()
+ payment = r.json()
+ if not isinstance(payment, dict) or not all(
+ isinstance(payment.get(field), str) and payment[field]
+ for field in ("checking_id", "bolt11")
+ ):
+ return InvoiceResponse(
+ ok=False, error_message="Server error: 'missing required fields'"
+ )
+ return InvoiceResponse(
+ ok=True,
+ checking_id=payment["checking_id"],
+ payment_request=payment["bolt11"],
+ )
+ except httpx.HTTPStatusError as exc:
+ return InvoiceResponse(ok=False, error_message=_error_detail(exc.response))
+ except (json.JSONDecodeError, KeyError) as exc:
+ logger.warning(exc)
+ return InvoiceResponse(
+ ok=False, error_message="Server error: 'invalid response'"
+ )
+ except Exception as exc:
+ logger.warning(exc)
+ return InvoiceResponse(
+ ok=False, error_message=f"Unable to connect to {self.endpoint}."
+ )
+
+ async def settle_hold_invoice(self, preimage: str) -> InvoiceResponse:
+ try:
+ r = await self.client.post(
+ url="/api/v1/payments/settle", json={"preimage": preimage}
+ )
+ r.raise_for_status()
+ return InvoiceResponse(ok=True, preimage=preimage)
+ except httpx.HTTPStatusError as exc:
+ return InvoiceResponse(ok=False, error_message=_error_detail(exc.response))
+ except Exception as exc:
+ logger.warning(exc)
+ return InvoiceResponse(
+ ok=False, error_message=f"Unable to connect to {self.endpoint}."
+ )
+
+ async def cancel_hold_invoice(self, payment_hash: str) -> InvoiceResponse:
+ try:
+ r = await self.client.post(
+ url="/api/v1/payments/cancel", json={"payment_hash": payment_hash}
+ )
+ r.raise_for_status()
+ return InvoiceResponse(ok=True, checking_id=payment_hash)
+ except httpx.HTTPStatusError as exc:
+ return InvoiceResponse(ok=False, error_message=_error_detail(exc.response))
+ except Exception as exc:
+ logger.warning(exc)
+ return InvoiceResponse(
+ ok=False, error_message=f"Unable to connect to {self.endpoint}."
+ )
+
+
+def _error_detail(response: httpx.Response) -> str:
+ try:
+ data = response.json()
+ except json.JSONDecodeError:
+ data = None
+ if isinstance(data, dict) and data.get("detail") is not None:
+ detail = data["detail"]
+ if not isinstance(detail, str):
+ return json.dumps(detail)
+ if detail:
+ return detail
+ return response.text or f"HTTP {response.status_code}"
diff --git a/lnbits/wallets/lndrest.py b/lnbits/wallets/lndrest.py
index 8becd03..0000874 100644
--- a/lnbits/wallets/lndrest.py
+++ b/lnbits/wallets/lndrest.py
@@ -347,13 +347,15 @@ class LndRestWallet(Wallet):
memo: str | None = None,
description_hash: bytes | None = None,
unhashed_description: bytes | None = None,
- **_,
+ **kwargs,
) -> InvoiceResponse:
data: dict = {
"value": amount,
"private": True,
"hash": base64.b64encode(bytes.fromhex(payment_hash)).decode("ascii"),
}
+ if kwargs.get("expiry"):
+ data["expiry"] = kwargs["expiry"]
if description_hash:
data["description_hash"] = base64.b64encode(description_hash).decode(
"ascii"
diff --git a/tests/regtest/helpers.py b/tests/regtest/helpers.py
index 0e1f4b6..778d008 100644
--- a/tests/regtest/helpers.py
+++ b/tests/regtest/helpers.py
@@ -12,6 +12,9 @@ from lnbits.wallets import get_funding_source
funding_source = get_funding_source()
is_boltz_wallet = funding_source.__class__.__name__ == "BoltzWallet"
+# LNbits inside docker funded by LND (lnd-3), supports hold invoices
+lnbits_lnd_endpoint = "http://localhost:5002"
+
docker_lightning_cli = [
"docker",
"exec",
diff --git a/tests/regtest/test_real_lnbits_hold_invoice.py b/tests/regtest/test_real_lnbits_hold_invoice.py
new file mode 100644
index 0000000..7ce32f5
--- /dev/null
+++ b/tests/regtest/test_real_lnbits_hold_invoice.py
@@ -0,0 +1,261 @@
+import asyncio
+import hashlib
+import json
+from contextlib import asynccontextmanager
+from subprocess import CalledProcessError
+
+import pytest
+from bolt11 import decode
+
+from lnbits.core.crud import get_payments, get_standalone_payment, get_wallet
+from lnbits.core.services import payments as service
+from lnbits.exceptions import InvoiceError
+from lnbits.settings import settings
+from lnbits.utils.crypto import random_secret_and_hash
+from lnbits.wallets import lnbits
+from lnbits.wallets.lnbits import LNbitsWallet
+
+from ..helpers import funding_source, is_fake
+from .helpers import docker_lightning_cli, lnbits_lnd_endpoint
+
+
+@pytest.fixture
+async def lnbits_lnd_wallet(app, monkeypatch: pytest.MonkeyPatch):
+ """Downstream payment services funded by an upstream LNbits on LND."""
+ monkeypatch.setattr(settings, "lnbits_endpoint", lnbits_lnd_endpoint)
+ wallet = LNbitsWallet()
+ monkeypatch.setattr(service, "get_funding_source", lambda: wallet)
+ try:
+ yield wallet
+ finally:
+ await wallet.cleanup()
+
+
+@pytest.mark.anyio
+@pytest.mark.skipif(is_fake, reason="this only works in regtest")
+@pytest.mark.skipif(
+ funding_source.__class__.__name__ != "LNbitsWallet",
+ reason="this only works for LNbitsWallet",
+)
+@pytest.mark.parametrize(
+ ("description_hash", "unhashed_description"),
+ [
+ (None, b"hold metadata"),
+ (b"e" * 32, None),
+ (b"e" * 32, b"hold metadata"),
+ ],
+)
+async def test_settle_real_hold_invoice_upstream(
+ app,
+ lnbits_lnd_wallet: LNbitsWallet,
+ from_wallet,
+ monkeypatch,
+ description_hash,
+ unhashed_description,
+):
+ wallet = lnbits_lnd_wallet
+ before = await get_wallet(from_wallet.id)
+ assert before
+ preimage, payment_hash = random_secret_and_hash()
+ payment = await service.create_invoice(
+ wallet_id=from_wallet.id,
+ amount=1000,
+ payment_hash=payment_hash,
+ memo="test_settle_upstream_holdinvoice",
+ expiry=600,
+ description_hash=description_hash,
+ unhashed_description=unhashed_description,
+ )
+ invoice = decode(payment.bolt11)
+ assert invoice.payment_hash == payment_hash
+ assert invoice.amount_msat == 1_000_000
+ assert invoice.expiry == 600
+ assert invoice.description_hash == (
+ description_hash.hex()
+ if description_hash
+ else hashlib.sha256(unhashed_description).hexdigest()
+ )
+
+ with pytest.raises(InvoiceError):
+ await service.settle_hold_invoice(payment, preimage)
+
+ # Establish the websocket subscription before allowing settlement.
+ connected = asyncio.Event()
+ connect = lnbits.connect
+
+ @asynccontextmanager
+ async def subscribed(*args, **kwargs):
+ async with connect(*args, **kwargs) as websocket:
+ if asyncio.current_task() is paid:
+ connected.set()
+ yield websocket
+
+ monkeypatch.setattr(lnbits, "connect", subscribed)
+ stream = wallet.paid_invoices_stream()
+ paid = asyncio.create_task(anext(stream))
+ try:
+ await asyncio.wait_for(connected.wait(), timeout=10)
+ async with _paying(wallet, payment.bolt11, payment_hash) as payer:
+ await _wait_for_invoice_state(payment_hash, "ACCEPTED", payer)
+ await _assert_pending_without_credit(
+ payment_hash, from_wallet.id, before.balance_msat
+ )
+ assert (await wallet.get_invoice_status(payment_hash)).pending
+ assert (await service.settle_hold_invoice(payment, preimage)).ok
+ await _wait_for_invoice_state(payment_hash, "SETTLED")
+ result = await asyncio.wait_for(payer, timeout=15)
+ assert result["status"] == "SUCCEEDED", result
+ assert result["payment_preimage"] == preimage
+
+ # Preserve actual upstream websocket coverage and reconcile downstream.
+ assert await asyncio.wait_for(paid, timeout=10) == payment_hash
+ for _ in range(2):
+ updated = await service.update_invoice_from_paid_invoices_stream(
+ payment_hash
+ )
+ assert updated and updated.success
+ await service.update_pending_payment(updated)
+ stored = await get_standalone_payment(payment_hash, incoming=True)
+ assert stored and stored.success
+ assert stored.preimage == preimage
+ after = await get_wallet(from_wallet.id)
+ assert after and after.balance_msat == before.balance_msat + 1_000_000
+ records = await get_payments(wallet_id=from_wallet.id, incoming=True)
+ assert len([p for p in records if p.payment_hash == payment_hash]) == 1
+ assert (await wallet.get_invoice_status(payment_hash)).success
+ finally:
+ paid.cancel()
+ await asyncio.gather(paid, return_exceptions=True)
+ await stream.aclose()
+
+
+@pytest.mark.anyio
+@pytest.mark.skipif(is_fake, reason="this only works in regtest")
+@pytest.mark.skipif(
+ funding_source.__class__.__name__ != "LNbitsWallet",
+ reason="this only works for LNbitsWallet",
+)
+async def test_cancel_real_hold_invoice_upstream(
+ app, lnbits_lnd_wallet: LNbitsWallet, from_wallet
+):
+ wallet = lnbits_lnd_wallet
+ before = await get_wallet(from_wallet.id)
+ assert before
+ _, payment_hash = random_secret_and_hash()
+ payment = await service.create_invoice(
+ wallet_id=from_wallet.id,
+ amount=1000,
+ payment_hash=payment_hash,
+ memo="test_cancel_upstream_holdinvoice",
+ )
+
+ async with _paying(wallet, payment.bolt11, payment_hash) as payer:
+ await _wait_for_invoice_state(payment_hash, "ACCEPTED", payer)
+ await _assert_pending_without_credit(
+ payment_hash, from_wallet.id, before.balance_msat
+ )
+ assert (await service.cancel_hold_invoice(payment)).ok
+ await _wait_for_invoice_state(payment_hash, "CANCELED")
+ # lncli exits 1 for a terminal failed payment. Only accept its specific
+ # terminal result; command errors and routing failures must fail the test.
+ with pytest.raises(CalledProcessError) as failure:
+ await asyncio.wait_for(payer, timeout=15)
+ assert failure.value.returncode == 1
+ assert failure.value.stderr.strip() == "[lncli] FAILED"
+ result = json.loads(failure.value.output)
+ assert result["status"] == "FAILED", result
+ assert (
+ result["failure_reason"] == "FAILURE_REASON_INCORRECT_PAYMENT_DETAILS"
+ ), result
+ assert result["htlcs"], result
+ assert all(
+ htlc["failure"]["code"] == "INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS"
+ for htlc in result["htlcs"]
+ ), result
+ assert (await wallet.get_invoice_status(payment_hash)).failed
+ stored = await get_standalone_payment(payment_hash, incoming=True)
+ assert stored and stored.failed
+ assert stored.extra["hold_invoice_cancelled"] is True
+ after = await get_wallet(from_wallet.id)
+ assert after and after.balance_msat == before.balance_msat
+
+
+async def _assert_pending_without_credit(payment_hash, wallet_id, balance_msat):
+ stored = await get_standalone_payment(payment_hash, incoming=True)
+ assert stored and stored.pending
+ assert (await service.update_pending_payment(stored)).pending
+ recipient = await get_wallet(wallet_id)
+ assert recipient and recipient.balance_msat == balance_msat
+
+
+async def _wait_for_invoice_state(payment_hash, expected, payer=None):
+ # The upstream LNbits uses lnd-3; lnd-1 is the payer.
+ command = [
+ "docker",
+ "exec",
+ "lnbits-lnd-3-1",
+ "lncli",
+ "--network=regtest",
+ "--rpcserver=lnd-3",
+ "lookupinvoice",
+ payment_hash,
+ ]
+
+ async def poll():
+ state = None
+ for _ in range(100):
+ invoice = await _run_json(command)
+ state = invoice["state"]
+ if state == expected:
+ return
+ if payer is not None and payer.done():
+ raise AssertionError(f"Payer ended before {expected}: {await payer}")
+ await asyncio.sleep(0.1)
+ raise AssertionError(f"Expected LND {expected}, last state: {state}")
+
+ await asyncio.wait_for(poll(), timeout=20)
+
+
+@asynccontextmanager
+async def _paying(wallet, bolt11, payment_hash):
+ payer = asyncio.create_task(
+ _run_json(
+ [
+ *docker_lightning_cli,
+ "payinvoice",
+ "--force",
+ "--json",
+ bolt11,
+ ]
+ )
+ )
+ try:
+ yield payer
+ finally:
+ try:
+ if not payer.done():
+ # Release the held HTLC even when an assertion failed.
+ await wallet.cancel_hold_invoice(payment_hash)
+ finally:
+ payer.cancel()
+ await asyncio.gather(payer, return_exceptions=True)
+
+
+async def _run_json(command):
+ process = await asyncio.create_subprocess_exec(
+ *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
+ )
+ try:
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=30)
+ if process.returncode:
+ raise CalledProcessError(
+ process.returncode,
+ command,
+ output=stdout.decode(),
+ stderr=stderr.decode(),
+ )
+ return json.loads(stdout)
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
diff --git a/tests/unit/test_lnbits_wallet_holdinvoice.py b/tests/unit/test_lnbits_wallet_holdinvoice.py
new file mode 100644
index 0000000..14117bd
--- /dev/null
+++ b/tests/unit/test_lnbits_wallet_holdinvoice.py
@@ -0,0 +1,286 @@
+import hashlib
+import json
+
+import httpx
+import pytest
+
+from lnbits.wallets.base import Feature
+from lnbits.wallets.lnbits import LNbitsWallet
+
+PAYMENT_HASH = "ab" * 32
+PREIMAGE = "cd" * 32
+BOLT11 = "lnbcrt10u1fakeholdinvoice"
+
+
+def test_lnbits_wallet_advertises_holdinvoice():
+ assert Feature.holdinvoice in (LNbitsWallet.features or [])
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("expiry", [None, 0, 600])
+@pytest.mark.parametrize(
+ ("description_hash", "unhashed_description"),
+ [
+ (None, None),
+ (None, b"hold metadata"),
+ (b"e" * 32, None),
+ (b"e" * 32, b"hold metadata"),
+ ],
+)
+async def test_lnbits_create_hold_invoice(
+ expiry, description_hash, unhashed_description
+):
+ requests: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(
+ 201,
+ json={
+ "checking_id": PAYMENT_HASH,
+ "payment_hash": PAYMENT_HASH,
+ "bolt11": BOLT11,
+ "preimage": None,
+ },
+ )
+
+ wallet = _wallet(handler)
+ try:
+ response = await wallet.create_hold_invoice(
+ amount=1000,
+ payment_hash=PAYMENT_HASH,
+ memo="hold",
+ description_hash=description_hash,
+ unhashed_description=unhashed_description,
+ expiry=expiry,
+ )
+ assert response.ok is True
+ assert response.checking_id == PAYMENT_HASH
+ assert response.payment_request == BOLT11
+ assert response.preimage is None
+ assert requests[0].method == "POST"
+ assert requests[0].url.path == "/api/v1/payments"
+ expected = {
+ "out": False,
+ "amount": 1000,
+ "memo": "hold",
+ "payment_hash": PAYMENT_HASH,
+ }
+ if expiry:
+ expected["expiry"] = expiry
+ if description_hash:
+ expected["description_hash"] = description_hash.hex()
+ elif unhashed_description:
+ expected["description_hash"] = hashlib.sha256(
+ unhashed_description
+ ).hexdigest()
+ if unhashed_description:
+ expected["unhashed_description"] = unhashed_description.hex()
+ assert json.loads(requests[0].content) == expected
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+async def test_lnbits_create_hold_invoice_forwards_backend_error():
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 520,
+ json={
+ "detail": "Hold invoices are not supported by the funding source.",
+ "status": "failed",
+ },
+ )
+
+ wallet = _wallet(handler)
+ try:
+ response = await wallet.create_hold_invoice(
+ amount=1000, payment_hash=PAYMENT_HASH
+ )
+ assert response.ok is False
+ assert (
+ response.error_message
+ == "Hold invoices are not supported by the funding source."
+ )
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+async def test_lnbits_settle_hold_invoice():
+ requests: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(200, json={"ok": True, "preimage": PREIMAGE})
+
+ wallet = _wallet(handler)
+ try:
+ response = await wallet.settle_hold_invoice(preimage=PREIMAGE)
+ assert response.ok is True
+ assert response.preimage == PREIMAGE
+ assert requests[0].url.path == "/api/v1/payments/settle"
+ assert json.loads(requests[0].content) == {"preimage": PREIMAGE}
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+async def test_lnbits_settle_hold_invoice_error():
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 520, json={"detail": "invoice is still open", "status": "failed"}
+ )
+
+ wallet = _wallet(handler)
+ try:
+ response = await wallet.settle_hold_invoice(preimage=PREIMAGE)
+ assert response.ok is False
+ assert response.error_message == "invoice is still open"
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+async def test_lnbits_cancel_hold_invoice():
+ requests: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(200, json={"ok": True, "checking_id": PAYMENT_HASH})
+
+ wallet = _wallet(handler)
+ try:
+ response = await wallet.cancel_hold_invoice(payment_hash=PAYMENT_HASH)
+ assert response.ok is True
+ assert response.checking_id == PAYMENT_HASH
+ assert requests[0].url.path == "/api/v1/payments/cancel"
+ assert json.loads(requests[0].content) == {"payment_hash": PAYMENT_HASH}
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+async def test_lnbits_cancel_hold_invoice_unreachable():
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("connection refused", request=request)
+
+ wallet = _wallet(handler)
+ try:
+ response = await wallet.cancel_hold_invoice(payment_hash=PAYMENT_HASH)
+ assert response.ok is False
+ assert response.error_message == "Unable to connect to http://lnbits.test."
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ ("body", "expected"),
+ [
+ ({"paid": True, "preimage": PREIMAGE}, "success"),
+ ({"paid": False, "status": "failed"}, "failed"),
+ ({"paid": False, "status": "pending"}, "pending"),
+ ({"paid": False}, "pending"),
+ ],
+)
+async def test_lnbits_get_invoice_status(body, expected):
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=body)
+
+ wallet = _wallet(handler)
+ try:
+ status = await wallet.get_invoice_status(PAYMENT_HASH)
+ assert getattr(status, expected) is True
+ finally:
+ await wallet.client.aclose()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "body",
+ [
+ "not json",
+ "null",
+ "[]",
+ "{}",
+ json.dumps({"checking_id": PAYMENT_HASH}),
+ json.dumps({"bolt11": BOLT11}),
+ json.dumps({"checking_id": None, "bolt11": BOLT11}),
+ json.dumps({"checking_id": PAYMENT_HASH, "bolt11": ""}),
+ json.dumps({"checking_id": PAYMENT_HASH, "bolt11": {"invalid": True}}),
+ ],
+)
+async def test_lnbits_create_hold_invoice_invalid_response(body):
+ wallet = _wallet(lambda _: httpx.Response(201, text=body))
+ try:
+ response = await wallet.create_hold_invoice(1000, PAYMENT_HASH)
+ assert response.ok is False
+ assert isinstance(response.error_message, str)
+ assert response.error_message.startswith("Server error:")
+ assert response.checking_id is None
+ assert response.payment_request is None
+ finally:
+ await wallet.cleanup()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("operation", ["create", "settle", "cancel"])
+@pytest.mark.parametrize(
+ ("body", "expected"),
+ [
+ ('{"detail":"hold rejected"}', "hold rejected"),
+ ('{"detail":{"reason":"hold rejected"}}', '{"reason": "hold rejected"}'),
+ ('{"detail":[{"msg":"invalid hash"}]}', '[{"msg": "invalid hash"}]'),
+ ('{"detail":42}', "42"),
+ ('{"detail":false}', "false"),
+ ('{"detail":null}', '{"detail":null}'),
+ ('{"detail":""}', '{"detail":""}'),
+ ('{"error":"unavailable"}', '{"error":"unavailable"}'),
+ ('["unavailable"]', '["unavailable"]'),
+ ("upstream unavailable", "upstream unavailable"),
+ ("", "HTTP 502"),
+ ],
+)
+async def test_lnbits_hold_invoice_http_errors(operation, body, expected):
+ wallet = _wallet(lambda _: httpx.Response(502, text=body))
+ try:
+ response = await _hold_operation(wallet, operation)
+ assert response.ok is False
+ assert isinstance(response.error_message, str)
+ assert response.error_message == expected
+ finally:
+ await wallet.cleanup()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("operation", ["create", "settle", "cancel"])
+@pytest.mark.parametrize("error", [httpx.ConnectTimeout, httpx.ReadTimeout])
+async def test_lnbits_hold_invoice_timeouts(operation, error):
+ def handler(request):
+ raise error("upstream timed out", request=request)
+
+ wallet = _wallet(handler)
+ try:
+ response = await _hold_operation(wallet, operation)
+ assert response.ok is False
+ assert response.error_message == "Unable to connect to http://lnbits.test."
+ finally:
+ await wallet.cleanup()
+
+
+async def _hold_operation(wallet, operation):
+ if operation == "create":
+ return await wallet.create_hold_invoice(1000, PAYMENT_HASH)
+ if operation == "settle":
+ return await wallet.settle_hold_invoice(PREIMAGE)
+ return await wallet.cancel_hold_invoice(PAYMENT_HASH)
+
+
+def _wallet(handler) -> LNbitsWallet:
+ wallet = object.__new__(LNbitsWallet)
+ wallet.endpoint = "http://lnbits.test"
+ wallet.client = httpx.AsyncClient(
+ base_url=wallet.endpoint, transport=httpx.MockTransport(handler)
+ )
+ return wallet
diff --git a/tests/unit/test_lndrest_holdinvoice.py b/tests/unit/test_lndrest_holdinvoice.py
new file mode 100644
index 0000000..04737ce
--- /dev/null
+++ b/tests/unit/test_lndrest_holdinvoice.py
@@ -0,0 +1,60 @@
+import base64
+import hashlib
+import json
+
+import httpx
+import pytest
+
+from lnbits.wallets.lndrest import LndRestWallet
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("expiry", [None, 0, 600])
+@pytest.mark.parametrize(
+ ("description_hash", "unhashed_description"),
+ [
+ (None, None),
+ (None, b"hold metadata"),
+ (b"e" * 32, None),
+ (b"e" * 32, b"hold metadata"),
+ ],
+)
+async def test_lndrest_hold_invoice_optional_fields(
+ expiry, description_hash, unhashed_description
+):
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return httpx.Response(200, json={"payment_request": "hold-bolt11"})
+
+ wallet = object.__new__(LndRestWallet)
+ async with httpx.AsyncClient(
+ base_url="https://lnd.test", transport=httpx.MockTransport(handler)
+ ) as wallet.client:
+ response = await wallet.create_hold_invoice(
+ 1000,
+ "ab" * 32,
+ memo="hold",
+ expiry=expiry,
+ description_hash=description_hash,
+ unhashed_description=unhashed_description,
+ )
+
+ assert response.ok
+ assert requests[0].url.path == "/v2/invoices/hodl"
+ data = json.loads(requests[0].content)
+ if expiry:
+ assert data["expiry"] == expiry
+ else:
+ # Leave LND's default in place for direct adapter calls.
+ assert "expiry" not in data
+ expected_hash = description_hash or (
+ hashlib.sha256(unhashed_description).digest() if unhashed_description else None
+ )
+ if expected_hash:
+ assert base64.b64decode(data["description_hash"]) == expected_hash
+ assert "memo" not in data
+ else:
+ assert data["memo"] == "hold"
+ assert "description_hash" not in data
diff --git a/tests/unit/test_services_hold_invoice.py b/tests/unit/test_services_hold_invoice.py
new file mode 100644
index 0000000..78f8a05
--- /dev/null
+++ b/tests/unit/test_services_hold_invoice.py
@@ -0,0 +1,200 @@
+import asyncio
+import hashlib
+import json
+import time
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+from bolt11 import Bolt11, MilliSatoshi, TagChar, Tags, decode, encode
+
+from lnbits.core.crud import (
+ create_wallet,
+ get_payments,
+ get_standalone_payment,
+ get_wallet,
+)
+from lnbits.core.models import CreateInvoice
+from lnbits.core.services import create_user_account, notifications
+from lnbits.core.services import payments as service
+from lnbits.utils.crypto import random_secret_and_hash
+from lnbits.wallets.lnbits import LNbitsWallet
+
+
+@pytest.fixture
+async def recipient(app):
+ user = await create_user_account()
+ return await create_wallet(user_id=user.id)
+
+
+@pytest.fixture
+async def upstream(monkeypatch):
+ state = {"status": "pending"}
+
+ def handler(request):
+ if request.url.path.endswith("/settle"):
+ state["status"] = "success"
+ return httpx.Response(200, json={"ok": True})
+ if request.url.path.endswith("/cancel"):
+ state["status"] = "failed"
+ return httpx.Response(200, json={"ok": True})
+ if request.method == "GET":
+ return httpx.Response(
+ 200,
+ json={"paid": state["status"] == "success", "status": state["status"]},
+ )
+ data = json.loads(request.content)
+ return httpx.Response(
+ 201,
+ json={"checking_id": data["payment_hash"], "bolt11": _invoice(data)},
+ )
+
+ wallet = object.__new__(LNbitsWallet)
+ wallet.endpoint = "http://upstream.test"
+ async with httpx.AsyncClient(
+ base_url=wallet.endpoint, transport=httpx.MockTransport(handler)
+ ) as wallet.client:
+ monkeypatch.setattr(service, "get_funding_source", lambda: wallet)
+ yield wallet
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("expiry", [None, 0, 600])
+@pytest.mark.parametrize(
+ ("description_hash", "unhashed_description"),
+ [(None, None), (None, b"metadata"), (b"e" * 32, None), (b"e" * 32, b"metadata")],
+)
+async def test_hold_service_forwards_optional_fields(
+ recipient,
+ upstream,
+ settings,
+ monkeypatch,
+ expiry,
+ description_hash,
+ unhashed_description,
+):
+ settings.lightning_invoice_expiry = 1800
+ create_hold = AsyncMock(wraps=upstream.create_hold_invoice)
+ monkeypatch.setattr(upstream, "create_hold_invoice", create_hold)
+ _, payment_hash = random_secret_and_hash()
+ payment = await service.create_wallet_invoice(
+ recipient.id,
+ CreateInvoice(
+ amount=1000,
+ memo="hold",
+ payment_hash=payment_hash,
+ expiry=expiry,
+ description_hash=description_hash.hex() if description_hash else None,
+ unhashed_description=(
+ unhashed_description.hex() if unhashed_description else None
+ ),
+ ),
+ )
+ create_hold.assert_awaited_once_with(
+ amount=1000,
+ memo=None if description_hash else ("" if unhashed_description else "hold"),
+ payment_hash=payment_hash,
+ description_hash=description_hash,
+ unhashed_description=unhashed_description,
+ expiry=expiry or 1800,
+ )
+ invoice = decode(payment.bolt11)
+ assert invoice.payment_hash == payment_hash
+ assert invoice.amount_msat == 1_000_000
+ assert invoice.expiry == (expiry or 1800)
+ assert invoice.description_hash == (
+ description_hash.hex()
+ if description_hash
+ else (
+ hashlib.sha256(unhashed_description).hexdigest()
+ if unhashed_description
+ else None
+ )
+ )
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("settle", [True, False])
+async def test_hold_service_accounting(recipient, upstream, settle, monkeypatch):
+ preimage, payment_hash = random_secret_and_hash()
+ payment = await service.create_invoice(
+ wallet_id=recipient.id, amount=1000, memo="hold", payment_hash=payment_hash
+ )
+ assert payment.extra["hold_invoice"] is True
+ payment = await get_standalone_payment(payment_hash, incoming=True)
+ assert payment
+
+ notified = asyncio.Event()
+ messages = []
+
+ async def notify(wallet, received):
+ if wallet.id == recipient.id:
+ messages.append((wallet.balance_msat, received))
+ notified.set()
+
+ async def paid_invoices():
+ yield payment_hash
+
+ monkeypatch.setattr(upstream, "paid_invoices_stream", paid_invoices)
+ monkeypatch.setattr(notifications, "send_ws_payment_notification", notify)
+
+ # Upstream reports accepted HTLCs as unpaid/pending until settlement.
+ payment = await service.update_pending_payment(payment)
+ assert payment.pending
+ balance = await get_wallet(recipient.id)
+ assert balance and balance.balance_msat == 0
+ await service.fundingsource_invoice_producer()
+ assert not messages
+
+ if settle:
+ assert (await service.settle_hold_invoice(payment, preimage)).ok
+ # Exercise the same reconciliation used by the funding-source stream,
+ # including a repeated notification and a subsequent polling update.
+ for _ in range(2):
+ notified.clear()
+ await service.fundingsource_invoice_producer()
+ await asyncio.wait_for(notified.wait(), timeout=5)
+ assert messages[-1][0] == 1_000_000
+ assert messages[-1][1].payment_hash == payment_hash
+ assert messages[-1][1].success
+ updated = await get_standalone_payment(payment_hash, incoming=True)
+ assert updated and updated.success
+ assert updated.preimage == preimage
+ assert updated.extra["hold_invoice_settled"] is True
+ await service.update_pending_payment(updated)
+ else:
+ assert (await service.cancel_hold_invoice(payment)).ok
+ updated = await service.update_pending_payment(payment)
+ assert updated.failed
+ assert updated.extra["hold_invoice_cancelled"] is True
+ assert (
+ await service.update_invoice_from_paid_invoices_stream(payment_hash) is None
+ )
+ assert not messages
+
+ stored = await get_standalone_payment(payment_hash, incoming=True)
+ assert stored
+ assert stored.success if settle else stored.failed
+ balance = await get_wallet(recipient.id)
+ assert balance and balance.balance_msat == (1_000_000 if settle else 0)
+ assert len(await get_payments(wallet_id=recipient.id, incoming=True)) == 1
+
+
+def _invoice(data):
+ tags = Tags()
+ tags.add(TagChar.payment_hash, data["payment_hash"])
+ tags.add(TagChar.payment_secret, "cd" * 32)
+ tags.add(TagChar.expire_time, data["expiry"])
+ if data.get("description_hash"):
+ tags.add(TagChar.description_hash, data["description_hash"])
+ else:
+ tags.add(TagChar.description, data["memo"])
+ return encode(
+ Bolt11(
+ currency="bcrt",
+ amount_msat=MilliSatoshi(data["amount"] * 1000),
+ date=int(time.time()),
+ tags=tags,
+ ),
+ private_key="ab" * 32,
+ )
Why this scored 32/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.