Skip to content

Commit b548173

Browse files
committed
Support (de)serializing payment_data in onion TLVs and track them
This is the first step in Base AMP support, just tracking the relevant data in internal datastructures.
1 parent f26e373 commit b548173

File tree

3 files changed

+127
-33
lines changed

3 files changed

+127
-33
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ enum PendingHTLCRouting {
7474
onion_packet: msgs::OnionPacket,
7575
short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
7676
},
77-
Receive {},
77+
Receive {
78+
payment_data: Option<msgs::FinalOnionHopData>,
79+
},
7880
}
7981

8082
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
@@ -119,6 +121,16 @@ pub(super) struct HTLCPreviousHopData {
119121
incoming_packet_shared_secret: [u8; 32],
120122
}
121123

124+
struct ClaimableHTLC {
125+
prev_hop: HTLCPreviousHopData,
126+
value: u64,
127+
/// Filled in when the HTLC was received with a payment_secret packet, which contains a
128+
/// total_msat (which may differ from value if this is a Multi-Path Payment) and a
129+
/// payment_secret which prevents path-probing attacks and can associate different HTLCs which
130+
/// are part of the same payment.
131+
payment_data: Option<msgs::FinalOnionHopData>,
132+
}
133+
122134
/// Tracks the inbound corresponding to an outbound HTLC
123135
#[derive(Clone, PartialEq)]
124136
pub(super) enum HTLCSource {
@@ -276,12 +288,11 @@ pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
276288
/// guarantees are made about the existence of a channel with the short id here, nor the short
277289
/// ids in the PendingHTLCInfo!
278290
pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
279-
/// payment_hash -> Vec<(amount_received, htlc_source)> for tracking things that were to us and
280-
/// can be failed/claimed by the user
291+
/// Tracks HTLCs that were to us and can be failed/claimed by the user
281292
/// Note that while this is held in the same mutex as the channels themselves, no consistency
282293
/// guarantees are made about the channels given here actually existing anymore by the time you
283294
/// go to read them!
284-
pub(super) claimable_htlcs: HashMap<PaymentHash, Vec<(u64, HTLCPreviousHopData)>>,
295+
claimable_htlcs: HashMap<PaymentHash, Vec<ClaimableHTLC>>,
285296
/// Messages to send to peers - pushed to in the same lock that they are generated in (except
286297
/// for broadcast messages, where ordering isn't as strict).
287298
pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
@@ -1007,13 +1018,19 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
10071018
return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
10081019
}
10091020

1021+
let payment_data = match next_hop_data.format {
1022+
msgs::OnionHopDataFormat::Legacy { .. } => None,
1023+
msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1024+
msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1025+
};
1026+
10101027
// Note that we could obviously respond immediately with an update_fulfill_htlc
10111028
// message, however that would leak that we are the recipient of this payment, so
10121029
// instead we stay symmetric with the forwarding case, only responding (after a
10131030
// delay) once they've send us a commitment_signed!
10141031

