Skip to content

Commit 8e8c6e7

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 e99fc10 commit 8e8c6e7

File tree

3 files changed

+86
-35
lines changed

3 files changed

+86
-35
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 46 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ enum PendingForwardReceiveHTLCInfo {
7474
onion_packet: msgs::OnionPacket,
7575
short_channel_id: u64, // This should be NonZero<u64> eventually
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,12 @@ pub(super) struct HTLCPreviousHopData {
119121
incoming_packet_shared_secret: [u8; 32],
120122
}
121123

124+
struct ClaimableHTLC {
125+
src: HTLCPreviousHopData,
126+
value: u64,
127+
payment_data: Option<msgs::FinalOnionHopData>,
128+
}
129+
122130
/// Tracks the inbound corresponding to an outbound HTLC
123131
#[derive(Clone, PartialEq)]
124132
pub(super) enum HTLCSource {
@@ -276,12 +284,11 @@ pub(super) struct ChannelHolder<ChanSigner: ChannelKeys> {
276284
/// guarantees are made about the existence of a channel with the short id here, nor the short
277285
/// ids in the PendingHTLCInfo!
278286
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
287+
/// Tracks things that were to us and can be failed/claimed by the user
281288
/// Note that while this is held in the same mutex as the channels themselves, no consistency
282289
/// guarantees are made about the channels given here actually existing anymore by the time you
283290
/// go to read them!
284-
pub(super) claimable_htlcs: HashMap<PaymentHash, Vec<(u64, HTLCPreviousHopData)>>,
291+
claimable_htlcs: HashMap<PaymentHash, Vec<ClaimableHTLC>>,
285292
/// Messages to send to peers - pushed to in the same lock that they are generated in (except
286293
/// for broadcast messages, where ordering isn't as strict).
287294
pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
@@ -989,13 +996,19 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
989996
return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
990997
}
991998

999+
let payment_data = match next_hop_data.format {
1000+
msgs::OnionHopDataFormat::Legacy { .. } => None,
1001+
msgs::OnionHopDataFormat::NonFinalNode { .. } => return_err!("Got non final data with an HMAC of 0", 0x4000 | 22, &[0;0]),
1002+
msgs::OnionHopDataFormat::FinalNode { payment_data } => payment_data,
1003+
};
1004+
9921005
// Note that we could obviously respond immediately with an update_fulfill_htlc
9931006
// message, however that would leak that we are the recipient of this payment, so
9941007
// instead we stay symmetric with the forwarding case, only responding (after a
9951008
// delay) once they've send us a commitment_signed!
9961009

9971010
PendingHTLCStatus::Forward(PendingHTLCInfo {
998-
type_data: PendingForwardReceiveHTLCInfo::Receive {},
1011+
type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
9991012
payment_hash: msg.payment_hash.clone(),
10001013
incoming_shared_secret: shared_secret,
10011014
amt_to_forward: next_hop_data.amt_to_forward,
@@ -1569,17 +1582,18 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
15691582
for forward_info in pending_forwards.drain(..) {
15701583
match forward_info {
15711584
HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info: PendingHTLCInfo {
1572-
type_data: PendingForwardReceiveHTLCInfo::Receive { },
1585+
type_data: PendingForwardReceiveHTLCInfo::Receive { payment_data },
15731586
incoming_shared_secret, payment_hash, amt_to_forward, .. }, } => {
15741587
let prev_hop_data = HTLCPreviousHopData {
15751588
short_channel_id: prev_short_channel_id,
15761589
htlc_id: prev_htlc_id,
15771590
incoming_packet_shared_secret: incoming_shared_secret,
15781591
};
1579-
match channel_state.claimable_htlcs.entry(payment_hash) {
1580-
hash_map::Entry::Occupied(mut entry) => entry.get_mut().push((amt_to_forward, prev_hop_data)),
1581-
hash_map::Entry::Vacant(entry) => { entry.insert(vec![(amt_to_forward, prev_hop_data)]); },
1582-
};
1592+
channel_state.claimable_htlcs.entry(payment_hash).or_insert(Vec::new()).push(ClaimableHTLC {
1593+
src: prev_hop_data,
1594+
value: amt_to_forward,
1595+
payment_data,
1596+
});
15831597
new_events.push(events::Event::PaymentReceived {
15841598
payment_hash: payment_hash,
15851599
amt: amt_to_forward,
@@ -1652,11 +1666,11 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
16521666
let mut channel_state = Some(self.channel_state.lock().unwrap());
16531667
let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
16541668
if let Some(mut sources) = removed_source {
1655-
for (recvd_value, htlc_with_hash) in sources.drain(..) {
1669+
for htlc in sources.drain(..) {
16561670
if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
16571671
self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1658-
HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1659-
HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(recvd_value).to_vec() });
1672+
HTLCSource::PreviousHopData(htlc.src), payment_hash,
1673+
HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(htlc.value).to_vec() });
16601674
}
16611675
true
16621676
} else { false }
@@ -1780,17 +1794,17 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref> ChannelMan
17801794
let mut channel_state = Some(self.channel_state.lock().unwrap());
17811795
let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
17821796
if let Some(mut sources) = removed_source {
1783-
for (received_amount, htlc_with_hash) in sources.drain(..) {
1797+
for htlc in sources.drain(..) {
17841798
if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1785-
if received_amount < expected_amount || received_amount > expected_amount * 2 {
1786-
let mut htlc_msat_data = byte_utils::be64_to_array(received_amount).to_vec();
1799+
if htlc.value < expected_amount || htlc.value > expected_amount * 2 {
1800+
let mut htlc_msat_data = byte_utils::be64_to_array(htlc.value).to_vec();
17871801
let mut height_data = byte_utils::be32_to_array(self.latest_block_height.load(Ordering::Acquire) as u32).to_vec();
17881802
htlc_msat_data.append(&mut height_data);
17891803
self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1790-
HTLCSource::PreviousHopData(htlc_with_hash), &payment_hash,
1804+
HTLCSource::PreviousHopData(htlc.src), &payment_hash,
17911805
HTLCFailReason::Reason { failure_code: 0x4000|15, data: htlc_msat_data });
17921806
} else {
1793-
self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1807+
self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc.src), payment_preimage);
17941808
}
17951809
}
17961810
true
@@ -3154,8 +3168,9 @@ impl Writeable for PendingHTLCInfo {
31543168
onion_packet.write(writer)?;
31553169
short_channel_id.write(writer)?;
31563170
},
3157-
&PendingForwardReceiveHTLCInfo::Receive { } => {
3171+
&PendingForwardReceiveHTLCInfo::Receive { ref payment_data } => {
31583172
1u8.write(writer)?;
3173+
payment_data.write(writer)?;
31593174
},
31603175
}
31613176
self.incoming_shared_secret.write(writer)?;
@@ -3174,7 +3189,9 @@ impl Readable for PendingHTLCInfo {
31743189
onion_packet: Readable::read(reader)?,
31753190
short_channel_id: Readable::read(reader)?,
31763191
},
3177-
1u8 => PendingForwardReceiveHTLCInfo::Receive { },
3192+
1u8 => PendingForwardReceiveHTLCInfo::Receive {
3193+
payment_data: Readable::read(reader)?,
3194+
},
31783195
_ => return Err(DecodeError::InvalidValue),
31793196
},
31803197
incoming_shared_secret: Readable::read(reader)?,
@@ -3384,9 +3401,10 @@ impl<ChanSigner: ChannelKeys + Writeable, M: Deref, T: Deref, K: Deref, F: Deref
33843401
for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
33853402
payment_hash.write(writer)?;
33863403
(previous_hops.len() as u64).write(writer)?;
3387-
for &(recvd_amt, ref previous_hop) in previous_hops.iter() {
3388-
recvd_amt.write(writer)?;
3389-
previous_hop.write(writer)?;
3404+
for htlc in previous_hops.iter() {
3405+
htlc.src.write(writer)?;
3406+
htlc.value.write(writer)?;
3407+
htlc.payment_data.write(writer)?;
33903408
}
33913409
}
33923410

@@ -3556,7 +3574,11 @@ impl<'a, ChanSigner: ChannelKeys + Readable, M: Deref, T: Deref, K: Deref, F: De
35563574
let previous_hops_len: u64 = Readable::read(reader)?;
35573575
let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
35583576
for _ in 0..previous_hops_len {
3559-
previous_hops.push((Readable::read(reader)?, Readable::read(reader)?));
3577+
previous_hops.push(ClaimableHTLC {
3578+
src: Readable::read(reader)?,
3579+
value: Readable::read(reader)?,
3580+
payment_data: Readable::read(reader)?,
3581+
});
35603582
}
35613583
claimable_htlcs.insert(payment_hash, previous_hops);
35623584
}

lightning/src/ln/msgs.rs

Lines changed: 37 additions & 10 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,11 @@ impl_writeable!(UpdateAddHTLC, 32+8+8+32+4+1366, {
965972
onion_routing_packet
966973
});
967974

975+
impl_writeable!(FinalOnionHopData, 32+8, {
976+
payment_secret,
977+
total_msat
978+
});
979+
968980
impl Writeable for OnionHopData {
969981
fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
970982
w.size_hint(33);
@@ -983,11 +995,19 @@ impl Writeable for OnionHopData {
983995
(6, short_channel_id)
984996
});
985997
},
986-
OnionHopDataFormat::FinalNode => {
987-
encode_varint_length_prefixed_tlv!(w, {
988-
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
989-
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
990-
});
998+
OnionHopDataFormat::FinalNode { ref payment_data } => {
999+
if let &Some(ref final_data) = payment_data {
1000+
encode_varint_length_prefixed_tlv!(w, {
1001+
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1002+
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value)),
1003+
(8, final_data)
1004+
});
1005+
} else {
1006+
encode_varint_length_prefixed_tlv!(w, {
1007+
(2, HighZeroBytesDroppedVarInt(self.amt_to_forward)),
1008+
(4, HighZeroBytesDroppedVarInt(self.outgoing_cltv_value))
1009+
});
1010+
}
9911011
},
9921012
}
9931013
Ok(())
@@ -1008,19 +1028,24 @@ impl Readable for OnionHopData {
10081028
let mut amt = HighZeroBytesDroppedVarInt(0u64);
10091029
let mut cltv_value = HighZeroBytesDroppedVarInt(0u32);
10101030
let mut short_id: Option<u64> = None;
1031+
let mut payment_data: Option<FinalOnionHopData> = None;
10111032
decode_tlv!(&mut rd, {
10121033
(2, amt),
10131034
(4, cltv_value)
10141035
}, {
1015-
(6, short_id)
1036+
(6, short_id),
1037+
(8, payment_data)
10161038
});
10171039
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
10181040
let format = if let Some(short_channel_id) = short_id {
1041+
if payment_data.is_some() { return Err(DecodeError::InvalidValue); }
10191042
OnionHopDataFormat::NonFinalNode {
10201043
short_channel_id,
10211044
}
10221045
} else {
1023-
OnionHopDataFormat::FinalNode
1046+
OnionHopDataFormat::FinalNode {
1047+
payment_data
1048+
}
10241049
};
10251050
(format, amt.0, cltv_value.0)
10261051
} else {
@@ -1998,15 +2023,17 @@ mod tests {
19982023
#[test]
19992024
fn encoding_final_onion_hop_data() {
20002025
let mut msg = msgs::OnionHopData {
2001-
format: OnionHopDataFormat::FinalNode,
2026+
format: OnionHopDataFormat::FinalNode {
2027+
payment_data: None,
2028+
},
20022029
amt_to_forward: 0x0badf00d01020304,
20032030
outgoing_cltv_value: 0xffffffff,
20042031
};
20052032
let encoded_value = msg.encode();
20062033
let target_value = hex::decode("1002080badf00d010203040404ffffffff").unwrap();
20072034
assert_eq!(encoded_value, target_value);
20082035
msg = Readable::read(&mut Cursor::new(&target_value[..])).unwrap();
2009-
if let OnionHopDataFormat::FinalNode = msg.format { } else { panic!(); }
2036+
if let OnionHopDataFormat::FinalNode { payment_data: None } = msg.format { } else { panic!(); }
20102037
assert_eq!(msg.amt_to_forward, 0x0badf00d01020304);
20112038
assert_eq!(msg.outgoing_cltv_value, 0xffffffff);
20122039
}

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)