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