What changed, and why it matters
This commit fixes how LNbits notifies the user interface about incoming Lightning payments. Previously, the same paid invoice could be processed and announced multiple times, causing duplicate or confusing wallet notifications. The change centralizes the 'mark as paid' logic under a database lock and only queues one WebSocket notification per invoice. There is no direct evidence in the commit of a security vulnerability such as theft of funds, but duplicate notifications could mislead users or downstream systems and the race condition hints at possible state inconsistencies.
Treat as a reliability/bug-fix commit rather than a critical security patch. Reviewers should verify that the new _update_incoming_payment_status helper is always called with an already-held database connection when invoked from update_pending_payment, and that the frontend no longer double-counts incoming payments. If running LNbits, apply during normal maintenance; no emergency response is indicated by this diff alone.
Security signals we found
Race condition in payment status update between polling loop and paid-invoice stream
Duplicate WebSocket notifications for the same settled invoice
Refactoring to atomic DB-lock guarded update of incoming payment status
Removal of duplicate invoice_queue.put_nowait calls
No explicit authentication, authorization, or cryptographic changes
Evidence from the diff
The patch refactors incoming-payment finalization in lnbits/core/services/payments.py. It introduces _update_incoming_payment_status(), which re-reads the current payment row under the existing database connection/lock, checks whether it is already successful, updates fee/preimage/status atomically, and only puts the payment on task_manager.invoice_queue once. update_pending_payment() and update_invoice_from_paid_invoices_stream() are rewritten to use this helper, and the producer no longer queues the event itself. Frontend JS and tests are updated to expect a single notification. The commit addresses a race between polling and the paid-invoice stream that could double-notify or double-settle, but the diff alone does not prove an exploitable security flaw.
Changed components
lnbits/core/services/payments.pylnbits/static/bundle-components.min.jslnbits/static/js/components/lnbits-manage-wallet-list.jstests/api/test_payment_status_api.pytests/unit/test_services_hold_invoice.pytests/unit/test_services_payments.pytests/unit/wallet-updates.test.cjsInspect captured patch +388 / −29
### lnbits/core/services/payments.py
@@ -431,14 +431,16 @@ async def update_pending_payments(wallet_id: str):
async def update_pending_payment(
payment: Payment, conn: Connection | None = None
) -> Payment:
- if payment.is_in and payment.is_expired:
- payment.status = PaymentState.FAILED
- payment.labels.append("expired")
- await update_payment(payment, conn=conn)
- logger.info(f"invoice {payment.checking_id} expired, marked as failed")
+ if payment.is_in and payment.success:
return payment
+ if payment.is_in and payment.is_expired:
+ return await _update_incoming_payment_status(
+ payment, PaymentFailedStatus(), conn=conn, expired=True
+ )
status = await check_payment_status(payment)
+ if payment.is_in and (status.success or status.failed):
+ return await _update_incoming_payment_status(payment, status, conn=conn)
if status.failed:
payment.status = PaymentState.FAILED
payment = await update_payment(payment, conn=conn)
@@ -1317,6 +1319,8 @@ async def update_invoice_from_paid_invoices_stream(checking_id: str) -> Payment
if not payment:
logger.warning(f"No incoming payment found for '{checking_id}'.")
return None
+ if payment.success:
+ return payment
status = await check_payment_status(payment)
@@ -1326,13 +1330,7 @@ async def update_invoice_from_paid_invoices_stream(checking_id: str) -> Payment
)
return None
- payment.fee = status.fee_msat or payment.fee
- # only overwrite preimage if status.preimage provides it
- payment.preimage = status.preimage or payment.preimage
- payment.status = PaymentState.SUCCESS
- payment = await update_payment(payment)
-
- return payment
+ return await _update_incoming_payment_status(payment, status)
async def fundingsource_invoice_producer() -> None:
@@ -1347,7 +1345,6 @@ async def fundingsource_invoice_producer() -> None:
payment = await update_invoice_from_paid_invoices_stream(checking_id)
if payment:
logger.success(f"fundingsource invoice {checking_id} settled")
- task_manager.invoice_queue.put_nowait(payment)
def _validate_offer_payment_request(
@@ -1517,3 +1514,37 @@ async def _handle_external_payment_response(
)
return payment
+
+
+async def _update_incoming_payment_status(
+ payment: Payment,
+ status: PaymentStatus,
+ conn: Connection | None = None,
+ expired: bool = False,
+) -> Payment:
+ if not status.success and not status.failed:
+ raise ValueError("Cannot update an incoming payment with a pending status.")
+
+ # Polling and the stream can both hold a pending copy of the same invoice.
+ # Check and settle under the existing DB lock so only one queues the event.
+ async with db.reuse_conn(conn) if conn else db.connect() as new_conn:
+ current = await get_standalone_payment(
+ payment.checking_id, incoming=True, conn=new_conn
+ )
+ if not current or current.success:
+ return current or payment
+
+ if status.success:
+ current.fee = status.fee_msat or current.fee
+ current.preimage = status.preimage or current.preimage
+ current.status = PaymentState.SUCCESS
+ else:
+ current.status = PaymentState.FAILED
+ if expired:
+ if "expired" not in current.labels:
+ current.labels.append("expired")
+ logger.info(f"invoice {current.checking_id} expired, marked as failed")
+ payment = await update_payment(current, conn=new_conn)
+ if payment.success:
+ task_manager.invoice_queue.put_nowait(payment)
+ return payment
### lnbits/static/bundle-components.min.js
[binary or diff unavailable]
### lnbits/static/js/components/lnbits-manage-wallet-list.js
@@ -71,8 +71,30 @@ window.app.component('lnbits-manage-wallet-list', {
if (!this.g.walletEventListeners.includes(wallet.id)) {
this.g.walletEventListeners.push(wallet.id)
const ws = new WebSocket(`${websocketUrl}/${wallet.inkey}`)
- ws.onmessage = this.onWebsocketMessage
- ws.onopen = () => console.log('ws connected for wallet', wallet.id)
+ let receivedPayment = false
+ ws.onmessage = ev => {
+ receivedPayment = true
+ this.onWebsocketMessage(ev)
+ }
+ ws.onopen = async () => {
+ console.log('ws connected for wallet', wallet.id)
+ try {
+ const {data} = await LNbits.api.getWallet(wallet)
+ // A live payment already refreshed the UI if it arrived meanwhile.
+ if (receivedPayment || ws.readyState !== WebSocket.OPEN) return
+ const currentWallet = this.g.user?.wallets.find(
+ w => w.id === wallet.id
+ )
+ if (!currentWallet) return
+ currentWallet.sat = Math.floor(data.balance / 1000)
+ if (this.g.wallet?.id === wallet.id) {
+ this.g.wallet.sat = currentWallet.sat
+ this.g.updatePayments = !this.g.updatePayments
+ }
+ } catch {
+ console.warn('Failed to refresh wallet', wallet.id)
+ }
+ }
// onclose and onerror can both happen on their own or together,
// so we add a clearTimeout to avoid multiple reconnections
ws.onclose = () => {
### tests/api/test_payment_status_api.py
@@ -7,7 +7,12 @@
from lnbits.core.crud.payments import create_payment, get_payment, update_payment
from lnbits.core.models import CreatePayment, PaymentState
from lnbits.core.models.wallets import WalletType
+from lnbits.core.services.payments import (
+ update_invoice_from_paid_invoices_stream,
+ update_pending_payment,
+)
from lnbits.task_manager import task_manager
+from lnbits.wallets.base import PaymentSuccessStatus
async def status_payment(
@@ -112,7 +117,7 @@ async def test_change_status_notifies_only_on_success(
@pytest.mark.parametrize("amount", [-10_000, 10_000])
@pytest.mark.parametrize("status", [PaymentState.PENDING, PaymentState.FAILED])
async def test_change_status_success_can_skip_notifications(
- client, superuser_token, from_user, notification_tasks, amount, status
+ client, superuser_token, from_user, notification_tasks, mocker, amount, status
):
payment, preimage = await status_payment(from_user, status, amount)
response = await change_status(
@@ -132,6 +137,21 @@ async def test_change_status_success_can_skip_notifications(
assert stored_payment.preimage == preimage
assert stored_payment.labels == ["existing", "status-changed"]
assert stored_payment.webhook_status is None
+ if amount > 0:
+ queued = mocker.patch.object(task_manager.invoice_queue, "put_nowait")
+ mocker.patch(
+ "lnbits.core.services.payments.check_payment_status",
+ return_value=PaymentSuccessStatus(),
+ )
+ # Neither a late stream event nor an old polling copy may replay the
+ # notification that the administrator explicitly suppressed.
+ assert (
+ await update_invoice_from_paid_invoices_stream(payment.checking_id)
+ == stored_payment
+ )
+ assert (await update_pending_payment(payment)).success
+ queued.assert_not_called()
+ assert not notification_tasks
@pytest.mark.anyio
### tests/unit/test_services_hold_invoice.py
@@ -150,18 +150,18 @@ async def paid_invoices():
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)
+ await service.fundingsource_invoice_producer()
+ await asyncio.wait_for(notified.wait(), timeout=5)
+ assert messages[0][0] == 1_000_000
+ assert messages[0][1].payment_hash == payment_hash
+ assert messages[0][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.fundingsource_invoice_producer()
+ await service.update_pending_payment(updated)
+ assert len(messages) == 1
else:
assert (await service.cancel_hold_invoice(payment)).ok
updated = await service.update_pending_payment(payment)
### tests/unit/test_services_payments.py
@@ -33,15 +33,18 @@
check_wallet_limits,
create_payment_request,
create_wallet_invoice,
+ fundingsource_invoice_producer,
get_payments_daily_stats,
settle_hold_invoice,
+ update_invoice_from_paid_invoices_stream,
update_pending_payment,
update_pending_payments,
update_wallet_balance,
)
from lnbits.db import Filters, Page
from lnbits.exceptions import InvoiceError, PaymentError
from lnbits.settings import Settings
+from lnbits.task_manager import task_manager
from lnbits.wallets.base import (
InvoiceResponse,
PaymentFailedStatus,
@@ -257,6 +260,154 @@ async def test_update_pending_payment_marks_expired_incoming_invoice_failed(
assert stored_payment.labels == ["test", "expired"]
+@pytest.mark.anyio
+@pytest.mark.parametrize("order", ["poll-first", "stream-first", "concurrent"])
+@pytest.mark.parametrize("fee_msat", [None, 0, 123, -123])
+async def test_incoming_poll_and_stream_notify_once(
+ app, settings: Settings, mocker: MockerFixture, order: str, fee_msat: int | None
+):
+ wallet = await _create_wallet()
+ fee_wallet = await _create_wallet()
+ settings.lnbits_service_fee_wallet = fee_wallet.id
+ settings.lnbits_service_fee = 1
+ checking_id = await _create_payment(wallet, fee=-42)
+ payment = await get_payment(checking_id)
+ payment.preimage = "existing-preimage"
+ await update_payment(payment)
+ queued = mocker.patch.object(task_manager.invoice_queue, "put_nowait")
+ direct_notification = mocker.patch(
+ "lnbits.core.services.payments.send_payment_notification_in_background"
+ )
+ ready = asyncio.Event()
+ checks = 0
+
+ async def check_status(_):
+ nonlocal checks
+ checks += 1
+ if order == "concurrent" and checks <= 2:
+ if checks == 2:
+ ready.set()
+ await asyncio.wait_for(ready.wait(), timeout=2)
+ return PaymentSuccessStatus(fee_msat=fee_msat)
+
+ async def paid_invoices():
+ yield checking_id
+ yield checking_id
+
+ mocker.patch(
+ "lnbits.core.services.payments.check_payment_status", side_effect=check_status
+ )
+ mocker.patch(
+ "lnbits.core.services.payments.get_funding_source",
+ return_value=SimpleNamespace(paid_invoices_stream=paid_invoices),
+ )
+ if order == "poll-first":
+ await update_pending_payment(payment.model_copy(deep=True))
+ await fundingsource_invoice_producer()
+ elif order == "stream-first":
+ await fundingsource_invoice_producer()
+ await update_pending_payment(payment.model_copy(deep=True))
+ else:
+ await asyncio.wait_for(
+ asyncio.gather(
+ update_pending_payment(payment.model_copy(deep=True)),
+ fundingsource_invoice_producer(),
+ ),
+ timeout=5,
+ )
+ # A stale polling result must not dispatch another notification either.
+ await update_pending_payment(payment)
+
+ stored = await get_payment(checking_id)
+ assert stored.success
+ assert stored.fee == (fee_msat or -42)
+ assert stored.preimage == "existing-preimage"
+ queued.assert_called_once_with(stored)
+ direct_notification.assert_not_called()
+ assert not await get_payments(wallet_id=fee_wallet.id)
+
+
+@pytest.mark.anyio
+async def test_incoming_poll_reuses_connection_and_dispatches_notification(
+ app, mocker: MockerFixture
+):
+ from lnbits.core.db import db
+ from lnbits.core.services.notifications import dispatch_payment_notification
+
+ wallet = await _create_wallet()
+ checking_id = await _create_payment(wallet)
+ payment = await get_payment(checking_id)
+ queued = mocker.patch.object(task_manager.invoice_queue, "put_nowait")
+ mocker.patch(
+ "lnbits.core.services.payments.check_payment_status",
+ return_value=PaymentSuccessStatus(preimage="backend-preimage"),
+ )
+ notify = mocker.patch(
+ "lnbits.core.services.notifications.send_payment_notification"
+ )
+
+ async with db.connect() as conn:
+ updated = await asyncio.wait_for(
+ update_pending_payment(payment, conn=conn), timeout=2
+ )
+ queued.assert_called_once_with(updated)
+ await dispatch_payment_notification(updated)
+ notify.assert_awaited_once()
+ assert notify.await_args
+ notified_wallet, notified_payment = notify.await_args.args
+ assert notified_wallet.balance_msat == payment.amount
+ assert notified_payment.success
+ assert notified_payment.preimage == "backend-preimage"
+
+
+@pytest.mark.anyio
+async def test_poll_does_not_expire_settled_invoice(app, mocker: MockerFixture):
+ wallet = await _create_wallet()
+ checking_id = await _create_payment(
+ wallet,
+ status=PaymentState.SUCCESS,
+ expiry=datetime.now(timezone.utc) - timedelta(seconds=1),
+ )
+ check_status = mocker.patch("lnbits.core.services.payments.check_payment_status")
+ queued = mocker.patch.object(task_manager.invoice_queue, "put_nowait")
+
+ updated = await update_pending_payment(await get_payment(checking_id))
+
+ assert updated.success
+ assert "expired" not in updated.labels
+ assert (await get_payment(checking_id)).success
+ check_status.assert_not_awaited()
+ queued.assert_not_called()
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("expired", [True, False])
+async def test_stale_poll_cannot_fail_a_settled_invoice(
+ app, mocker: MockerFixture, expired: bool
+):
+ wallet = await _create_wallet()
+ checking_id = await _create_payment(
+ wallet,
+ expiry=datetime.now(timezone.utc) - timedelta(seconds=1) if expired else None,
+ )
+ stale = await get_payment(checking_id)
+ queued = mocker.patch.object(task_manager.invoice_queue, "put_nowait")
+ check_status = mocker.patch(
+ "lnbits.core.services.payments.check_payment_status",
+ return_value=PaymentSuccessStatus(),
+ )
+ await update_invoice_from_paid_invoices_stream(checking_id)
+ check_status.return_value = PaymentFailedStatus()
+
+ updated = await update_pending_payment(stale)
+
+ assert updated.success
+ assert "expired" not in updated.labels
+ assert (await get_payment(checking_id)).success
+ assert await update_invoice_from_paid_invoices_stream(checking_id) == updated
+ queued.assert_called_once_with(updated)
+
+
@pytest.mark.anyio
async def test_check_pending_payments_skips_voidwallet_and_updates_recent_items(
mocker: MockerFixture,
### tests/unit/wallet-updates.test.cjs
@@ -0,0 +1,135 @@
+const assert = require('node:assert/strict')
+const {readFileSync} = require('node:fs')
+const {resolve} = require('node:path')
+const {test} = require('node:test')
+const vm = require('node:vm')
+
+function harness(getWallet) {
+ let component
+ const sockets = []
+ const timers = []
+ const reactions = []
+ const warnings = []
+ const wallet = {id: 'wallet', inkey: 'invoice-key', sat: 1}
+ const context = {
+ window: {app: {component: (_, value) => (component = value)}},
+ LNbits: {api: {getWallet}},
+ websocketUrl: 'wss://example.com/api/v1/ws',
+ WebSocket: class {
+ static OPEN = 1
+ readyState = 1
+ constructor(url) {
+ this.url = url
+ sockets.push(this)
+ }
+ },
+ setTimeout: callback => timers.push(callback),
+ clearTimeout() {},
+ console: {log() {}, warn: (...args) => warnings.push(args)},
+ eventReaction: amount => reactions.push(amount)
+ }
+ vm.runInNewContext(
+ readFileSync(
+ resolve(
+ __dirname,
+ '../../lnbits/static/js/components/lnbits-manage-wallet-list.js'
+ ),
+ 'utf8'
+ ),
+ context
+ )
+ const instance = {
+ ...component.data(),
+ maxWallets: 10,
+ g: {
+ user: {wallets: [wallet]},
+ wallet: {...wallet},
+ walletEventListeners: [],
+ updatePayments: false,
+ updatePaymentsHash: false
+ }
+ }
+ for (const [name, method] of Object.entries(component.methods)) {
+ instance[name] = method.bind(instance)
+ }
+ instance.paymentEvents()
+ return {instance, wallet, sockets, timers, reactions, warnings}
+}
+
+test('socket open and reconnect refresh balances and payments without a payment reaction', async () => {
+ let balance = 21000
+ const {instance, wallet, sockets, timers, reactions} = harness(
+ async wallet => {
+ assert.equal(wallet.inkey, 'invoice-key')
+ return {data: {balance}}
+ }
+ )
+ await sockets[0].onopen()
+ assert.equal(wallet.sat, 21)
+ assert.equal(instance.g.wallet.sat, 21)
+ assert.equal(instance.g.updatePayments, true)
+ assert.equal(instance.g.updatePaymentsHash, false)
+ assert.deepEqual(reactions, [])
+
+ sockets[0].onclose()
+ // A payment arrives while disconnected; only the HTTP balance knows about it.
+ balance = 42001
+ timers.at(-1)()
+ assert.equal(sockets.length, 2)
+ await sockets[1].onopen()
+ assert.equal(wallet.sat, 42)
+ assert.equal(instance.g.wallet.sat, 42)
+ assert.equal(instance.g.updatePayments, false)
+ assert.equal(instance.g.updatePaymentsHash, false)
+ assert.deepEqual(reactions, [])
+})
+
+test('refresh updates a background wallet without changing the active wallet', async () => {
+ const {instance, wallet, sockets} = harness(async () => ({
+ data: {balance: 0}
+ }))
+ instance.g.wallet = {id: 'other-wallet', sat: 100}
+ await sockets[0].onopen()
+ assert.equal(wallet.sat, 0)
+ assert.equal(instance.g.wallet.sat, 100)
+ assert.equal(instance.g.updatePayments, false)
+})
+
+test('a late HTTP snapshot cannot overwrite a live payment update', async () => {
+ let finish
+ const {instance, wallet, sockets, reactions} = harness(
+ () => new Promise(resolve => (finish = resolve))
+ )
+ const refreshing = sockets[0].onopen()
+ sockets[0].onmessage({
+ data: JSON.stringify({
+ wallet_balance: 42,
+ payment: {wallet_id: wallet.id, amount: 21000}
+ })
+ })
+ finish({data: {balance: 21000}})
+ await refreshing
+ assert.equal(wallet.sat, 42)
+ assert.equal(instance.g.wallet.sat, 42)
+ assert.equal(instance.g.updatePayments, true)
+ assert.equal(instance.g.updatePaymentsHash, true)
+ assert.deepEqual(reactions, [42000])
+})
+
+test('refresh failure is handled and the next connection retries', async () => {
+ let fail = true
+ const {instance, wallet, sockets, timers, warnings} = harness(async () => {
+ if (fail) throw new Error('offline')
+ return {data: {balance: 42000}}
+ })
+ await sockets[0].onopen()
+ assert.equal(wallet.sat, 1)
+ assert.equal(instance.g.updatePayments, false)
+ assert.equal(warnings.length, 1)
+ fail = false
+ sockets[0].onclose()
+ timers.at(-1)()
+ await sockets[1].onopen()
+ assert.equal(wallet.sat, 42)
+ assert.equal(instance.g.updatePayments, true)
+})Why this scored 45/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.