diff --git a/doc/lightningd-config.5.md b/doc/lightningd-config.5.md index 42b4fba07974..ba673f9cc94c 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/lightningd/pay.c b/lightningd/pay.c index dc7e66a945aa..819b2f4666cd 100644 --- a/lightningd/pay.c +++ b/lightningd/pay.c @@ -917,6 +917,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; @@ -965,15 +967,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! */ @@ -1053,12 +1054,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/plugins/xpay/xpay.c b/plugins/xpay/xpay.c index 99d82665c1e7..8f6701b0e4f5 100644 --- a/plugins/xpay/xpay.c +++ b/plugins/xpay/xpay.c @@ -445,8 +445,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) { @@ -467,7 +466,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); @@ -485,8 +489,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); @@ -3996,7 +4003,7 @@ int main(int argc, char *argv[]) NULL, &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_dynamic("xpay-failing-node-tolerance", "int", "How many times a node can give us a weird error before we disable it.", diff --git a/tests/test_pay.py b/tests/test_pay.py index f6160bf0fe24..b9902ee10d6b 100644 --- a/tests/test_pay.py +++ b/tests/test_pay.py @@ -3404,6 +3404,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) diff --git a/tests/test_xpay.py b/tests/test_xpay.py index 0ce4feacca84..cf7d8eca5789 100644 --- a/tests/test_xpay.py +++ b/tests/test_xpay.py @@ -753,13 +753,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) @@ -771,17 +785,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: