d191c470373256d4424e6a47ffd1b5f740a2a08c
[rust-lightning] / lightning / src / ln / onion_payment.rs
1 //! Utilities for channelmanager.rs
2 //!
3 //! Includes a public [`peel_payment_onion`] function for use by external projects or libraries.
4
5 use bitcoin::hashes::Hash;
6 use bitcoin::hashes::sha256::Hash as Sha256;
7 use bitcoin::secp256k1::{self, Secp256k1, PublicKey};
8
9 use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
10 use crate::ln::PaymentHash;
11 use crate::ln::channelmanager::{CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
12 use crate::ln::msgs;
13 use crate::ln::onion_utils;
14 use crate::ln::onion_utils::HTLCFailReason;
15 use crate::sign::{NodeSigner, Recipient};
16 use crate::util::logger::Logger;
17
18 use crate::prelude::*;
19 use core::ops::Deref;
20
21 /// Invalid inbound onion payment.
22 pub struct InboundOnionErr {
23         /// BOLT 4 error code.
24         pub err_code: u16,
25         /// Data attached to this error.
26         pub err_data: Vec<u8>,
27         /// Error message text.
28         pub msg: &'static str,
29 }
30
31 pub(super) fn create_fwd_pending_htlc_info(
32         msg: &msgs::UpdateAddHTLC, hop_data: msgs::InboundOnionPayload, hop_hmac: [u8; 32],
33         new_packet_bytes: [u8; onion_utils::ONION_DATA_LEN], shared_secret: [u8; 32],
34         next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>
35 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
36         debug_assert!(next_packet_pubkey_opt.is_some());
37         let outgoing_packet = msgs::OnionPacket {
38                 version: 0,
39                 public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
40                 hop_data: new_packet_bytes,
41                 hmac: hop_hmac,
42         };
43
44         let (short_channel_id, amt_to_forward, outgoing_cltv_value) = match hop_data {
45                 msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
46                         (short_channel_id, amt_to_forward, outgoing_cltv_value),
47                 msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
48                         return Err(InboundOnionErr {
49                                 msg: "Final Node OnionHopData provided for us as an intermediary node",
50                                 err_code: 0x4000 | 22,
51                                 err_data: Vec::new(),
52                         }),
53         };
54
55         Ok(PendingHTLCInfo {
56                 routing: PendingHTLCRouting::Forward {
57                         onion_packet: outgoing_packet,
58                         short_channel_id,
59                 },
60                 payment_hash: msg.payment_hash,
61                 incoming_shared_secret: shared_secret,
62                 incoming_amt_msat: Some(msg.amount_msat),
63                 outgoing_amt_msat: amt_to_forward,
64                 outgoing_cltv_value,
65                 skimmed_fee_msat: None,
66         })
67 }
68
69 pub(super) fn create_recv_pending_htlc_info(
70         hop_data: msgs::InboundOnionPayload, shared_secret: [u8; 32], payment_hash: PaymentHash,
71         amt_msat: u64, cltv_expiry: u32, phantom_shared_secret: Option<[u8; 32]>, allow_underpay: bool,
72         counterparty_skimmed_fee_msat: Option<u64>, current_height: u32, accept_mpp_keysend: bool,
73 ) -> Result<PendingHTLCInfo, InboundOnionErr> {
74         let (payment_data, keysend_preimage, custom_tlvs, onion_amt_msat, outgoing_cltv_value, payment_metadata) = match hop_data {
75                 msgs::InboundOnionPayload::Receive {
76                         payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata, ..
77                 } =>
78                         (payment_data, keysend_preimage, custom_tlvs, amt_msat, outgoing_cltv_value, payment_metadata),
79                 msgs::InboundOnionPayload::BlindedReceive {
80                         amt_msat, total_msat, outgoing_cltv_value, payment_secret, ..
81                 } => {
82                         let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
83                         (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
84                 }
85                 msgs::InboundOnionPayload::Forward { .. } => {
86                         return Err(InboundOnionErr {
87                                 err_code: 0x4000|22,
88                                 err_data: Vec::new(),
89                                 msg: "Got non final data with an HMAC of 0",
90                         })
91                 },
92         };
93         // final_incorrect_cltv_expiry
94         if outgoing_cltv_value > cltv_expiry {
95                 return Err(InboundOnionErr {
96                         msg: "Upstream node set CLTV to less than the CLTV set by the sender",
97                         err_code: 18,
98                         err_data: cltv_expiry.to_be_bytes().to_vec()
99                 })
100         }
101         // final_expiry_too_soon
102         // We have to have some headroom to broadcast on chain if we have the preimage, so make sure
103         // we have at least HTLC_FAIL_BACK_BUFFER blocks to go.
104         //
105         // Also, ensure that, in the case of an unknown preimage for the received payment hash, our
106         // payment logic has enough time to fail the HTLC backward before our onchain logic triggers a
107         // channel closure (see HTLC_FAIL_BACK_BUFFER rationale).
108         if cltv_expiry <= current_height + HTLC_FAIL_BACK_BUFFER + 1 {
109                 let mut err_data = Vec::with_capacity(12);
110                 err_data.extend_from_slice(&amt_msat.to_be_bytes());
111                 err_data.extend_from_slice(&current_height.to_be_bytes());
112                 return Err(InboundOnionErr {
113                         err_code: 0x4000 | 15, err_data,
114                         msg: "The final CLTV expiry is too soon to handle",
115                 });
116         }
117         if (!allow_underpay && onion_amt_msat > amt_msat) ||
118                 (allow_underpay && onion_amt_msat >
119                  amt_msat.saturating_add(counterparty_skimmed_fee_msat.unwrap_or(0)))
120         {
121                 return Err(InboundOnionErr {
122                         err_code: 19,
123                         err_data: amt_msat.to_be_bytes().to_vec(),
124                         msg: "Upstream node sent less than we were supposed to receive in payment",
125                 });
126         }
127
128         let routing = if let Some(payment_preimage) = keysend_preimage {
129                 // We need to check that the sender knows the keysend preimage before processing this
130                 // payment further. Otherwise, an intermediary routing hop forwarding non-keysend-HTLC X
131                 // could discover the final destination of X, by probing the adjacent nodes on the route
132                 // with a keysend payment of identical payment hash to X and observing the processing
133                 // time discrepancies due to a hash collision with X.
134                 let hashed_preimage = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
135                 if hashed_preimage != payment_hash {
136                         return Err(InboundOnionErr {
137                                 err_code: 0x4000|22,
138                                 err_data: Vec::new(),
139                                 msg: "Payment preimage didn't match payment hash",
140                         });
141                 }
142                 if !accept_mpp_keysend && payment_data.is_some() {
143                         return Err(InboundOnionErr {
144                                 err_code: 0x4000|22,
145                                 err_data: Vec::new(),
146                                 msg: "We don't support MPP keysend payments",
147                         });
148                 }
149                 PendingHTLCRouting::ReceiveKeysend {
150                         payment_data,
151                         payment_preimage,
152                         payment_metadata,
153                         incoming_cltv_expiry: outgoing_cltv_value,
154                         custom_tlvs,
155                 }
156         } else if let Some(data) = payment_data {
157                 PendingHTLCRouting::Receive {
158                         payment_data: data,
159                         payment_metadata,
160                         incoming_cltv_expiry: outgoing_cltv_value,
161                         phantom_shared_secret,
162                         custom_tlvs,
163                 }
164         } else {
165                 return Err(InboundOnionErr {
166                         err_code: 0x4000|0x2000|3,
167                         err_data: Vec::new(),
168                         msg: "We require payment_secrets",
169                 });
170         };
171         Ok(PendingHTLCInfo {
172                 routing,
173                 payment_hash,
174                 incoming_shared_secret: shared_secret,
175                 incoming_amt_msat: Some(amt_msat),
176                 outgoing_amt_msat: onion_amt_msat,
177                 outgoing_cltv_value,
178                 skimmed_fee_msat: counterparty_skimmed_fee_msat,
179         })
180 }
181
182 /// Peel one layer off an incoming onion, returning [`PendingHTLCInfo`] (either Forward or Receive).
183 /// This does all the relevant context-free checks that LDK requires for payment relay or
184 /// acceptance. If the payment is to be received, and the amount matches the expected amount for
185 /// a given invoice, this indicates the [`msgs::UpdateAddHTLC`], once fully committed in the
186 /// channel, will generate an [`Event::PaymentClaimable`].
187 ///
188 /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
189 pub fn peel_payment_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
190         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
191         cur_height: u32, accept_mpp_keysend: bool,
192 ) -> Result<PendingHTLCInfo, InboundOnionErr>
193 where
194         NS::Target: NodeSigner,
195         L::Target: Logger,
196 {
197         let (hop, shared_secret, next_packet_details_opt) =
198                 decode_incoming_update_add_htlc_onion(msg, node_signer, logger, secp_ctx
199         ).map_err(|e| {
200                 let (err_code, err_data) = match e {
201                         HTLCFailureMsg::Malformed(m) => (m.failure_code, Vec::new()),
202                         HTLCFailureMsg::Relay(r) => (0x4000 | 22, r.reason.data),
203                 };
204                 let msg = "Failed to decode update add htlc onion";
205                 InboundOnionErr { msg, err_code, err_data }
206         })?;
207         Ok(match hop {
208                 onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
209                         let NextPacketDetails {
210                                 next_packet_pubkey, outgoing_amt_msat: _, outgoing_scid: _, outgoing_cltv_value
211                         } = match next_packet_details_opt {
212                                 Some(next_packet_details) => next_packet_details,
213                                 // Forward should always include the next hop details
214                                 None => return Err(InboundOnionErr {
215                                         msg: "Failed to decode update add htlc onion",
216                                         err_code: 0x4000 | 22,
217                                         err_data: Vec::new(),
218                                 }),
219                         };
220
221                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
222                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
223                         ) {
224                                 return Err(InboundOnionErr {
225                                         msg: err_msg,
226                                         err_code: code,
227                                         err_data: Vec::new(),
228                                 });
229                         }
230                         create_fwd_pending_htlc_info(
231                                 msg, next_hop_data, next_hop_hmac, new_packet_bytes, shared_secret,
232                                 Some(next_packet_pubkey)
233                         )?
234                 },
235                 onion_utils::Hop::Receive(received_data) => {
236                         create_recv_pending_htlc_info(
237                                 received_data, shared_secret, msg.payment_hash, msg.amount_msat, msg.cltv_expiry,
238                                 None, false, msg.skimmed_fee_msat, cur_height, accept_mpp_keysend,
239                         )?
240                 }
241         })
242 }
243
244 pub(super) struct NextPacketDetails {
245         pub(super) next_packet_pubkey: Result<PublicKey, secp256k1::Error>,
246         pub(super) outgoing_scid: u64,
247         pub(super) outgoing_amt_msat: u64,
248         pub(super) outgoing_cltv_value: u32,
249 }
250
251 pub(super) fn decode_incoming_update_add_htlc_onion<NS: Deref, L: Deref, T: secp256k1::Verification>(
252         msg: &msgs::UpdateAddHTLC, node_signer: &NS, logger: &L, secp_ctx: &Secp256k1<T>,
253 ) -> Result<(onion_utils::Hop, [u8; 32], Option<NextPacketDetails>), HTLCFailureMsg>
254 where
255         NS::Target: NodeSigner,
256         L::Target: Logger,
257 {
258         macro_rules! return_malformed_err {
259                 ($msg: expr, $err_code: expr) => {
260                         {
261                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
262                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
263                                         channel_id: msg.channel_id,
264                                         htlc_id: msg.htlc_id,
265                                         sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).to_byte_array(),
266                                         failure_code: $err_code,
267                                 }));
268                         }
269                 }
270         }
271
272         if let Err(_) = msg.onion_routing_packet.public_key {
273                 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
274         }
275
276         let shared_secret = node_signer.ecdh(
277                 Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
278         ).unwrap().secret_bytes();
279
280         if msg.onion_routing_packet.version != 0 {
281                 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
282                 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
283                 //the hash doesn't really serve any purpose - in the case of hashing all data, the
284                 //receiving node would have to brute force to figure out which version was put in the
285                 //packet by the node that send us the message, in the case of hashing the hop_data, the
286                 //node knows the HMAC matched, so they already know what is there...
287                 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
288         }
289         macro_rules! return_err {
290                 ($msg: expr, $err_code: expr, $data: expr) => {
291                         {
292                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
293                                 return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
294                                         channel_id: msg.channel_id,
295                                         htlc_id: msg.htlc_id,
296                                         reason: HTLCFailReason::reason($err_code, $data.to_vec())
297                                                 .get_encrypted_failure_packet(&shared_secret, &None),
298                                 }));
299                         }
300                 }
301         }
302
303         let next_hop = match onion_utils::decode_next_payment_hop(
304                 shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
305                 msg.payment_hash, node_signer
306         ) {
307                 Ok(res) => res,
308                 Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
309                         return_malformed_err!(err_msg, err_code);
310                 },
311                 Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
312                         return_err!(err_msg, err_code, &[0; 0]);
313                 },
314         };
315
316         let next_packet_details = match next_hop {
317                 onion_utils::Hop::Forward {
318                         next_hop_data: msgs::InboundOnionPayload::Forward {
319                                 short_channel_id, amt_to_forward, outgoing_cltv_value
320                         }, ..
321                 } => {
322                         let next_packet_pubkey = onion_utils::next_hop_pubkey(secp_ctx,
323                                 msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
324                         NextPacketDetails {
325                                 next_packet_pubkey, outgoing_scid: short_channel_id,
326                                 outgoing_amt_msat: amt_to_forward, outgoing_cltv_value
327                         }
328                 },
329                 onion_utils::Hop::Receive { .. } => return Ok((next_hop, shared_secret, None)),
330                 onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::Receive { .. }, .. } |
331                         onion_utils::Hop::Forward { next_hop_data: msgs::InboundOnionPayload::BlindedReceive { .. }, .. } =>
332                 {
333                         return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
334                 }
335         };
336
337         Ok((next_hop, shared_secret, Some(next_packet_details)))
338 }
339
340 pub(super) fn check_incoming_htlc_cltv(
341         cur_height: u32, outgoing_cltv_value: u32, cltv_expiry: u32
342 ) -> Result<(), (&'static str, u16)> {
343         if (cltv_expiry as u64) < (outgoing_cltv_value) as u64 + MIN_CLTV_EXPIRY_DELTA as u64 {
344                 return Err((
345                         "Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta",
346                         0x1000 | 13, // incorrect_cltv_expiry
347                 ));
348         }
349         // Theoretically, channel counterparty shouldn't send us a HTLC expiring now,
350         // but we want to be robust wrt to counterparty packet sanitization (see
351         // HTLC_FAIL_BACK_BUFFER rationale).
352         if cltv_expiry <= cur_height + HTLC_FAIL_BACK_BUFFER as u32 { // expiry_too_soon
353                 return Err(("CLTV expiry is too close", 0x1000 | 14));
354         }
355         if cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
356                 return Err(("CLTV expiry is too far in the future", 21));
357         }
358         // If the HTLC expires ~now, don't bother trying to forward it to our
359         // counterparty. They should fail it anyway, but we don't want to bother with
360         // the round-trips or risk them deciding they definitely want the HTLC and
361         // force-closing to ensure they get it if we're offline.
362         // We previously had a much more aggressive check here which tried to ensure
363         // our counterparty receives an HTLC which has *our* risk threshold met on it,
364         // but there is no need to do that, and since we're a bit conservative with our
365         // risk threshold it just results in failing to forward payments.
366         if (outgoing_cltv_value) as u64 <= (cur_height + LATENCY_GRACE_PERIOD_BLOCKS) as u64 {
367                 return Err(("Outgoing CLTV value is too soon", 0x1000 | 14));
368         }
369
370         Ok(())
371 }
372
373 #[cfg(test)]
374 mod tests {
375         use bitcoin::hashes::Hash;
376         use bitcoin::hashes::sha256::Hash as Sha256;
377         use bitcoin::secp256k1::{PublicKey, SecretKey};
378         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
379         use crate::ln::ChannelId;
380         use crate::ln::channelmanager::RecipientOnionFields;
381         use crate::ln::features::{ChannelFeatures, NodeFeatures};
382         use crate::ln::msgs;
383         use crate::ln::onion_utils::create_payment_onion;
384         use crate::routing::router::{Path, RouteHop};
385         use crate::util::test_utils;
386
387         #[test]
388         fn test_peel_payment_onion() {
389                 use super::*;
390                 let secp_ctx = Secp256k1::new();
391
392                 let bob = crate::sign::KeysManager::new(&[2; 32], 42, 42);
393                 let bob_pk = PublicKey::from_secret_key(&secp_ctx, &bob.get_node_secret_key());
394                 let charlie = crate::sign::KeysManager::new(&[3; 32], 42, 42);
395                 let charlie_pk = PublicKey::from_secret_key(&secp_ctx, &charlie.get_node_secret_key());
396
397                 let (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
398                         prng_seed, hops, recipient_amount, pay_secret) = payment_onion_args(bob_pk, charlie_pk);
399
400                 let path = Path {
401                         hops: hops,
402                         blinded_tail: None,
403                 };
404
405                 let (onion, amount_msat, cltv_expiry) = create_payment_onion(
406                         &secp_ctx, &path, &session_priv, total_amt_msat, recipient_onion, cur_height,
407                         &payment_hash, &Some(preimage), prng_seed
408                 ).unwrap();
409
410                 let msg = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, onion);
411                 let logger = test_utils::TestLogger::with_id("bob".to_string());
412
413                 let peeled = peel_payment_onion(&msg, &&bob, &&logger, &secp_ctx, cur_height, true)
414                         .map_err(|e| e.msg).unwrap();
415
416                 let next_onion = match peeled.routing {
417                         PendingHTLCRouting::Forward { onion_packet, short_channel_id: _ } => {
418                                 onion_packet
419                         },
420                         _ => panic!("expected a forwarded onion"),
421                 };
422
423                 let msg2 = make_update_add_msg(amount_msat, cltv_expiry, payment_hash, next_onion);
424                 let peeled2 = peel_payment_onion(&msg2, &&charlie, &&logger, &secp_ctx, cur_height, true)
425                         .map_err(|e| e.msg).unwrap();
426
427                 match peeled2.routing {
428                         PendingHTLCRouting::ReceiveKeysend { payment_preimage, payment_data, incoming_cltv_expiry, .. } => {
429                                 assert_eq!(payment_preimage, preimage);
430                                 assert_eq!(peeled2.outgoing_amt_msat, recipient_amount);
431                                 assert_eq!(incoming_cltv_expiry, peeled2.outgoing_cltv_value);
432                                 let msgs::FinalOnionHopData{total_msat, payment_secret} = payment_data.unwrap();
433                                 assert_eq!(total_msat, total_amt_msat);
434                                 assert_eq!(payment_secret, pay_secret);
435                         },
436                         _ => panic!("expected a received keysend"),
437                 };
438         }
439
440         fn make_update_add_msg(
441                 amount_msat: u64, cltv_expiry: u32, payment_hash: PaymentHash,
442                 onion_routing_packet: msgs::OnionPacket
443         ) -> msgs::UpdateAddHTLC {
444                 msgs::UpdateAddHTLC {
445                         channel_id: ChannelId::from_bytes([0; 32]),
446                         htlc_id: 0,
447                         amount_msat,
448                         cltv_expiry,
449                         payment_hash,
450                         onion_routing_packet,
451                         skimmed_fee_msat: None,
452                 }
453         }
454
455         fn payment_onion_args(hop_pk: PublicKey, recipient_pk: PublicKey) -> (
456                 SecretKey, u64, u32, RecipientOnionFields, PaymentPreimage, PaymentHash, [u8; 32],
457                 Vec<RouteHop>, u64, PaymentSecret,
458         ) {
459                 let session_priv_bytes = [42; 32];
460                 let session_priv = SecretKey::from_slice(&session_priv_bytes).unwrap();
461                 let total_amt_msat = 1000;
462                 let cur_height = 1000;
463                 let pay_secret = PaymentSecret([99; 32]);
464                 let recipient_onion = RecipientOnionFields::secret_only(pay_secret);
465                 let preimage_bytes = [43; 32];
466                 let preimage = PaymentPreimage(preimage_bytes);
467                 let rhash_bytes = Sha256::hash(&preimage_bytes).to_byte_array();
468                 let payment_hash = PaymentHash(rhash_bytes);
469                 let prng_seed = [44; 32];
470
471                 // make a route alice -> bob -> charlie
472                 let hop_fee = 1;
473                 let recipient_amount = total_amt_msat - hop_fee;
474                 let hops = vec![
475                         RouteHop {
476                                 pubkey: hop_pk,
477                                 fee_msat: hop_fee,
478                                 cltv_expiry_delta: 42,
479                                 short_channel_id: 1,
480                                 node_features: NodeFeatures::empty(),
481                                 channel_features: ChannelFeatures::empty(),
482                                 maybe_announced_channel: false,
483                         },
484                         RouteHop {
485                                 pubkey: recipient_pk,
486                                 fee_msat: recipient_amount,
487                                 cltv_expiry_delta: 42,
488                                 short_channel_id: 2,
489                                 node_features: NodeFeatures::empty(),
490                                 channel_features: ChannelFeatures::empty(),
491                                 maybe_announced_channel: false,
492                         }
493                 ];
494
495                 (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
496                         prng_seed, hops, recipient_amount, pay_secret)
497         }
498
499 }