From 986371dad7a8b863943c34d067a2b8ecc2108ab8 Mon Sep 17 00:00:00 2001 From: cdecker Date: Tue, 10 Nov 2026 10:01:26 +0000 Subject: [PATCH 1/2] lightningd: aggregate payment status before refusing a retry in check_progress. The "another payment group is still in progress" check fired as soon as it saw a PENDING payment row of a different group. But payments_by_hash() returns rows in HTLC-creation order, so a straggler part created *before* a later, successful part would shadow that success: retrying an already-paid payment_hash could get "still in progress, cannot retry" instead of the "already succeeded" answer, depending purely on which part we created first. Since a success is final (we return the stored preimage without sending an HTLC, or refuse with "Already succeeded other parts"), the group check is moot once anything completed: in every one of those cases no HTLC is sent, so HTLCs from the other group cannot mix with ours and overpay. Instead, collect have_complete and pending_other_group while scanning, and only report PAY_IN_PROGRESS if nothing has succeeded. Changelog-Changed: pay: retrying a payment_hash where a part already succeeded now reports "Already succeeded" even if other parts are still pending. Signed-off-by: cdecker --- lightningd/pay.c | 32 +++++++++---- tests/test_pay.py | 114 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+), 9 deletions(-) diff --git a/lightningd/pay.c b/lightningd/pay.c index 068941f8954b..01a9349c078b 100644 --- a/lightningd/pay.c +++ b/lightningd/pay.c @@ -912,6 +912,8 @@ static struct command_result *check_progress(struct lightningd *ld, const struct wallet_payment **succeeded_payment) { bool have_complete = false; + bool pending_other_group = false; + u64 pending_other_groupid = 0; struct amount_msat msat_already_pending = AMOUNT_MSAT(0); *succeeded_payment = NULL; @@ -960,15 +962,14 @@ static struct command_result *check_progress(struct lightningd *ld, case PAYMENT_PENDING: /* At most one payment group can be in-flight at any - * time. */ + * time. However, we cannot fail yet: a later row + * could show this hash already succeeded (we scan in + * HTLC-creation order!), and a success is final: we + * will not send an HTLC in any case (see below). */ if (payment->groupid != group) { - tal_free(stmt); - return command_fail( - cmd, PAY_IN_PROGRESS, - "Payment with groupid=%" PRIu64 - " still in progress, cannot retry before " - "that completes.", - payment->groupid); + pending_other_group = true; + pending_other_groupid = payment->groupid; + break; } /* Can't mix non-parallel and parallel payments! */ @@ -1048,12 +1049,25 @@ static struct command_result *check_progress(struct lightningd *ld, } } - /* If any part has succeeded, you can't start a new one! */ + /* If any part has succeeded, you can't start a new one! This takes + * precedence over a pending payment from another group: whatever we + * return here, no HTLC is sent, so stragglers from that group cannot + * combine with ours and overpay. */ if (have_complete) { return command_fail(cmd, PAY_RHASH_ALREADY_USED, "Already succeeded other parts"); } + /* Nothing has succeeded yet: we must not mix HTLCs from a different + * (still-pending) group with ours. */ + if (pending_other_group) { + return command_fail(cmd, PAY_IN_PROGRESS, + "Payment with groupid=%" PRIu64 + " still in progress, cannot retry before " + "that completes.", + pending_other_groupid); + } + /* BOLT #4: * * - MUST NOT send another HTLC if the total `amt_to_forward` of the HTLC diff --git a/tests/test_pay.py b/tests/test_pay.py index ee62142e685e..deadde556a67 100644 --- a/tests/test_pay.py +++ b/tests/test_pay.py @@ -3347,6 +3347,120 @@ def on_htlc_accepted(htlc, onion, plugin, **kwargs): groupid=1) +def test_retry_after_success_pending_straggler(node_factory, bitcoind): + """A success is final: retrying a payment_hash which already + succeeded must not be blocked by a straggling HTLC from the original + attempt, because we will not send an HTLC in any case. + + We make the straggler (partid 1) the first row in the wallet, so the + check must aggregate the payment rows before deciding: the pending + straggler may not shadow the later success. + """ + l1 = node_factory.get_node() + # l2 never acknowledges: part 1 is stuck pending forever (but in db). + l2 = node_factory.get_node(options={'dev-disable-commit-after': 0}) + l3, l4 = node_factory.get_nodes(2) + + l1.rpc.connect(l2.info['id'], 'localhost', l2.port) + l1.fundchannel(l2, 100000) + l1.rpc.connect(l3.info['id'], 'localhost', l3.port) + l1.fundchannel(l3, 100000) + l2.rpc.connect(l4.info['id'], 'localhost', l4.port) + scid24, _ = l2.fundchannel(l4, 100000) + l3.rpc.connect(l4.info['id'], 'localhost', l4.port) + scid34, _ = l3.fundchannel(l4, 100000) + mine_funding_to_announce(bitcoind, [l1, l2, l3, l4]) + + # Wait until l1 knows about all channels. + wait_for(lambda: len(l1.rpc.listchannels()['channels']) == 8) + + inv = l4.rpc.invoice(1000, 'inv', 'inv', preimage='00' * 32) + paysecret = l4.rpc.decode(inv['bolt11'])['payment_secret'] + + # Separate routes for each part: r124 delivers 999 of the 1000, + # r134 delivers the whole 1000 (so it succeeds on its own). + l1.rpc.askrene_create_layer(layer='excl_l2l4') + l1.rpc.askrene_update_channel(layer='excl_l2l4', short_channel_id_dir=scid24 + '/0', enabled=False) + l1.rpc.askrene_update_channel(layer='excl_l2l4', short_channel_id_dir=scid24 + '/1', enabled=False) + r134 = only_one(l1.rpc.getroutes(l1.info['id'], l4.info['id'], 1000, layers=['excl_l2l4', 'auto.localchans', 'auto.sourcefree'], maxfee_msat=10000000, final_cltv=9, maxparts=1)['routes'])['path'] + l1.rpc.askrene_remove_layer(layer='excl_l2l4') + + l1.rpc.askrene_create_layer(layer='excl_l3l4') + l1.rpc.askrene_update_channel(layer='excl_l3l4', short_channel_id_dir=scid34 + '/0', enabled=False) + l1.rpc.askrene_update_channel(layer='excl_l3l4', short_channel_id_dir=scid34 + '/1', enabled=False) + r124 = only_one(l1.rpc.getroutes(l1.info['id'], l4.info['id'], 999, layers=['excl_l3l4', 'auto.localchans', 'auto.sourcefree'], maxfee_msat=10000000, final_cltv=9, maxparts=1)['routes'])['path'] + l1.rpc.askrene_remove_layer(layer='excl_l3l4') + + # Part 1 goes via l2 and is stuck pending, but in the wallet. + l1.rpc.sendpay( + route=r124, + payment_hash=inv['payment_hash'], + amount_msat=1000, + bolt11=inv['bolt11'], + payment_secret=paysecret, + partid=1, + groupid=1, + ) + l1.daemon.wait_for_log('peer_out WIRE_UPDATE_ADD_HTLC') + + # Part 2 goes via l3, delivering the whole amount: invoice paid. + l1.rpc.sendpay( + route=r134, + payment_hash=inv['payment_hash'], + amount_msat=1000, + bolt11=inv['bolt11'], + payment_secret=paysecret, + partid=2, + groupid=1, + ) + res = l1.rpc.waitsendpay(payment_hash=inv['payment_hash'], partid=2, + groupid=1, timeout=TIMEOUT) + assert res['status'] == 'complete' + + # The straggler is still pending when we retry. + pays = l1.rpc.listsendpays(payment_hash=inv['payment_hash'])['payments'] + assert len(pays) == 2 + assert sorted([p['status'] for p in pays]) == ['complete', 'pending'] + + # Retrying partid 2 with a new group succeeds immediately: we know + # the preimage, so no HTLC is sent. It must *not* be stopped by the + # (earlier-created, so scanned first!) pending straggler. + pay = l1.rpc.sendpay( + route=r134, + payment_hash=inv['payment_hash'], + amount_msat=1000, + bolt11=inv['bolt11'], + payment_secret=paysecret, + partid=2, + groupid=2, + ) + assert pay['status'] == 'complete' + assert pay['payment_preimage'] == '00' * 32 + + # Retrying with the stuck part's partid is refused with "Already + # succeeded", *not* "still in progress": a success is final. + with pytest.raises(RpcError, match=r'Already succeeded'): + l1.rpc.sendpay( + route=r134, + payment_hash=inv['payment_hash'], + amount_msat=1000, + bolt11=inv['bolt11'], + payment_secret=paysecret, + partid=1, + groupid=2, + ) + + # In no case did we send another HTLC for this hash. + assert len(l1.rpc.listsendpays(payment_hash=inv['payment_hash'])['payments']) == 2 + + # Let the straggler through: it fails, since the invoice is paid. + l2.rpc.dev_reenable_commit(l4.info['id']) + l2.rpc.dev_reenable_commit(l1.info['id']) + with pytest.raises(RpcError, match=r'WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS'): + l1.rpc.waitsendpay(payment_hash=inv['payment_hash'], partid=1, + groupid=1, timeout=TIMEOUT) + + def test_partial_payment_timeout(node_factory, bitcoind): l1, l2 = node_factory.line_graph(2) From 0fe8f42c63c4d61f415c7875682f5792a4dcfca2 Mon Sep 17 00:00:00 2001 From: cdecker Date: Tue, 10 Nov 2026 10:16:47 +0000 Subject: [PATCH 2/2] xpay: return success immediately, even in slow mode. xpay-slow-mode was added so that a caller who might retry a *failed* payment (possibly from another node!) does not do so while our straggler HTLCs could still be collected alongside theirs, overpaying the invoice. For success this concern does not apply: once we hold the preimage, the payment is final. Any future attempt to pay this payment_hash is answered by lightningd out of the wallet without sending an HTLC (and the previous commit guarantees a pending straggler can no longer shadow that answer), so it can never overpay, no matter when our stragglers resolve. Thus slow mode now only waits for all parts before returning failure; a successful xpay returns as soon as a part succeeds, reporting in-flight parts optimistically as the default mode already does. Changelog-Changed: xpay: `xpay-slow-mode` now only waits until all parts have completed before returning failure: success is always returned immediately. Signed-off-by: cdecker --- doc/lightningd-config.5.md | 2 +- plugins/xpay/xpay.c | 19 +++++++++++++------ tests/test_xpay.py | 39 ++++++++++++++++++++------------------ 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/doc/lightningd-config.5.md b/doc/lightningd-config.5.md index de10ab6d8b29..7340187a1621 100644 --- a/doc/lightningd-config.5.md +++ b/doc/lightningd-config.5.md @@ -566,7 +566,7 @@ command, so they invoices can also be paid onchain. * **xpay-slow-mode**=*BOOL* [plugin `xpay`, *dynamic*] - Setting this makes `xpay` wait until all parts have failed/succeeded before returning. Usually this is unnecessary, as xpay will return on the first success (we have the preimage, if they don't take all the parts that's their problem) or failure (the destination could succeed another part, but it would mean it was only partially paid). The default is `false`. + Setting this makes `xpay` wait until all parts have failed or succeeded before returning a failure. Usually this is unnecessary, as xpay will return on the first failure (the destination could succeed another part, but it would mean it was only partially paid). Success is always returned as soon as we have the preimage: at that point any future attempt to pay this invoice will succeed immediately without sending any HTLC, so there is no possibility of overpay. The default is `false`. * **xpay-user-layer**=*name* [plugin `xpay`] diff --git a/plugins/xpay/xpay.c b/plugins/xpay/xpay.c index a7ba821ad407..cb8e67922fc0 100644 --- a/plugins/xpay/xpay.c +++ b/plugins/xpay/xpay.c @@ -431,8 +431,7 @@ static size_t count_current_attempts(const struct payment *payment) return result; } -/* We total up all attempts which succeeded in the past (if we're not - * in slow mode, that's only the one which just succeeded), and then we +/* We total up all attempts which succeeded in the past, and then we * assume any others currently-in-flight will also succeed. */ static struct amount_msat total_sent(const struct payment *payment) { @@ -453,7 +452,12 @@ static struct amount_msat total_sent(const struct payment *payment) return total; } -/* Should we finish command now? */ +/* Should we finish the (failing) command now? Success never waits: + * once we have the preimage, a success is final: lightningd will + * resolve any future attempt for this hash without sending an HTLC + * (see check_progress), so slow mode only ever matters for failure, + * where the caller might retry (possibly elsewhere!) while our + * stragglers could still be collected alongside theirs. */ static bool should_finish_command(const struct payment *payment) { const struct xpay *xpay = xpay_of(payment->plugin); @@ -471,8 +475,11 @@ static void payment_succeeded(struct payment *payment, { struct json_stream *js; - /* Only succeed once */ - if (payment->cmd && should_finish_command(payment)) { + /* Only succeed once. We return as soon as we have the preimage, + * even in slow mode: a success is final, so stragglers cannot + * combine with a future attempt (lightningd hands that attempt + * the stored preimage without sending any HTLC). */ + if (payment->cmd) { js = jsonrpc_stream_success(payment->cmd); json_add_preimage(js, "payment_preimage", preimage); json_add_amount_msat(js, "amount_msat", payment->amount); @@ -3812,7 +3819,7 @@ int main(int argc, char *argv[]) "Make xpay take over pay commands it can handle.", bool_option, bool_jsonfmt, &xpay->take_over_pay), plugin_option_dynamic("xpay-slow-mode", "bool", - "Wait until all parts have completed before returning success or failure", + "Wait until all parts have completed before returning failure (success is always returned immediately)", bool_option, bool_jsonfmt, &xpay->slow_mode), plugin_option_multi("xpay-user-layer", "string", "Add a layer that will be used for every payment", diff --git a/tests/test_xpay.py b/tests/test_xpay.py index e8584a93b0df..9e4cf8d256fa 100644 --- a/tests/test_xpay.py +++ b/tests/test_xpay.py @@ -752,13 +752,27 @@ def test_fail_after_success(node_factory, bitcoind, executor, slow_mode): l4.daemon.wait_for_log('dev_disconnect: -WIRE_UPDATE_FULFILL_HTLC') l4.stop() - # Normally, we return as soon as first part succeeds. - if slow_mode is False: - assert fut.result(TIMEOUT) == {'payment_preimage': '00' * 32, - 'amount_msat': 800000000, - 'amount_sent_msat': 800016004, - 'failed_parts': 0, - 'successful_parts': 2} + # We return as soon as the first part succeeds: a success is final, + # even in slow mode (which only waits for all parts before returning + # *failure*). + assert fut.result(TIMEOUT) == {'payment_preimage': '00' * 32, + 'amount_msat': 800000000, + 'amount_sent_msat': 800016004, + 'failed_parts': 0, + 'successful_parts': 2} + + # Retrying while the stuck part is still pending can never end up + # sending an HTLC for this hash again: we may succeed with the known + # preimage, be told it's already paid, or even fail to route at all + # (the first attempt's reservations are still held), but it must + # *not* be reported as "still in progress". + num_htlcs = len(l1.rpc.listsendpays(payment_hash=l1.rpc.decode(inv)['payment_hash'])['payments']) + try: + res = l1.rpc.xpay(inv) + assert res['payment_preimage'] == '00' * 32 + except RpcError as e: + assert 'still in progress' not in e.error['message'] + assert len(l1.rpc.listsendpays(payment_hash=l1.rpc.decode(inv)['payment_hash'])['payments']) == num_htlcs # Time it out, l2 will collect it. bitcoind.generate_block(13) @@ -770,17 +784,6 @@ def test_fail_after_success(node_factory, bitcoind, executor, slow_mode): line = l1.daemon.is_in_log(r"UNUSUAL.*Destination accepted partial payment, failed a part") assert re.search(r'but accepted only .* of 800000000msat\. Winning\?!', line) - if slow_mode is True: - # Now it succeeds, but notes that it only sent one part! - res = fut.result(TIMEOUT) - # Some variation due to floating point. - assert res['amount_sent_msat'] < 800000000 - assert res == {'payment_preimage': '00' * 32, - 'amount_msat': 800000000, - 'amount_sent_msat': res['amount_sent_msat'], - 'failed_parts': 1, - 'successful_parts': 1} - def test_xpay_twohop_bug(node_factory, bitcoind): """From https://github.com/ElementsProject/lightning/issues/8119: