5966dce91039db227155264deb0557a2ed2012ff
[rust-lightning] / lightning / src / ln / onion_payment.rs
1 //! Utilities to decode payment onions and do contextless validation of incoming payments.
2 //!
3 //! Primarily features [`peel_payment_onion`], which allows the decoding of an onion statelessly
4 //! and can be used to predict whether we'd accept a payment.
5
6 use bitcoin::hashes::{Hash, HashEngine};
7 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
8 use bitcoin::hashes::sha256::Hash as Sha256;
9 use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1};
10
11 use crate::blinded_path;
12 use crate::blinded_path::payment::{PaymentConstraints, PaymentRelay};
13 use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
14 use crate::ln::PaymentHash;
15 use crate::ln::channelmanager::{BlindedForward, CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
16 use crate::ln::features::BlindedHopFeatures;
17 use crate::ln::msgs;
18 use crate::ln::onion_utils;
19 use crate::ln::onion_utils::{HTLCFailReason, INVALID_ONION_BLINDING};
20 use crate::sign::{NodeSigner, Recipient};
21 use crate::util::logger::Logger;
22
23 use crate::prelude::*;
24 use core::ops::Deref;
25
26 /// Invalid inbound onion payment.
27 #[derive(Debug)]
28 pub struct InboundOnionErr {
29         /// BOLT 4 error code.
30         pub err_code: u16,
31         /// Data attached to this error.
32         pub err_data: Vec<u8>,
33         /// Error message text.
34         pub msg: &'static str,
35 }
36
37 fn check_blinded_payment_constraints(
38         amt_msat: u64, cltv_expiry: u32, constraints: &PaymentConstraints
39 ) -> Result<(), ()> {
40         if amt_msat < constraints.htlc_minimum_msat ||
41                 cltv_expiry > constraints.max_cltv_expiry
42         { return Err(()) }
43         Ok(())
44 }
45
46 fn check_blinded_forward(
47         inbound_amt_msat: u64, inbound_cltv_expiry: u32, payment_relay: &PaymentRelay,
48         payment_constraints: &PaymentConstraints, features: &BlindedHopFeatures
49 ) -> Result<(u64, u32), ()> {
50         let amt_to_forward = blinded_path::payment::amt_to_forward_msat(
51                 inbound_amt_msat, payment_relay
52         ).ok_or(())?;
53         let outgoing_cltv_value = inbound_cltv_expiry.checked_sub(
54                 payment_relay.cltv_expiry_delta as u32
55         ).ok_or(())?;
56         check_blinded_payment_constraints(inbound_amt_msat, outgoing_cltv_value, payment_constraints)?;
57
58         if features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
59         Ok((amt_to_forward, outgoing_cltv_value))
60 }
61
62 pub(super) fn create_fwd_pending_htlc_info(
63         msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
64         new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
65         next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
66 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
67         debug_assert!(next_packet_pubkey_opt.is_some());
68         let outgoing_packet = msgs::OnionPacket {
69                 version: 0,
70                 public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
71                 hop_data: new_packet_bytes,
72                 hmac: hop_hmac,
73         };
74
75         let (
76                 short_channel_id, amt_to_forward, outgoing_cltv_value, inbound_blinding_point
77         ) = match hop_data {
78                 msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
79                         (short_channel_id, amt_to_forward, outgoing_cltv_value, None),
80                 msgs::InboundOnionPayload::BlindedForward {
81                         short_channel_id, payment_relay, payment_constraints, intro_node_blinding_point, features,
82                 } => {
83                         let (amt_to_forward, outgoing_cltv_value) = check_blinded_forward(
84                                 msg.amount_msat, msg.cltv_expiry, &payment_relay, &payment_constraints, &features
85                         ).map_err(|()| {
86                                 // We should be returning malformed here if `msg.blinding_point` is set, but this is
87                                 // unreachable right now since we checked it in `decode_update_add_htlc_onion`.
88                                 InboundOnionErr {
89                                         msg: "Underflow calculating outbound amount or cltv value for blinded forward",
90                                         err_code: INVALID_ONION_BLINDING,
91                                         err_data: vec![0; 32],
92                                 }
93                         })?;
94                         (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(intro_node_blinding_point))
95                 },
96                 msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
97                         return Err(InboundOnionErr {
98                                 msg: "Final Node OnionHopData provided for us as an intermediary node",
99                                 err_code: 0x4000 | 22,
100                                 err_data: Vec::new(),
101                         }),
102         };
103
104         Ok(PendingHTLCInfo {
105                 routing: PendingHTLCRouting::Forward {
106                         onion_packet: outgoing_packet,
107                         short_channel_id,
108                         blinded: inbound_blinding_point.map(|bp| BlindedForward { inbound_blinding_point: bp }),
109                 },
110                 payment_hash: msg.payment_hash,
111                 incoming_shared_secret: shared_secret,
112                 incoming_amt_msat: Some(msg.amount_msat),
113                 outgoing_amt_msat: amt_to_forward,
114                 outgoing_cltv_value,
115                 skimmed_fee_msat: None,
116         })
117 }
118
119 pub(super) fn create_recv_pending_htlc_info(
120         hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
121         amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
122         counterparty_skimmed_fee_msat: Option<u64>, current_height: u32, accept_mpp_keysend: bool,
123 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
124         let (
125                 payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value,
126                 payment_metadata, requires_blinded_error
127         ) = match hop_data {
128                 msgs::InboundOnionPayload::Receive {
129                         payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
130                 } =>
131                         (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata,
132                          false),
133                 msgs::InboundOnionPayload::BlindedReceive {
134                         amt_msat, total_msat, outgoing_cltv_value, payment_secret, intro_node_blinding_point,
135                         payment_constraints, ..
136                 } => {
137                         check_blinded_payment_constraints(amt_msat, cltv_expiry, &payment_constraints)
138                                 .map_err(|()| {
139                                         InboundOnionErr {
140                                                 err_code: INVALID_ONION_BLINDING,
141                                                 err_data: vec![0; 32],
142                                                 msg: "Amount or cltv_expiry violated blinded payment constraints",
143                                         }
144                                 })?;
145                         let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
146                         (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None,
147                          intro_node_blinding_point.is_none())
148                 }
149                 msgs::InboundOnionPayload::Forward { .. } => {
150                         return Err(InboundOnionErr {
151                                 err_code: 0x4000|22,
152                                 err_data: Vec::new(),
153                                 msg: "Got non final data with an HMAC of 0",
154                         })
155                 },
156                 msgs::InboundOnionPayload::BlindedForward { .. } => {
157                         return Err(InboundOnionErr {
158                                 err_code: INVALID_ONION_BLINDING,
159                                 err_data: vec![0; 32],
160                                 msg: "Got blinded non final data with an HMAC of 0",
161                         })
162                 }
163         };
164         // final_incorrect_cltv_expiry
165         if outgoing_cltv_value > cltv_expiry {
166                 return Err(InboundOnionErr {
167                         msg: "Upstream node set CLTV to less than the CLTV set by the sender",
168                         err_code: 18,
169                         err_data: cltv_expiry.to_be_bytes().to_vec()
170                 })
171         }
172         // final_expiry_too_soon
173         // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
174         // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
175         //
176         // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
177         // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
178         // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
179         if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
180                 let mut err_data = Vec::with_capacity(12);
181                 err_data.extend_from_slice(&amt_msat.to_be_bytes());
182                 err_data.extend_from_slice(&current_height.to_be_bytes());
183                 return Err(InboundOnionErr {
184                         err_code: 0x4000 | 15, err_data,
185                         msg: "The final CLTV expiry is too soon to handle",
186                 });
187         }
188         if (!allow_underpay && onion_amt_msat > amt_msat) ||
189                 (allow_underpay && onion_amt_msat >
190                  amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
191         {
192                 return Err(InboundOnionErr {
193                         err_code: 19,
194                         err_data: amt_msat.to_be_bytes().to_vec(),
195                         msg: "Upstream node sent less than we were supposed to receive in payment",
196                 });
197         }
198
199         let routing = if let Some(payment_preimage) = keysend_preimage {
200                 // We need to check that the sender knows the keysend preimage before processing this
201                 // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
202                 // could discover the final destination of X, by probing the adjacent nodes on the route
203                 // with a keysend payment of identical payment hash to X and observing the processing
204                 // time discrepancies due to a hash collision with X.
205                 let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
206                 if hashed_preimage != payment_hash {
207                         return Err(InboundOnionErr {
208                                 err_code: 0x4000|22,
209                                 err_data: Vec::new(),
210                                 msg: "Payment preimage didn't match payment hash",
211                         });
212                 }
213                 if !accept_mpp_keysend && payment_data.is_some() {
214                         return Err(InboundOnionErr {
215                                 err_code: 0x4000|22,
216                                 err_data: Vec::new(),
217                                 msg: "We don't support MPP keysend payments",
218                         });
219                 }
220                 PendingHTLCRouting::ReceiveKeysend {
221                         payment_data,
222                         payment_preimage,
223                         payment_metadata,
224                         incoming_cltv_expiry: outgoing_cltv_value,
225                         custom_tlvs,
226                 }
227         } else if let Some(data) = payment_data {
228                 PendingHTLCRouting::Receive {
229                         payment_data: data,
230                         payment_metadata,
231                         incoming_cltv_expiry: outgoing_cltv_value,
232                         phantom_shared_secret,
233                         custom_tlvs,
234                         requires_blinded_error,
235                 }
236         } else {
237                 return Err(InboundOnionErr {
238                         err_code: 0x4000|0x2000|3,
239                         err_data: Vec::new(),
240                         msg: "We require payment_secrets",
241                 });
242         };
243         Ok(PendingHTLCInfo {
244                 routing,
245                 payment_hash,
246                 incoming_shared_secret: shared_secret,
247                 incoming_amt_msat: Some(amt_msat),
248                 outgoing_amt_msat: onion_amt_msat,
249                 outgoing_cltv_value,
250                 skimmed_fee_msat: counterparty_skimmed_fee_msat,
251         })
252 }
253
254 /// Peel one layer off an incoming onion, returning a [`PendingHTLCInfo`] that contains information
255 /// about the intended next-hop for the HTLC.
256 ///
257 /// This does all the relevant context-free checks that LDK requires for payment relay or
258 /// acceptance. If the payment is to be received, and the amount matches the expected amount for
259 /// a given invoice, this indicates the [`msgs::UpdateAddHTLC`], once fully committed in the
260 /// channel, will generate an [`Event::PaymentClaimable`].
261 ///
262 /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
263 pub fn peel_payment_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
264         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
265         cur_height: u32, accept_mpp_keysend: bool, allow_skimmed_fees: bool,
266 ) -> Result<PendingHTLCInfo, InboundOnionErr>
267 where
268         NS::Target: NodeSigner,
269         L::Target: Logger,
270 {
271         let (hop, shared_secret, next_packet_details_opt) =
272                 decode_incoming_update_add_htlc_onion(msg, node_signer, logger, secp_ctx
273         ).map_err(|e| {
274                 let (err_code, err_data) = match e {
275                         HTLCFailureMsg::Malformed(m) => (m.failure_code, Vec::new()),
276                         HTLCFailureMsg::Relay(r) => (0x4000 | 22, r.reason.data),
277                 };
278                 let msg = "Failed to decode update add htlc onion";
279                 InboundOnionErr { msg, err_code, err_data }
280         })?;
281         Ok(match hop {
282                 onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
283                         let NextPacketDetails {
284                                 next_packet_pubkey, outgoing_amt_msat: _, outgoing_scid: _, outgoing_cltv_value
285                         } = match next_packet_details_opt {
286                                 Some(next_packet_details) => next_packet_details,
287                                 // Forward should always include the next hop details
288                                 None => return Err(InboundOnionErr {
289                                         msg: "Failed to decode update add htlc onion",
290                                         err_code: 0x4000 | 22,
291                                         err_data: Vec::new(),
292                                 }),
293                         };
294
295                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
296                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
297                         ) {
298                                 return Err(InboundOnionErr {
299                                         msg: err_msg,
300                                         err_code: code,
301                                         err_data: Vec::new(),
302                                 });
303                         }
304
305                         // TODO: If this is potentially a phantom payment we should decode the phantom payment
306                         // onion here and check it.
307
308                         create_fwd_pending_htlc_info(
309                                 msg, next_hop_data, next_hop_hmac, new_packet_bytes, shared_secret,
310                                 Some(next_packet_pubkey)
311                         )?
312                 },
313                 onion_utils::Hop::Receive(received_data) => {
314                         create_recv_pending_htlc_info(
315                                 received_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry,
316                                 None, allow_skimmed_fees, msg.skimmed_fee_msat, cur_height, accept_mpp_keysend,
317                         )?
318                 }
319         })
320 }
321
322 pub(super) struct NextPacketDetails {
323         pub(super) next_packet_pubkey: Result<PublicKey, secp256k1::Error>,
324         pub(super) outgoing_scid: u64,
325         pub(super) outgoing_amt_msat: u64,
326         pub(super) outgoing_cltv_value: u32,
327 }
328
329 pub(super) fn decode_incoming_update_add_htlc_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
330         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
331 ) -> Result<(onion_utils::Hop, [u8; 32], Option<NextPacketDetails>), HTLCFailureMsg>
332 where
333         NS::Target: NodeSigner,
334         L::Target: Logger,
335 {
336         macro_rules! return_malformed_err {
337                 ($msg: expr, $err_code: expr) => {
338                         {
339                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
340                                 let (sha256_of_onion, failure_code) = if msg.blinding_point.is_some() {
341                                         ([0; 32], INVALID_ONION_BLINDING)
342                                 } else {
343                                         (Sha256::hash(&msg.onion_routing_packet.hop_data).to_byte_array(), $err_code)
344                                 };
345                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
346                                         channel_id: msg.channel_id,
347                                         htlc_id: msg.htlc_id,
348                                         sha256_of_onion,
349                                         failure_code,
350                                 }));
351                         }
352                 }
353         }
354
355         if let Err(_) = msg.onion_routing_packet.public_key {
356                 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
357         }
358
359         let blinded_node_id_tweak = msg.blinding_point.map(|bp| {
360                 let blinded_tlvs_ss = node_signer.ecdh(Recipient::Node, &bp, None).unwrap().secret_bytes();
361                 let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
362                 hmac.input(blinded_tlvs_ss.as_ref());
363                 Scalar::from_be_bytes(Hmac::from_engine(hmac).to_byte_array()).unwrap()
364         });
365         let shared_secret = node_signer.ecdh(
366                 Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), blinded_node_id_tweak.as_ref()
367         ).unwrap().secret_bytes();
368
369         if msg.onion_routing_packet.version != 0 {
370                 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
371                 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
372                 //the hash doesn't really serve any purpose - in the case of hashing all data, the
373                 //receiving node would have to brute force to figure out which version was put in the
374                 //packet by the node that send us the message, in the case of hashing the hop_data, the
375                 //node knows the HMAC matched, so they already know what is there...
376                 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
377         }
378         macro_rules! return_err {
379                 ($msg: expr, $err_code: expr, $data: expr) => {
380                         {
381                                 if msg.blinding_point.is_some() {
382                                         return_malformed_err!($msg, INVALID_ONION_BLINDING)
383                                 }
384
385                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
386                                 return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
387                                         channel_id: msg.channel_id,
388                                         htlc_id: msg.htlc_id,
389                                         reason: HTLCFailReason::reason($err_code, $data.to_vec())
390                                                 .get_encrypted_failure_packet(&shared_secret, &None),
391                                 }));
392                         }
393                 }
394         }
395
396         let next_hop = match onion_utils::decode_next_payment_hop(
397                 shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
398                 msg.payment_hash, msg.blinding_point, node_signer
399         ) {
400                 Ok(res) => res,
401                 Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
402                         return_malformed_err!(err_msg, err_code);
403                 },
404                 Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
405                         return_err!(err_msg, err_code, &[0; 0]);
406                 },
407         };
408
409         let next_packet_details = match next_hop {
410                 onion_utils::Hop::Forward {
411                         next_hop_data: msgs::InboundOnionPayload::Forward {
412                                 short_channel_id, amt_to_forward, outgoing_cltv_value
413                         }, ..
414                 } => {
415                         let next_packet_pubkey = onion_utils::next_hop_pubkey(secp_ctx,
416                                 msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
417                         NextPacketDetails {
418                                 next_packet_pubkey, outgoing_scid: short_channel_id,
419                                 outgoing_amt_msat: amt_to_forward, outgoing_cltv_value
420                         }
421                 },
422                 onion_utils::Hop::Forward {
423                         next_hop_data: msgs::InboundOnionPayload::BlindedForward {
424                                 short_channel_id, ref payment_relay, ref payment_constraints, ref features, ..
425                         }, ..
426                 } => {
427                         let (amt_to_forward, outgoing_cltv_value) = match check_blinded_forward(
428                                 msg.amount_msat, msg.cltv_expiry, &payment_relay, &payment_constraints, &features
429                         ) {
430                                 Ok((amt, cltv)) => (amt, cltv),
431                                 Err(()) => {
432                                         return_err!("Underflow calculating outbound amount or cltv value for blinded forward",
433                                                 INVALID_ONION_BLINDING, &[0; 32]);
434                                 }
435                         };
436                         let next_packet_pubkey = onion_utils::next_hop_pubkey(&secp_ctx,
437                                 msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
438                         NextPacketDetails {
439                                 next_packet_pubkey, outgoing_scid: short_channel_id, outgoing_amt_msat: amt_to_forward,
440                                 outgoing_cltv_value
441                         }
442                 },
443                 onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
444                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
445                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
446                 {
447                         return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
448                 }
449         };
450
451         Ok((next_hop, shared_secret, Some(next_packet_details)))
452 }
453
454 pub(super) fn check_incoming_htlc_cltv(
455         cur_height: u32, outgoing_cltv_value: u32, cltv_expiry: u32
456 ) -> Result<(), (&'static str, u16)> {
457         if (cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
458                 return Err((
459                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
460                         0x1000 | 13, // incorrect_cltv_expiry
461                 ));
462         }
463         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
464         // but we want to be robust wrt to counterparty packet sanitization (see
465         // HTLC_FAIL_BACK_BUFFER rationale).
466         if cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
467                 return Err(("CLTV expiry is too close", 0x1000 | 14));
468         }
469         if cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
470                 return Err(("CLTV expiry is too far in the future", 21));
471         }
472         // If the HTLC expires ~now, don't bother trying to forward it to our
473         // counterparty. They should fail it anyway, but we don't want to bother with
474         // the round-trips or risk them deciding they definitely want the HTLC and
475         // force-closing to ensure they get it if we're offline.
476         // We previously had a much more aggressive check here which tried to ensure
477         // our counterparty receives an HTLC which has *our* risk threshold met on it,
478         // but there is no need to do that, and since we're a bit conservative with our
479         // risk threshold it just results in failing to forward payments.
480         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
481                 return Err(("Outgoing CLTV value is too soon", 0x1000 | 14));
482         }
483
484         Ok(())
485 }
486
487 #[cfg(test)]
488 mod tests {
489         use bitcoin::hashes::Hash;
490         use bitcoin::hashes::sha256::Hash as Sha256;
491         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
492         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
493         use crate::ln::ChannelId;
494         use crate::ln::channelmanager::RecipientOnionFields;
495         use crate::ln::features::{ChannelFeatures, NodeFeatures};
496         use crate::ln::msgs;
497         use crate::ln::onion_utils::create_payment_onion;
498         use crate::routing::router::{Path, RouteHop};
499         use crate::util::test_utils;
500
501         #[test]
502         fn fail_construct_onion_on_too_big_payloads() {
503                 // Ensure that if we call `construct_onion_packet` and friends where payloads are too large for
504                 // the allotted packet length, we'll fail to construct. Previously, senders would happily
505                 // construct invalid packets by array-shifting the final node's HMAC out of the packet when
506                 // adding an intermediate onion layer, causing the receiver to error with "final payload
507                 // provided for us as an intermediate node."
508                 let secp_ctx = Secp256k1::new();
509                 let bob = crate::sign::KeysManager::new(&[2; 32], 42, 42);
510                 let bob_pk = PublicKey::from_secret_key(&secp_ctx, &bob.get_node_secret_key());
511                 let charlie = crate::sign::KeysManager::new(&[3; 32], 42, 42);
512                 let charlie_pk = PublicKey::from_secret_key(&secp_ctx, &charlie.get_node_secret_key());
513
514                 let (
515                         session_priv, total_amt_msat, cur_height, mut recipient_onion, keysend_preimage, payment_hash,
516                         prng_seed, hops, ..
517                 ) = payment_onion_args(bob_pk, charlie_pk);
518
519                 // Ensure the onion will not fit all the payloads by adding a large custom TLV.
520                 recipient_onion.custom_tlvs.push((13377331, vec![0; 1156]));
521
522                 let path = Path { hops, blinded_tail: None, };
523                 let onion_keys = super::onion_utils::construct_onion_keys(&secp_ctx, &path, &session_priv).unwrap();
524                 let (onion_payloads, ..) = super::onion_utils::build_onion_payloads(
525                         &path, total_amt_msat, recipient_onion, cur_height + 1, &Some(keysend_preimage)
526                 ).unwrap();
527
528                 assert!(super::onion_utils::construct_onion_packet(
529                                 onion_payloads, onion_keys, prng_seed, &payment_hash
530                 ).is_err());
531         }
532
533         #[test]
534         fn test_peel_payment_onion() {
535                 use super::*;
536                 let secp_ctx = Secp256k1::new();
537
538                 let bob = crate::sign::KeysManager::new(&[2; 32], 42, 42);
539                 let bob_pk = PublicKey::from_secret_key(&secp_ctx, &bob.get_node_secret_key());
540                 let charlie = crate::sign::KeysManager::new(&[3; 32], 42, 42);
541                 let charlie_pk = PublicKey::from_secret_key(&secp_ctx, &charlie.get_node_secret_key());
542
543                 let (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
544                         prng_seed, hops, recipient_amount, pay_secret) = payment_onion_args(bob_pk, charlie_pk);
545
546                 let path = Path {
547                         hops: hops,
548                         blinded_tail: None,
549                 };
550
551                 let (onion, amount_msat, cltv_expiry) = create_payment_onion(
552                         &secp_ctx, &path, &session_priv, total_amt_msat, recipient_onion, cur_height,
553                         &payment_hash, &Some(preimage), prng_seed
554                 ).unwrap();
555
556                 let msg = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, onion);
557                 let logger = test_utils::TestLogger::with_id("bob".to_string());
558
559                 let peeled = peel_payment_onion(&msg, &&bob, &&logger, &secp_ctx, cur_height, true, false)
560                         .map_err(|e| e.msg).unwrap();
561
562                 let next_onion = match peeled.routing {
563                         PendingHTLCRouting::Forward { onion_packet, .. } => {
564                                 onion_packet
565                         },
566                         _ => panic!("expected a forwarded onion"),
567                 };
568
569                 let msg2 = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, next_onion);
570                 let peeled2 = peel_payment_onion(&msg2, &&charlie, &&logger, &secp_ctx, cur_height, true, false)
571                         .map_err(|e| e.msg).unwrap();
572
573                 match peeled2.routing {
574                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, payment_data, incoming_cltv_expiry, .. } => {
575                                 assert_eq!(payment_preimage, preimage);
576                                 assert_eq!(peeled2.outgoing_amt_msat, recipient_amount);
577                                 assert_eq!(incoming_cltv_expiry, peeled2.outgoing_cltv_value);
578                                 let msgs::FinalOnionHopData{total_msat, payment_secret} = payment_data.unwrap();
579                                 assert_eq!(total_msat, total_amt_msat);
580                                 assert_eq!(payment_secret, pay_secret);
581                         },
582                         _ => panic!("expected a received keysend"),
583                 };
584         }
585
586         fn make_update_add_msg(
587                 amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash,
588                 onion_routing_packet: msgs::OnionPacket
589         ) -> msgs::UpdateAddHTLC {
590                 msgs::UpdateAddHTLC {
591                         channel_id: ChannelId::from_bytes([0; 32]),
592                         htlc_id: 0,
593                         amount_msat,
594                         cltv_expiry,
595                         payment_hash,
596                         onion_routing_packet,
597                         skimmed_fee_msat: None,
598                         blinding_point: None,
599                 }
600         }
601
602         fn payment_onion_args(hop_pk: PublicKey, recipient_pk: PublicKey) -> (
603                 SecretKey, u64, u32, RecipientOnionFields, PaymentPreimage, PaymentHash, [u8; 32],
604                 Vec<RouteHop>, u64, PaymentSecret,
605         ) {
606                 let session_priv_bytes = [42; 32];
607                 let session_priv = SecretKey::from_slice(&session_priv_bytes).unwrap();
608                 let total_amt_msat = 1000;
609                 let cur_height = 1000;
610                 let pay_secret = PaymentSecret([99; 32]);
611                 let recipient_onion = RecipientOnionFields::secret_only(pay_secret);
612                 let preimage_bytes = [43; 32];
613                 let preimage = PaymentPreimage(preimage_bytes);
614                 let rhash_bytes = Sha256::hash(&preimage_bytes).to_byte_array();
615                 let payment_hash = PaymentHash(rhash_bytes);
616                 let prng_seed = [44; 32];
617
618                 // make a route alice -> bob -> charlie
619                 let hop_fee = 1;
620                 let recipient_amount = total_amt_msat - hop_fee;
621                 let hops = vec![
622                         RouteHop {
623                                 pubkey: hop_pk,
624                                 fee_msat: hop_fee,
625                                 cltv_expiry_delta: 42,
626                                 short_channel_id: 1,
627                                 node_features: NodeFeatures::empty(),
628                                 channel_features: ChannelFeatures::empty(),
629                                 maybe_announced_channel: false,
630                         },
631                         RouteHop {
632                                 pubkey: recipient_pk,
633                                 fee_msat: recipient_amount,
634                                 cltv_expiry_delta: 42,
635                                 short_channel_id: 2,
636                                 node_features: NodeFeatures::empty(),
637                                 channel_features: ChannelFeatures::empty(),
638                                 maybe_announced_channel: false,
639                         }
640                 ];
641
642                 (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
643                         prng_seed, hops, recipient_amount, pay_secret)
644         }
645
646 }