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