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