Skip to content

Commit cbdc1df

Browse files
committed
Hold time reporting
Adds hold time reporting for the final and intermediate nodes.
1 parent cfff997 commit cbdc1df

File tree

6 files changed

+130
-23
lines changed

6 files changed

+130
-23
lines changed

lightning/src/ln/blinded_payment_tests.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2333,6 +2333,8 @@ fn test_trampoline_unblinded_receive() {
23332333
None,
23342334
).unwrap();
23352335

2336+
// Use a different session key to construct the replacement onion packet. Note that the sender isn't aware of
2337+
// this and won't be able to decode the fulfill hold times.
23362338
let outer_session_priv = secret_from_hex("e52c20461ed7acd46c4e7b591a37610519179482887bd73bf3b94617f8f03677");
23372339

23382340
let (outer_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], outer_total_msat, &recipient_onion_fields, outer_starting_htlc_offset, &None, None, Some(trampoline_packet)).unwrap();

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2890,7 +2890,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
28902890
as_raa = Some(get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, node_b_id));
28912891
}
28922892

2893-
let fulfill_msg = msgs::UpdateFulfillHTLC {
2893+
let mut fulfill_msg = msgs::UpdateFulfillHTLC {
28942894
channel_id: chan_id_2,
28952895
htlc_id: 0,
28962896
payment_preimage,
@@ -2904,6 +2904,8 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
29042904
);
29052905
check_added_monitors!(nodes[2], 1);
29062906
get_htlc_update_msgs!(nodes[2], node_b_id);
2907+
// Note that we don't populate fulfill_msg.attribution_data here, which will lead to hold times being
2908+
// unavailable.
29072909
} else {
29082910
nodes[2].node.claim_funds(payment_preimage);
29092911
check_added_monitors!(nodes[2], 1);
@@ -2919,6 +2921,7 @@ fn do_test_reconnect_dup_htlc_claims(htlc_status: HTLCStatusAtDupClaim, second_f
29192921
fulfill_msg.payment_preimage,
29202922
cs_updates.update_fulfill_htlcs[0].payment_preimage
29212923
);
2924+
fulfill_msg.attribution_data = cs_updates.update_fulfill_htlcs[0].attribution_data.clone();
29222925
}
29232926
nodes[1].node.handle_update_fulfill_htlc(node_c_id, &fulfill_msg);
29242927
expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, false);

lightning/src/ln/channel.rs

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6166,7 +6166,7 @@ where
61666166
assert!(!self.context.channel_state.can_generate_new_commitment());
61676167
let mon_update_id = self.context.latest_monitor_update_id; // Forget the ChannelMonitor update
61686168
let fulfill_resp =
6169-
self.get_update_fulfill_htlc(htlc_id_arg, payment_preimage_arg, None, logger);
6169+
self.get_update_fulfill_htlc(htlc_id_arg, payment_preimage_arg, None, None, logger);
61706170
self.context.latest_monitor_update_id = mon_update_id;
61716171
if let UpdateFulfillFetch::NewClaim { update_blocked, .. } = fulfill_resp {
61726172
assert!(update_blocked); // The HTLC must have ended up in the holding cell.
@@ -6175,7 +6175,8 @@ where
61756175

61766176
fn get_update_fulfill_htlc<L: Deref>(
61776177
&mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage,
6178-
payment_info: Option<PaymentClaimDetails>, logger: &L,
6178+
payment_info: Option<PaymentClaimDetails>, attribution_data: Option<AttributionData>,
6179+
logger: &L,
61796180
) -> UpdateFulfillFetch
61806181
where
61816182
L::Target: Logger,
@@ -6290,7 +6291,7 @@ where
62906291
self.context.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::ClaimHTLC {
62916292
payment_preimage: payment_preimage_arg,
62926293
htlc_id: htlc_id_arg,
6293-
attribution_data: None,
6294+
attribution_data,
62946295
});
62956296
return UpdateFulfillFetch::NewClaim {
62966297
monitor_update,
@@ -6321,7 +6322,7 @@ where
63216322
);
63226323
htlc.state = InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill(
63236324
payment_preimage_arg.clone(),
6324-
None,
6325+
attribution_data,
63256326
));
63266327
}
63276328

@@ -6330,13 +6331,20 @@ where
63306331