10151032
PendingHTLCStatus::Forward(PendingHTLCInfo {
1016-
routing: PendingHTLCRouting::Receive {},
1033+
routing: PendingHTLCRouting::Receive { payment_data },
10171034
payment_hash: msg.payment_hash.clone(),
10181035
incoming_shared_secret: shared_secret,
10191036
amt_to_forward: next_hop_data.amt_to_forward,
@@ -1580,17 +1597,18 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
15801597
for forward_info in pending_forwards.drain(..) {
15811598
match forward_info {
15821599
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1583-
routing: PendingHTLCRouting::Receive { },
1600+
routing: PendingHTLCRouting::Receive { payment_data },
15841601
incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
1585-
let prev_hop_data = HTLCPreviousHopData {
1602+
let prev_hop = HTLCPreviousHopData {
15861603
short_channel_id: prev_short_channel_id,
15871604
htlc_id: prev_htlc_id,
15881605
incoming_packet_shared_secret: incoming_shared_secret,
15891606
};
1590-
match channel_state.claimable_htlcs.entry(payment_hash) {
1591-
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push((amt_to_forward, prev_hop_data)),
1592-
hash_map::Entry::Vacant(entry) => { entry.insert(vec![(amt_to_forward, prev_hop_data)]); },
1593-
};
1607+
channel_state.claimable_htlcs.entry(payment_hash).or_insert(Vec::new()).push(ClaimableHTLC {
1608+
prev_hop,
1609+
value: amt_to_forward,
1610+
payment_data,
1611+
});
15941612
new_events.push(events::Event::PaymentReceived {
15951613
payment_hash: payment_hash,
15961614
amt: amt_to_forward,
@@ -1660,11 +1678,11 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
16601678
let mut channel_state = Some(self.channel_state.lock().unwrap());
16611679
let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
16621680
if let Some(mut sources) = removed_source {
1663-
for (recvd_value, htlc_with_hash) in sources.drain(..) {
1681+
for htlc in sources.drain(..) {
16641682
if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
16651683
self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1666-
HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1667-
HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(recvd_value).to_vec() });
1684+
HTLCSource::PreviousHopData(htlc.prev_hop), payment_hash,
1685+
HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(htlc.value).to_vec() });
16681686
}
16691687
true
16701688
} else { false }
@@ -1788,17 +1806,17 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
17881806
let mut channel_state = Some(self.channel_state.lock().unwrap());
17891807
let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
17901808
if let Some(mut sources) = removed_source {
1791-
for (received_amount, htlc_with_hash) in sources.drain(..) {
1809+
for htlc in sources.drain(..) {
17921810
if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1793-
if received_amount < expected_amount || received_amount > expected_amount * 2 {
1794-
let mut htlc_msat_data = byte_utils::be64_to_array(received_amount).to_vec();
1811+
if htlc.value < expected_amount || htlc.value > expected_amount * 2 {
1812+
let mut htlc_msat_data = byte_utils::be64_to_array(htlc.value).to_vec();
17951813
let mut height_data = byte_utils::be32_to_array(self.latest_block_height.load(Ordering::Acquire) as u32).to_vec();
17961814
htlc_msat_data.append(&mut height_data);
17971815
self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1798-
HTLCSource::PreviousHopData(htlc_with_hash), &payment_hash,
1816+
HTLCSource::PreviousHopData(htlc.prev_hop), &payment_hash,
17991817
HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_data });
18001818
} else {
1801-
self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1819+
self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc.prev_hop), payment_preimage);
18021820
}
18031821
}
18041822
true
@@ -3098,8 +3116,9 @@ impl Writeable for PendingHTLCInfo {
30983116
onion_packet.write(writer)?;
30993117
short_channel_id.write(writer)?;
31003118
},
3101-
&PendingHTLCRouting::Receive { } => {
3119+
&PendingHTLCRouting::Receive { ref payment_data } => {
31023120
1u8.write(writer)?;
3121+
payment_data.write(writer)?;
31033122
},
31043123
}
31053124
self.incoming_shared_secret.write(writer)?;
@@ -3118,7 +3137,9 @@ impl Readable for PendingHTLCInfo {
31183137
onion_packet: Readable::read(reader)?,
31193138
short_channel_id: Readable::read(reader)?,
31203139
},
3121-
1u8 => PendingHTLCRouting::Receive { },
3140+
1u8 => PendingHTLCRouting::Receive {
3141+
payment_data: Readable::read(reader)?,
3142+
},
31223143
_ => return Err(DecodeError::InvalidValue),
31233144
},
31243145
incoming_shared_secret: Readable::read(reader)?,
@@ -3187,6 +3208,12 @@ impl_writeable!(HTLCPreviousHopData, 0, {
31873208
incoming_packet_shared_secret
31883209
});
31893210

3211+
impl_writeable!(ClaimableHTLC, 0, {
3212+
prev_hop,
3213+
value,
3214+
payment_data
3215+
});
3216+
31903217
impl Writeable for HTLCSource {
31913218
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
31923219
match self {
@@ -3328,9 +3355,8 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
33283355
for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
33293356
payment_hash.write(writer)?;
33303357
(previous_hops.len() as u64).write(writer)?;
3331-
for &(recvd_amt, ref previous_hop) in previous_hops.iter() {
3332-
recvd_amt.write(writer)?;
3333-
previous_hop.write(writer)?;
3358+
for htlc in previous_hops.iter() {
3359+
htlc.write(writer)?;
33343360
}
33353361
}
33363362

@@ -3507,7 +3533,7 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
35073533
let previous_hops_len: u64 = Readable::read(reader)?;
35083534
let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
35093535
for _ in 0..previous_hops_len {
3510-
previous_hops.push((Readable::read(reader)?, Readable::read(reader)?));
3536+
previous_hops.push(Readable::read(reader)?);
35113537
}
35123538
claimable_htlcs.insert(payment_hash, previous_hops);
35133539
}

lightning/src/ln/msgs.rs

Lines changed: 73 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -614,6 +614,11 @@ pub trait RoutingMessageHandler : Send + Sync {
614614
mod fuzzy_internal_msgs {
615615
// These types aren't intended to be pub, but are exposed for direct fuzzing (as we deserialize
616616
// them from untrusted input):
617+
#[derive(Clone)]
618+
pub(crate) struct FinalOnionHopData {
619+
pub(crate) payment_secret: [u8; 32],
620+
pub(crate) total_msat: u64,
621+
}
617622

618623
pub(crate) enum OnionHopDataFormat {
619624
Legacy { // aka Realm-0
@@ -622,7 +627,9 @@ mod fuzzy_internal_msgs {
622627
NonFinalNode {
623628
short_channel_id: u64,
624629
},
625-
FinalNode,
630+
FinalNode {
631+
payment_data: Option<FinalOnionHopData>,
632+
},
626633
}
627634

628635
pub struct OnionHopData {
@@ -965,6 +972,22 @@ impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
965972
onion_routing_packet
966973
});
967974

975+
impl Writeable for FinalOnionHopData {
976+
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
977+
w.size_hint(32 + 8 - (self.total_msat.leading_zeros()/8) as usize);
978+
self.payment_secret.write(w)?;
979+
HighZeroBytesDroppedVarInt(self.total_msat).write(w)
980+
}
981+
}
982+
983+
impl Readable for FinalOnionHopData {
984+
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
985+
let payment_secret = Readable::read(r)?;
986+
let amt: HighZeroBytesDroppedVarInt<u64> = Readable::read(r)?;
987+
Ok(Self { payment_secret, total_msat: amt.0 })
988+
}
989+
}
990+
968991
impl Writeable for OnionHopData {
969992
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
970993
w.size_hint(33);
@@ -983,7 +1006,14 @@ impl Writeable for OnionHopData {
9831006
(6, short_channel_id)
9841007
});
9851008
},
986-
OnionHopDataFormat::FinalNode => {
1009+
OnionHopDataFormat::FinalNode { payment_data: Some(ref final_data) } => {
1010+
encode_varint_length_prefixed_tlv!(w, {
1011+
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1012+
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1013+
(8, final_data)
1014+
});
1015+
},
1016+
OnionHopDataFormat::FinalNode { payment_data: None } => {
9871017
encode_varint_length_prefixed_tlv!(w, {
9881018
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
9891019
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
@@ -1008,19 +1038,24 @@ impl Readable for OnionHopData {
10081038
let mut amt = HighZeroBytesDroppedVarInt(0u64);
10091039
let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
10101040
let mut short_id: Option<u64> = None;
1041+
let mut payment_data: Option<FinalOnionHopData> = None;
10111042
decode_tlv!(&mut rd, {
10121043
(2, amt),
10131044
(4, cltv_value)
10141045
}, {
1015-
(6, short_id)
1046+
(6, short_id),
1047+
(8, payment_data)
10161048
});
10171049
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
10181050
let format = if let Some(short_channel_id) = short_id {
1051+
if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
10191052
OnionHopDataFormat::NonFinalNode {
10201053
short_channel_id,
10211054
}
10221055
} else {
1023-
OnionHopDataFormat::FinalNode
1056+
OnionHopDataFormat::FinalNode {
1057+
payment_data
1058+
}
10241059
};
10251060
(format, amt.0, cltv_value.0)
10261061
} else {
@@ -1305,7 +1340,7 @@ impl_writeable_len_match!(NodeAnnouncement, {
13051340
mod tests {
13061341
use hex;
13071342
use ln::msgs;
1308-
use ln::msgs::{ChannelFeatures, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
1343+
use ln::msgs::{ChannelFeatures, FinalOnionHopData, InitFeatures, NodeFeatures, OptionalField, OnionErrorPacket, OnionHopDataFormat};
13091344
use ln::channelmanager::{PaymentPreimage, PaymentHash};
13101345
use util::ser::{Writeable, Readable};
13111346

@@ -1998,15 +2033,46 @@ mod tests {
19982033
#[test]
19992034
fn encoding_final_onion_hop_data() {
20002035
let mut msg = msgs::OnionHopData {
2001-
format: OnionHopDataFormat::FinalNode,
2036+
format: OnionHopDataFormat::FinalNode {
2037+
payment_data: None,
2038+
},
20022039
amt_to_forward: 0x0badf00d01020304,
20032040
outgoing_cltv_value: 0xffffffff,
20042041
};
20052042
let encoded_value = msg.encode();
20062043
let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
20072044
assert_eq!(encoded_value, target_value);
20082045
msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2009-
if let OnionHopDataFormat::FinalNode = msg.format { } else { panic!(); }
2046+
if let OnionHopDataFormat::FinalNode { payment_data: None } = msg.format { } else { panic!(); }
2047+
assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
2048+
assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
2049+
}
2050+
2051+
#[test]
2052+
fn encoding_final_onion_hop_data_with_secret() {
2053+
let expected_payment_secret = [0x42u8; 32];
2054+
let mut msg = msgs::OnionHopData {
2055+
format: OnionHopDataFormat::FinalNode {
2056+
payment_data: Some(FinalOnionHopData {
2057+
payment_secret: expected_payment_secret,
2058+
total_msat: 0x1badca1f
2059+
}),
2060+
},
2061+
amt_to_forward: 0x0badf00d01020304,
2062+
outgoing_cltv_value: 0xffffffff,
2063+
};
2064+
let encoded_value = msg.encode();
2065+
let target_value = hex::decode("3602080badf00d010203040404ffffffff082442424242424242424242424242424242424242424242424242424242424242421badca1f").unwrap();
2066+
assert_eq!(encoded_value, target_value);
2067+
msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2068+
if let OnionHopDataFormat::FinalNode {
2069+
payment_data: Some(FinalOnionHopData {
2070+
payment_secret,
2071+
total_msat: 0x1badca1f
2072+
})
2073+
} = msg.format {
2074+
assert_eq!(payment_secret, expected_payment_secret);
2075+
} else { panic!(); }
20102076
assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
20112077
assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
20122078
}

lightning/src/ln/onion_utils.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,9 @@ pub(super) fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) ->
123123
res.insert(0, msgs::OnionHopData {
124124
format: if hop.node_features.supports_variable_length_onion() {
125125
if idx == 0 {
126-
msgs::OnionHopDataFormat::FinalNode
126+
msgs::OnionHopDataFormat::FinalNode {
127+
payment_data: None,
128+
}
127129
} else {
128130
msgs::OnionHopDataFormat::NonFinalNode {
129131
short_channel_id: last_short_channel_id,

0 commit comments

Comments
 (0)