Skip to content

Commit 8e83b7a

Browse files
committed
Support receiving, validating, and claiming MPP keysend
f - modify for new config
1 parent 6501977 commit 8e83b7a

File tree

2 files changed

+114
-49
lines changed

2 files changed

+114
-49
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 55 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3468,9 +3468,13 @@ where
34683468
}
34693469

34703470
macro_rules! check_total_value {
3471-
($payment_data: expr, $payment_preimage: expr) => {{
3471+
($payment_data: expr, $payment_preimage: expr, $is_keysend: expr) => {{
34723472
let mut payment_claimable_generated = false;
3473-
let purpose = || {
3473+
let purpose = if $is_keysend {
3474+
events::PaymentPurpose::SpontaneousPayment(
3475+
$payment_preimage.expect("Should never call check_total_value with $is_keysend as true but no preimage")
3476+
)
3477+
} else {
34743478
events::PaymentPurpose::InvoicePayment {
34753479
payment_preimage: $payment_preimage,
34763480
payment_secret: $payment_data.payment_secret,
@@ -3486,7 +3490,7 @@ where
34863490
.or_insert_with(|| {
34873491
committed_to_claimable = true;
34883492
ClaimablePayment {
3489-
purpose: purpose(), htlcs: Vec::new(), onion_fields: None,
3493+
purpose: purpose.clone(), htlcs: Vec::new(), onion_fields: None,
34903494
}
34913495
});
34923496
if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
@@ -3497,7 +3501,7 @@ where
34973501
claimable_payment.onion_fields = Some(onion_fields);
34983502
}
34993503
let ref mut htlcs = &mut claimable_payment.htlcs;
3500-
if htlcs.len() == 1 {
3504+
if htlcs.len() == 1 && !$is_keysend {
35013505
if let OnionPayload::Spontaneous(_) = htlcs[0].onion_payload {
35023506
log_trace!(self.logger, "Failing new HTLC with payment_hash {} as we already had an existing keysend HTLC with the same payment hash", log_bytes!(payment_hash.0));
35033507
fail_htlc!(claimable_htlc, payment_hash);
@@ -3508,17 +3512,12 @@ where
35083512
for htlc in htlcs.iter() {
35093513
total_value += htlc.sender_intended_value;
35103514
earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
3511-
match &htlc.onion_payload {
3512-
OnionPayload::Invoice { .. } => {
3513-
if htlc.total_msat != $payment_data.total_msat {
3514-
log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
3515-
log_bytes!(payment_hash.0), $payment_data.total_msat, htlc.total_msat);
3516-
total_value = msgs::MAX_VALUE_MSAT;
3517-
}
3518-
if total_value >= msgs::MAX_VALUE_MSAT { break; }
3519-
},
3520-
_ => unreachable!(),
3515+
if htlc.total_msat != $payment_data.total_msat {
3516+
log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
3517+
log_bytes!(payment_hash.0), $payment_data.total_msat, htlc.total_msat);
3518+
total_value = msgs::MAX_VALUE_MSAT;
35213519
}
3520+
if total_value >= msgs::MAX_VALUE_MSAT { break; }
35223521
}
35233522
// The condition determining whether an MPP is complete must
35243523
// match exactly the condition used in `timer_tick_occurred`
@@ -3539,7 +3538,7 @@ where
35393538
new_events.push(events::Event::PaymentClaimable {
35403539
receiver_node_id: Some(receiver_node_id),
35413540
payment_hash,
3542-
purpose: purpose(),
3541+
purpose,
35433542
amount_msat,
35443543
via_channel_id: Some(prev_channel_id),
35453544
via_user_channel_id: Some(prev_user_channel_id),
@@ -3587,40 +3586,44 @@ where
35873586
fail_htlc!(claimable_htlc, payment_hash);
35883587
}
35893588
}
3590-
check_total_value!(payment_data, payment_preimage);
3589+
check_total_value!(payment_data, payment_preimage, false);
35913590
},
35923591
OnionPayload::Spontaneous(preimage) => {
3593-
let mut claimable_payments = self.claimable_payments.lock().unwrap();
3594-
if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
3595-
fail_htlc!(claimable_htlc, payment_hash);
3596-
}
3597-
match claimable_payments.claimable_payments.entry(payment_hash) {
3598-
hash_map::Entry::Vacant(e) => {
3599-
let amount_msat = claimable_htlc.value;
3600-
claimable_htlc.total_value_received = Some(amount_msat);
3601-
let claim_deadline = Some(claimable_htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER);
3602-
let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
3603-
e.insert(ClaimablePayment {
3604-
purpose: purpose.clone(),
3605-
onion_fields: Some(onion_fields.clone()),
3606-
htlcs: vec![claimable_htlc],
3607-
});
3608-
let prev_channel_id = prev_funding_outpoint.to_channel_id();
3609-
new_events.push(events::Event::PaymentClaimable {
3610-
receiver_node_id: Some(receiver_node_id),
3611-
payment_hash,
3612-
amount_msat,
3613-
purpose,
3614-
via_channel_id: Some(prev_channel_id),
3615-
via_user_channel_id: Some(prev_user_channel_id),
3616-
claim_deadline,
3617-
onion_fields: Some(onion_fields),
3618-
});
3619-
},
3620-
hash_map::Entry::Occupied(_) => {
3621-
log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} for a duplicative payment hash", log_bytes!(payment_hash.0));
3592+
if let Some(payment_data) = payment_data {
3593+
check_total_value!(payment_data, Some(preimage), true);
3594+
} else {
3595+
let mut claimable_payments = self.claimable_payments.lock().unwrap();
3596+
if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
36223597
fail_htlc!(claimable_htlc, payment_hash);
36233598
}
3599+
match claimable_payments.claimable_payments.entry(payment_hash) {
3600+
hash_map::Entry::Vacant(e) => {
3601+
let amount_msat = claimable_htlc.value;
3602+
claimable_htlc.total_value_received = Some(amount_msat);
3603+
let claim_deadline = Some(claimable_htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER);
3604+
let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
3605+
e.insert(ClaimablePayment {
3606+
purpose: purpose.clone(),
3607+
onion_fields: Some(onion_fields.clone()),
3608+
htlcs: vec![claimable_htlc],
3609+
});
3610+
let prev_channel_id = prev_funding_outpoint.to_channel_id();
3611+
new_events.push(events::Event::PaymentClaimable {
3612+
receiver_node_id: Some(receiver_node_id),
3613+
payment_hash,
3614+
amount_msat,
3615+
purpose,
3616+
via_channel_id: Some(prev_channel_id),
3617+
via_user_channel_id: Some(prev_user_channel_id),
3618+
claim_deadline,
3619+
onion_fields: Some(onion_fields),
3620+
});
3621+
},
3622+
hash_map::Entry::Occupied(_) => {
3623+
log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} for a duplicative payment hash", log_bytes!(payment_hash.0));
3624+
fail_htlc!(claimable_htlc, payment_hash);
3625+
}
3626+
}
36243627
}
36253628
}
36263629
}
@@ -3639,7 +3642,7 @@ where
36393642
log_bytes!(payment_hash.0), payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
36403643
fail_htlc!(claimable_htlc, payment_hash);
36413644
} else {
3642-
let payment_claimable_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage);
3645+
let payment_claimable_generated = check_total_value!(payment_data, inbound_payment.get().payment_preimage, false);
36433646
if payment_claimable_generated {
36443647
inbound_payment.remove_entry();
36453648
}
@@ -4114,12 +4117,16 @@ where
41144117
/// event matches your expectation. If you fail to do so and call this method, you may provide
41154118
/// the sender "proof-of-payment" when they did not fulfill the full expected payment.
41164119
///
4120+
/// To accept multi-part keysend payments you must set [`UserConfig::accept_mpp_keysend`] to
4121+
/// true.
4122+
///
41174123
/// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
41184124
/// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
41194125
/// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
41204126
/// [`process_pending_events`]: EventsProvider::process_pending_events
41214127
/// [`create_inbound_payment`]: Self::create_inbound_payment
41224128
/// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
4129+
/// [`UserConfig::accept_mpp_keysend`]: crate::util::config::UserConfig::accept_mpp_keysend
41234130
pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
41244131
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
41254132

@@ -4180,9 +4187,9 @@ where
41804187
expected_amt_msat = htlc.total_value_received;
41814188

41824189
if let OnionPayload::Spontaneous(_) = &htlc.onion_payload {
4183-
// We don't currently support MPP for spontaneous payments, so just check
4190+
// If the user chooses not to support MPP for spontaneous payments, just check
41844191
// that there's one payment here and move on.
4185-
if sources.len() != 1 {
4192+
if !self.default_configuration.accept_mpp_keysend && sources.len() != 1 {
41864193
log_error!(self.logger, "Somehow ended up with an MPP spontaneous payment - this should not be reachable!");
41874194
debug_assert!(false);
41884195
valid_mpp = false;

lightning/src/ln/functional_tests.rs

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use crate::ln::{chan_utils, onion_utils};
2727
use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
2828
use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
2929
use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30-
use crate::ln::features::{ChannelFeatures, NodeFeatures};
30+
use crate::ln::features::{ChannelFeatures, NodeFeatures, InvoiceFeatures};
3131
use crate::ln::msgs;
3232
use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
3333
use crate::util::enforcing_trait_impls::EnforcingSigner;
@@ -8215,6 +8215,64 @@ fn test_simple_mpp() {
82158215
claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
82168216
}
82178217

8218+
fn do_test_mpp_keysend(accept_mpp_keysend: bool) {
8219+
let mut mpp_keysend_config = test_default_channel_config();
8220+
mpp_keysend_config.accept_mpp_keysend = accept_mpp_keysend;
8221+
let chanmon_cfgs = create_chanmon_cfgs(4);
8222+
let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8223+
let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
8224+
let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8225+
8226+
create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8227+
create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8228+
create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8229+
create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8230+
let network_graph = nodes[0].network_graph.clone();
8231+
8232+
let payer_pubkey = nodes[0].node.get_our_node_id();
8233+
let payee_pubkey = nodes[3].node.get_our_node_id();
8234+
let recv_value = 15_000_000;
8235+
let mut invoice_features = InvoiceFeatures::for_keysend();
8236+
invoice_features.set_basic_mpp_optional();
8237+
let route_params = RouteParameters {
8238+
payment_params: PaymentParameters::from_node_id(payee_pubkey, 40).with_features(invoice_features),
8239+
// Approxiamating the amount to make the router use MPP is not reliable in
8240+
// case those thresholds change, but helpful to test where the router may
8241+
// block mpp keysend
8242+
final_value_msat: recv_value,
8243+
};
8244+
let scorer = test_utils::TestScorer::new();
8245+
let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
8246+
let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
8247+
8248+
let test_preimage = PaymentPreimage([42; 32]);
8249+
let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
8250+
RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
8251+
check_added_monitors!(nodes[0], 2);
8252+
8253+
let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8254+
let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8255+
assert_eq!(events.len(), 2);
8256+
for (path_idx, expected_path) in expected_route.iter().enumerate() {
8257+
let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8258+
let expect_payment = path_idx == expected_route.len() - 1;
8259+
pass_along_path(&nodes[0], *expected_path, recv_value, payment_hash.clone(), None, ev, expect_payment, Some(test_preimage));
8260+
}
8261+
8262+
claim_payment_along_route(&nodes[0], expected_route, false, test_preimage);
8263+
}
8264+
8265+
#[test]
8266+
fn test_mpp_keysend() {
8267+
do_test_mpp_keysend(true);
8268+
}
8269+
8270+
#[test]
8271+
#[should_panic]
8272+
fn test_mpp_keysend_fail() {
8273+
do_test_mpp_keysend(false);
8274+
}
8275+
82188276
#[test]
82198277
fn test_preimage_storage() {
82208278
// Simple test of payment preimage storage allowing no client-side storage to claim payments

0 commit comments

Comments
 (0)