63316332
pub fn get_update_fulfill_htlc_and_commit<L: Deref>(
63326333
&mut self, htlc_id: u64, payment_preimage: PaymentPreimage,
6333-
payment_info: Option<PaymentClaimDetails>, logger: &L,
6334+
payment_info: Option<PaymentClaimDetails>, attribution_data: Option<AttributionData>,
6335+
logger: &L,
63346336
) -> UpdateFulfillCommitFetch
63356337
where
63366338
L::Target: Logger,
63376339
{
63386340
let release_cs_monitor = self.context.blocked_monitor_updates.is_empty();
6339-
match self.get_update_fulfill_htlc(htlc_id, payment_preimage, payment_info, logger) {
6341+
match self.get_update_fulfill_htlc(
6342+
htlc_id,
6343+
payment_preimage,
6344+
payment_info,
6345+
attribution_data,
6346+
logger,
6347+
) {
63406348
UpdateFulfillFetch::NewClaim {
63416349
mut monitor_update,
63426350
htlc_value_msat,
@@ -6668,7 +6676,7 @@ where
66686676

66696677
pub fn update_fulfill_htlc(
66706678
&mut self, msg: &msgs::UpdateFulfillHTLC,
6671-
) -> Result<(HTLCSource, u64, Option<u64>), ChannelError> {
6679+
) -> Result<(HTLCSource, u64, Option<u64>, Option<Duration>), ChannelError> {
66726680
if self.context.channel_state.is_remote_stfu_sent()
66736681
|| self.context.channel_state.is_quiescent()
66746682
{
@@ -6688,8 +6696,9 @@ where
66886696
}
66896697

66906698
let outcome = OutboundHTLCOutcome::Success(msg.payment_preimage);
6691-
self.mark_outbound_htlc_removed(msg.htlc_id, outcome)
6692-
.map(|htlc| (htlc.source.clone(), htlc.amount_msat, htlc.skimmed_fee_msat))
6699+
self.mark_outbound_htlc_removed(msg.htlc_id, outcome).map(|htlc| {
6700+
(htlc.source.clone(), htlc.amount_msat, htlc.skimmed_fee_msat, htlc.send_timestamp)
6701+
})
66936702
}
66946703

66956704
#[rustfmt::skip]
@@ -7249,7 +7258,11 @@ where
72497258
}
72507259
None
72517260
},
7252-
&HTLCUpdateAwaitingACK::ClaimHTLC { ref payment_preimage, htlc_id, .. } => {
7261+
&HTLCUpdateAwaitingACK::ClaimHTLC {
7262+
ref payment_preimage,
7263+
htlc_id,
7264+
ref attribution_data,
7265+
} => {
72537266
// If an HTLC claim was previously added to the holding cell (via
72547267
// `get_update_fulfill_htlc`, then generating the claim message itself must
72557268
// not fail - any in between attempts to claim the HTLC will have resulted
@@ -7260,8 +7273,13 @@ where
72607273
// `ChannelMonitorUpdate` to the user, making this one redundant, however
72617274
// there's no harm in including the extra `ChannelMonitorUpdateStep` here.
72627275
// We do not bother to track and include `payment_info` here, however.
7263-
let fulfill =
7264-
self.get_update_fulfill_htlc(htlc_id, *payment_preimage, None, logger);
7276+
let fulfill = self.get_update_fulfill_htlc(
7277+
htlc_id,
7278+
*payment_preimage,
7279+
None,
7280+
attribution_data.clone(),
7281+
logger,
7282+
);
72657283
let mut additional_monitor_update =
72667284
if let UpdateFulfillFetch::NewClaim { monitor_update, .. } = fulfill {
72677285
monitor_update
@@ -13565,7 +13583,7 @@ where
1356513583
}
1356613584
}
1356713585

13568-
fn duration_since_epoch() -> Option<Duration> {
13586+
pub(crate) fn duration_since_epoch() -> Option<Duration> {
1356913587
#[cfg(not(feature = "std"))]
1357013588
let now = None;
1357113589

@@ -13581,7 +13599,7 @@ fn duration_since_epoch() -> Option<Duration> {
1358113599

1358213600
/// Returns the time expressed in hold time units (1 unit = 100 ms) that has elapsed between send_timestamp and now. If
1358313601
/// any of the arguments are `None`, returns `None`.
13584-
fn hold_time(send_timestamp: Option<Duration>, now: Option<Duration>) -> Option<u32> {
13602+
pub(crate) fn hold_time(send_timestamp: Option<Duration>, now: Option<Duration>) -> Option<u32> {
1358513603
send_timestamp.and_then(|t| {
1358613604
now.map(|now| {
1358713605
let elapsed = now.saturating_sub(t).as_millis() / HOLD_TIME_UNIT_MILLIS;

lightning/src/ln/channelmanager.rs

Lines changed: 66 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,12 @@ use crate::events::{
5858
use crate::events::{FundingInfo, PaidBolt12Invoice};
5959
// Since this struct is returned in `list_channels` methods, expose it here in case users want to
6060
// construct one themselves.
61-
use crate::ln::channel::PendingV2Channel;
6261
use crate::ln::channel::{
63-
self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, InboundV1Channel,
62+
self, hold_time, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, InboundV1Channel,
6463
OutboundV1Channel, ReconnectionMsg, ShutdownResult, UpdateFulfillCommitFetch,
6564
WithChannelContext,
6665
};
66+
use crate::ln::channel::{duration_since_epoch, PendingV2Channel};
6767
use crate::ln::channel_state::ChannelDetails;
6868
use crate::ln::inbound_payment;
6969
use crate::ln::msgs;
@@ -77,6 +77,7 @@ use crate::ln::onion_payment::{
7777
NextPacketDetails,
7878
};
7979
use crate::ln::onion_utils::{self};
80+
use crate::ln::onion_utils::{process_fulfill_attribution_data, AttributionData};
8081
use crate::ln::onion_utils::{HTLCFailReason, LocalHTLCFailureReason};
8182
use crate::ln::our_peer_storage::EncryptedOurPeerStorage;
8283
#[cfg(test)]
@@ -7639,10 +7640,30 @@ where
76397640
pending_claim: PendingMPPClaimPointer(Arc::clone(pending_claim)),
76407641
}
76417642
});
7643+
7644+
// Create new attribution data as the final hop. Always report a zero hold time, because reporting a
7645+
// non-zero value will not make a difference in the penalty that may be applied by the sender. If there
7646+
// is a phantom hop, we need to double-process.
7647+
let attribution_data =
7648+
if let Some(phantom_secret) = htlc.prev_hop.phantom_shared_secret {
7649+
let attribution_data =
7650+
process_fulfill_attribution_data(None, &phantom_secret, 0);
7651+
Some(attribution_data)
7652+
} else {
7653+
None
7654+
};
7655+
7656+
let attribution_data = process_fulfill_attribution_data(
7657+
attribution_data.as_ref(),
7658+
&htlc.prev_hop.incoming_packet_shared_secret,
7659+
0,
7660+
);
7661+
76427662
self.claim_funds_from_hop(
76437663
htlc.prev_hop,
76447664
payment_preimage,
76457665
payment_info.clone(),
7666+
Some(attribution_data),
76467667
|_, definitely_duplicate| {
76477668
debug_assert!(
76487669
!definitely_duplicate,
@@ -7687,7 +7708,8 @@ where
76877708
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
76887709
>(
76897710
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
7690-
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
7711+
payment_info: Option<PaymentClaimDetails>, attribution_data: Option<AttributionData>,
7712+
completion_action: ComplFunc,
76917713
) {
76927714
let counterparty_node_id = prev_hop.counterparty_node_id.or_else(|| {
76937715
let short_to_chan_info = self.short_to_chan_info.read().unwrap();
@@ -7700,7 +7722,13 @@ where
77007722
channel_id: prev_hop.channel_id,
77017723
htlc_id: prev_hop.htlc_id,
77027724
};
7703-
self.claim_mpp_part(htlc_source, payment_preimage, payment_info, completion_action)
7725+
self.claim_mpp_part(
7726+
htlc_source,
7727+
payment_preimage,
7728+
payment_info,
7729+
attribution_data,
7730+
completion_action,
7731+
)
77047732
}
77057733

77067734
fn claim_mpp_part<
@@ -7710,7 +7738,8 @@ where
77107738
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
77117739
>(
77127740
&self, prev_hop: HTLCClaimSource, payment_preimage: PaymentPreimage,
7713-
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
7741+
payment_info: Option<PaymentClaimDetails>, attribution_data: Option<AttributionData>,
7742+
completion_action: ComplFunc,
77147743
) {
77157744
//TODO: Delay the claimed_funds relaying just like we do outbound relay!
77167745

@@ -7751,6 +7780,7 @@ where
77517780
prev_hop.htlc_id,
77527781
payment_preimage,
77537782
payment_info,
7783+
attribution_data,
77547784
&&logger,
77557785
);
77567786

@@ -7959,7 +7989,8 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
79597989
forwarded_htlc_value_msat: Option<u64>, skimmed_fee_msat: Option<u64>, from_onchain: bool,
79607990
startup_replay: bool, next_channel_counterparty_node_id: PublicKey,
79617991
next_channel_outpoint: OutPoint, next_channel_id: ChannelId,
7962-
next_user_channel_id: Option<u128>,
7992+
next_user_channel_id: Option<u128>, attribution_data: Option<&AttributionData>,
7993+
send_timestamp: Option<Duration>,
79637994
) {
79647995
match source {
79657996
HTLCSource::OutboundRoute {
@@ -7991,10 +8022,25 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
79918022
let prev_node_id = hop_data.counterparty_node_id;
79928023
let completed_blocker =
79938024
RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
8025+
8026+
// Obtain hold time, if available.
8027+
let now = duration_since_epoch();
8028+
let hold_time = hold_time(send_timestamp, now).unwrap_or(0);
8029+
8030+
// If attribution data was received from downstream, we shift it and get it ready for adding our hold
8031+
// time. Note that fulfilled HTLCs take a fast path to the incoming side. We don't need to wait for RAA
8032+
// to record the hold time like we do for failed HTLCs.
8033+
let attribution_data = process_fulfill_attribution_data(
8034+
attribution_data,
8035+
&hop_data.incoming_packet_shared_secret,
8036+
hold_time,
8037+
);
8038+
79948039
self.claim_funds_from_hop(
79958040
hop_data,
79968041
payment_preimage,
79978042
None,
8043+
Some(attribution_data),
79988044
|htlc_claim_value_msat, definitely_duplicate| {
79998045
let chan_to_release = Some(EventUnblockedChannel {
80008046
counterparty_node_id: next_channel_counterparty_node_id,
@@ -9553,7 +9599,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
95539599
) -> Result<(), MsgHandleErrInternal> {
95549600
let funding_txo;
95559601
let next_user_channel_id;
9556-
let (htlc_source, forwarded_htlc_value, skimmed_fee_msat) = {
9602+
let (htlc_source, forwarded_htlc_value, skimmed_fee_msat, send_timestamp) = {
95579603
let per_peer_state = self.per_peer_state.read().unwrap();
95589604
let peer_state_mutex = per_peer_state.get(counterparty_node_id).ok_or_else(|| {
95599605
debug_assert!(false);
@@ -9608,6 +9654,8 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
96089654
funding_txo,
96099655
msg.channel_id,
96109656
Some(next_user_channel_id),
9657+
msg.attribution_data.as_ref(),
9658+
send_timestamp,
96119659
);
96129660

96139661
Ok(())
@@ -10429,6 +10477,8 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
1042910477
"Claiming HTLC with preimage {} from our monitor",
1043010478
preimage
1043110479
);
10480+
// Claim the funds from the previous hop, if there is one. Because this is in response to a
10481+
// chain event, no attribution data is available.
1043210482
self.claim_funds_internal(
1043310483
htlc_update.source,
1043410484
preimage,
@@ -10440,6 +10490,8 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
1044010490
funding_outpoint,
1044110491
channel_id,
1044210492
None,
10493+
None,
10494+
None,
1044310495
);
1044410496
} else {
1044510497
log_trace!(
@@ -16293,10 +16345,14 @@ where
1629316345
// Note that we don't need to pass the `payment_info` here - its
1629416346
// already (clearly) durably on disk in the `ChannelMonitor` so there's
1629516347
// no need to worry about getting it into others.
16348+
//
16349+
// We don't encode any attribution data, because the required onion shared secret isn't
16350+
// available here.
1629616351
channel_manager.claim_mpp_part(
1629716352
part.into(),
1629816353
payment_preimage,
1629916354
None,
16355+
None,
1630016356
|_, _| {
1630116357
(
1630216358
Some(MonitorUpdateCompletionAction::PaymentClaimed {
@@ -16441,6 +16497,7 @@ where
1644116497
// We use `downstream_closed` in place of `from_onchain` here just as a guess - we
1644216498
// don't remember in the `ChannelMonitor` where we got a preimage from, but if the
1644316499
// channel is closed we just assume that it probably came from an on-chain claim.
16500+
// The same holds for attribution data. We don't have any, so we pass an empty one.
1644416501
channel_manager.claim_funds_internal(
1644516502
source,
1644616503
preimage,
@@ -16452,6 +16509,8 @@ where
1645216509
downstream_funding,
1645316510
downstream_channel_id,
1645416511
None,
16512+
None,
16513+
None,
1645516514
);
1645616515
}
1645716516

lightning/src/ln/functional_tests.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7748,7 +7748,8 @@ pub fn test_onion_value_mpp_set_calculation() {
77487748
assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
77497749

77507750
if idx == 0 {
7751-
// routing node
7751+
// Manipulate the onion packet for the routing node. Note that we pick a dummy session_priv here. The sender
7752+
// won't be able to decode fulfill attribution data.
77527753
let session_priv = [3; 32];
77537754
let height = nodes[0].best_block_info().1;
77547755
let session_priv = SecretKey::from_slice(&session_priv).unwrap();

0 commit comments

Comments
 (0)