@@ -50,7 +50,7 @@ use crate::ln::chan_utils::{
5050#[cfg(splicing)]
5151use crate::ln::chan_utils::FUNDING_TRANSACTION_WITNESS_WEIGHT;
5252use crate::ln::chan_utils;
53- use crate::ln::onion_utils::{HTLCFailReason};
53+ use crate::ln::onion_utils::{HTLCFailReason, ATTRIBUTION_DATA_LEN };
5454use crate::chain::BestBlock;
5555use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator, fee_for_weight};
5656use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
@@ -68,8 +68,11 @@ use crate::util::scid_utils::scid_from_parts;
6868
6969use crate::io;
7070use crate::prelude::*;
71+ use core::time::Duration;
7172use core::{cmp,mem,fmt};
7273use core::ops::Deref;
74+ #[cfg(feature = "std")]
75+ use std::time::SystemTime;
7376#[cfg(any(test, fuzzing, debug_assertions))]
7477use crate::sync::Mutex;
7578use crate::sign::type_resolver::ChannelSignerType;
@@ -323,6 +326,7 @@ struct OutboundHTLCOutput {
323326 source: HTLCSource,
324327 blinding_point: Option<PublicKey>,
325328 skimmed_fee_msat: Option<u64>,
329+ timestamp: Option<Duration>,
326330}
327331
328332/// See AwaitingRemoteRevoke ChannelState for more info
@@ -4933,7 +4937,7 @@ trait FailHTLCContents {
49334937impl FailHTLCContents for msgs::OnionErrorPacket {
49344938 type Message = msgs::UpdateFailHTLC;
49354939 fn to_message(self, htlc_id: u64, channel_id: ChannelId) -> Self::Message {
4936- msgs::UpdateFailHTLC { htlc_id, channel_id, reason: self.data }
4940+ msgs::UpdateFailHTLC { htlc_id, channel_id, reason: self.data, attribution_data: self.attribution_data }
49374941 }
49384942 fn to_inbound_htlc_state(self) -> InboundHTLCState {
49394943 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(self))
@@ -6100,10 +6104,16 @@ impl<SP: Deref> FundedChannel<SP> where
61006104 false
61016105 } else { true }
61026106 });
6107+ let now = duration_since_epoch();
61036108 pending_outbound_htlcs.retain(|htlc| {
61046109 if let &OutboundHTLCState::AwaitingRemovedRemoteRevoke(ref outcome) = &htlc.state {
61056110 log_trace!(logger, " ...removing outbound AwaitingRemovedRemoteRevoke {}", &htlc.payment_hash);
6106- if let OutboundHTLCOutcome::Failure(reason) = outcome.clone() { // We really want take() here, but, again, non-mut ref :(
6111+ if let OutboundHTLCOutcome::Failure(mut reason) = outcome.clone() { // We really want take() here, but, again, non-mut ref :(
6112+ if let (Some(timestamp), Some(now)) = (htlc.timestamp, now) {
6113+ let hold_time = u32::try_from((now - timestamp).as_millis()).unwrap_or(u32::MAX);
6114+ reason.set_hold_time(hold_time);
6115+ }
6116+
61076117 revoked_htlcs.push((htlc.source.clone(), htlc.payment_hash, reason));
61086118 } else {
61096119 finalized_claimed_htlcs.push(htlc.source.clone());
@@ -6845,6 +6855,7 @@ impl<SP: Deref> FundedChannel<SP> where
68456855 channel_id: self.context.channel_id(),
68466856 htlc_id: htlc.htlc_id,
68476857 reason: err_packet.data.clone(),
6858+ attribution_data: err_packet.attribution_data,
68486859 });
68496860 },
68506861 &InboundHTLCRemovalReason::FailMalformed((ref sha256_of_onion, ref failure_code)) => {
@@ -8671,6 +8682,7 @@ impl<SP: Deref> FundedChannel<SP> where
86718682 return Ok(None);
86728683 }
86738684
8685+ let timestamp = duration_since_epoch();
86748686 self.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
86758687 htlc_id: self.context.next_holder_htlc_id,
86768688 amount_msat,
@@ -8680,6 +8692,7 @@ impl<SP: Deref> FundedChannel<SP> where
86808692 source,
86818693 blinding_point,
86828694 skimmed_fee_msat,
8695+ timestamp,
86838696 });
86848697
86858698 let res = msgs::UpdateAddHTLC {
@@ -10247,6 +10260,7 @@ impl<SP: Deref> Writeable for FundedChannel<SP> where SP::Target: SignerProvider
1024710260 dropped_inbound_htlcs += 1;
1024810261 }
1024910262 }
10263+ let mut removed_htlc_failure_attribution_data: Vec<&Option<[u8; ATTRIBUTION_DATA_LEN]>> = Vec::new();
1025010264 (self.context.pending_inbound_htlcs.len() as u64 - dropped_inbound_htlcs).write(writer)?;
1025110265 for htlc in self.context.pending_inbound_htlcs.iter() {
1025210266 if let &InboundHTLCState::RemoteAnnounced(_) = &htlc.state {
@@ -10272,9 +10286,10 @@ impl<SP: Deref> Writeable for FundedChannel<SP> where SP::Target: SignerProvider
1027210286 &InboundHTLCState::LocalRemoved(ref removal_reason) => {
1027310287 4u8.write(writer)?;
1027410288 match removal_reason {
10275- InboundHTLCRemovalReason::FailRelay(msgs::OnionErrorPacket { data }) => {
10289+ InboundHTLCRemovalReason::FailRelay(msgs::OnionErrorPacket { data, attribution_data }) => {
1027610290 0u8.write(writer)?;
1027710291 data.write(writer)?;
10292+ removed_htlc_failure_attribution_data.push(&attribution_data);
1027810293 },
1027910294 InboundHTLCRemovalReason::FailMalformed((hash, code)) => {
1028010295 1u8.write(writer)?;
@@ -10336,10 +10351,11 @@ impl<SP: Deref> Writeable for FundedChannel<SP> where SP::Target: SignerProvider
1033610351
1033710352 let mut holding_cell_skimmed_fees: Vec<Option<u64>> = Vec::new();
1033810353 let mut holding_cell_blinding_points: Vec<Option<PublicKey>> = Vec::new();
10354+ let mut holding_cell_failure_attribution_data: Vec<(u32, [u8; ATTRIBUTION_DATA_LEN])> = Vec::new();
1033910355 // Vec of (htlc_id, failure_code, sha256_of_onion)
1034010356 let mut malformed_htlcs: Vec<(u64, u16, [u8; 32])> = Vec::new();
1034110357 (self.context.holding_cell_htlc_updates.len() as u64).write(writer)?;
10342- for update in self.context.holding_cell_htlc_updates.iter() {
10358+ for (i, update) in self.context.holding_cell_htlc_updates.iter().enumerate () {
1034310359 match update {
1034410360 &HTLCUpdateAwaitingACK::AddHTLC {
1034510361 ref amount_msat, ref cltv_expiry, ref payment_hash, ref source, ref onion_routing_packet,
@@ -10364,6 +10380,13 @@ impl<SP: Deref> Writeable for FundedChannel<SP> where SP::Target: SignerProvider
1036410380 2u8.write(writer)?;
1036510381 htlc_id.write(writer)?;
1036610382 err_packet.data.write(writer)?;
10383+
10384+ // Store the attribution data for later writing. Include the holding cell htlc update index because
10385+ // FailMalformedHTLC is stored with the same type 2 and we wouldn't be able to distinguish the two
10386+ // when reading back in.
10387+ if let Some(attribution_data ) = err_packet.attribution_data {
10388+ holding_cell_failure_attribution_data.push((i as u32, attribution_data));
10389+ }
1036710390 }
1036810391 &HTLCUpdateAwaitingACK::FailMalformedHTLC {
1036910392 htlc_id, failure_code, sha256_of_onion
@@ -10547,6 +10570,8 @@ impl<SP: Deref> Writeable for FundedChannel<SP> where SP::Target: SignerProvider
1054710570 (49, self.context.local_initiated_shutdown, option), // Added in 0.0.122
1054810571 (51, is_manual_broadcast, option), // Added in 0.0.124
1054910572 (53, funding_tx_broadcast_safe_event_emitted, option), // Added in 0.0.124
10573+ (55, removed_htlc_failure_attribution_data, optional_vec), // Added in 0.2
10574+ (57, holding_cell_failure_attribution_data, optional_vec), // Added in 0.2
1055010575 });
1055110576
1055210577 Ok(())
@@ -10624,6 +10649,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1062410649 let reason = match <u8 as Readable>::read(reader)? {
1062510650 0 => InboundHTLCRemovalReason::FailRelay(msgs::OnionErrorPacket {
1062610651 data: Readable::read(reader)?,
10652+ attribution_data: None,
1062710653 }),
1062810654 1 => InboundHTLCRemovalReason::FailMalformed(Readable::read(reader)?),
1062910655 2 => InboundHTLCRemovalReason::Fulfill(Readable::read(reader)?),
@@ -10664,6 +10690,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1066410690 },
1066510691 skimmed_fee_msat: None,
1066610692 blinding_point: None,
10693+ timestamp: None,
1066710694 });
1066810695 }
1066910696
@@ -10688,6 +10715,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1068810715 htlc_id: Readable::read(reader)?,
1068910716 err_packet: OnionErrorPacket {
1069010717 data: Readable::read(reader)?,
10718+ attribution_data: None,
1069110719 },
1069210720 },
1069310721 _ => return Err(DecodeError::InvalidValue),
@@ -10831,6 +10859,9 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1083110859 let mut pending_outbound_blinding_points_opt: Option<Vec<Option<PublicKey>>> = None;
1083210860 let mut holding_cell_blinding_points_opt: Option<Vec<Option<PublicKey>>> = None;
1083310861
10862+ let mut removed_htlc_failure_attribution_data: Option<Vec<Option<[u8; ATTRIBUTION_DATA_LEN]>>> = None;
10863+ let mut holding_cell_failure_attribution_data: Option<Vec<(u32, [u8; ATTRIBUTION_DATA_LEN])>> = None;
10864+
1083410865 let mut malformed_htlcs: Option<Vec<(u64, u16, [u8; 32])>> = None;
1083510866 let mut monitor_pending_update_adds: Option<Vec<msgs::UpdateAddHTLC>> = None;
1083610867
@@ -10873,6 +10904,8 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1087310904 (49, local_initiated_shutdown, option),
1087410905 (51, is_manual_broadcast, option),
1087510906 (53, funding_tx_broadcast_safe_event_emitted, option),
10907+ (55, removed_htlc_failure_attribution_data, optional_vec),
10908+ (57, holding_cell_failure_attribution_data, optional_vec),
1087610909 });
1087710910
1087810911 let holder_signer = signer_provider.derive_channel_signer(channel_keys_id);
@@ -10954,6 +10987,38 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1095410987 if iter.next().is_some() { return Err(DecodeError::InvalidValue) }
1095510988 }
1095610989
10990+ if let Some(attribution_datas) = removed_htlc_failure_attribution_data {
10991+ let mut removed_htlc_relay_failures =
10992+ pending_inbound_htlcs.iter_mut().filter_map(|status|
10993+ if let InboundHTLCState::LocalRemoved(ref mut reason) = &mut status.state {
10994+ if let InboundHTLCRemovalReason::FailRelay(ref mut packet) = reason {
10995+ Some(&mut packet.attribution_data)
10996+ } else {
10997+ None
10998+ }
10999+ } else {
11000+ None
11001+ }
11002+ );
11003+
11004+ for attribution_data in attribution_datas {
11005+ *removed_htlc_relay_failures.next().ok_or(DecodeError::InvalidValue)? = attribution_data;
11006+ }
11007+ if removed_htlc_relay_failures.next().is_some() { return Err(DecodeError::InvalidValue); }
11008+ }
11009+
11010+ if let Some(attribution_datas) = holding_cell_failure_attribution_data {
11011+ for (i, attribution_data) in attribution_datas {
11012+ let update = holding_cell_htlc_updates.get_mut(i as usize).ok_or(DecodeError::InvalidValue)?;
11013+
11014+ if let HTLCUpdateAwaitingACK::FailHTLC { htlc_id: _, ref mut err_packet } = update {
11015+ err_packet.attribution_data = Some(attribution_data);
11016+ } else {
11017+ return Err(DecodeError::InvalidValue);
11018+ }
11019+ }
11020+ }
11021+
1095711022 if let Some(malformed_htlcs) = malformed_htlcs {
1095811023 for (malformed_htlc_id, failure_code, sha256_of_onion) in malformed_htlcs {
1095911024 let htlc_idx = holding_cell_htlc_updates.iter().position(|htlc| {
@@ -11144,6 +11209,18 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, &'c Channel
1114411209 }
1114511210}
1114611211
11212+ fn duration_since_epoch() -> Option<Duration> {
11213+ #[cfg(not(feature = "std"))]
11214+ let now = None;
11215+
11216+ #[cfg(feature = "std")]
11217+ let now = Some(std::time::SystemTime::now()
11218+ .duration_since(std::time::SystemTime::UNIX_EPOCH)
11219+ .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH"));
11220+
11221+ now
11222+ }
11223+
1114711224#[cfg(test)]
1114811225mod tests {
1114911226 use std::cmp;
@@ -11157,7 +11234,7 @@ mod tests {
1115711234 use bitcoin::network::Network;
1115811235 #[cfg(splicing)]
1115911236 use bitcoin::Weight;
11160- use crate::ln::onion_utils::INVALID_ONION_BLINDING;
11237+ use crate::ln::onion_utils::{ATTRIBUTION_DATA_LEN, INVALID_ONION_BLINDING} ;
1116111238 use crate::types::payment::{PaymentHash, PaymentPreimage};
1116211239 use crate::ln::channel_keys::{RevocationKey, RevocationBasepoint};
1116311240 use crate::ln::channelmanager::{self, HTLCSource, PaymentId};
@@ -11378,6 +11455,7 @@ mod tests {
1137811455 },
1137911456 skimmed_fee_msat: None,
1138011457 blinding_point: None,
11458+ timestamp: None,
1138111459 });
1138211460
1138311461 // Make sure when Node A calculates their local commitment transaction, none of the HTLCs pass
@@ -11762,6 +11840,7 @@ mod tests {
1176211840 source: dummy_htlc_source.clone(),
1176311841 skimmed_fee_msat: None,
1176411842 blinding_point: None,
11843+ timestamp: None,
1176511844 };
1176611845 let mut pending_outbound_htlcs = vec![dummy_outbound_output.clone(); 10];
1176711846 for (idx, htlc) in pending_outbound_htlcs.iter_mut().enumerate() {
@@ -11793,7 +11872,7 @@ mod tests {
1179311872 htlc_id: 0,
1179411873 };
1179511874 let dummy_holding_cell_failed_htlc = |htlc_id| HTLCUpdateAwaitingACK::FailHTLC {
11796- htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42] }
11875+ htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42], attribution_data: Some([1; ATTRIBUTION_DATA_LEN]) }
1179711876 };
1179811877 let dummy_holding_cell_malformed_htlc = |htlc_id| HTLCUpdateAwaitingACK::FailMalformedHTLC {
1179911878 htlc_id, failure_code: INVALID_ONION_BLINDING, sha256_of_onion: [0; 32],
0 commit comments