1 //! Utilities for channelmanager.rs
3 //! Includes a public [`peel_payment_onion`] function for use by external projects or libraries.
5 use bitcoin::hashes::Hash;
6 use bitcoin::hashes::sha256::Hash as Sha256;
7 use bitcoin::secp256k1::{self, Secp256k1, PublicKey};
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};
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;
18 use crate::prelude::*;
21 /// Invalid inbound onion payment.
22 pub struct InboundOnionErr {
23 /// BOLT 4 error code.
25 /// Data attached to this error.
26 pub err_data: Vec<u8>,
27 /// Error message text.
28 pub msg: &'static str,
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 {
39 public_key: next_packet_pubkey_opt.unwrap_or(Err(secp256k1::Error::InvalidPublicKey)),
40 hop_data: new_packet_bytes,
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,
56 routing: PendingHTLCRouting::Forward {
57 onion_packet: outgoing_packet,
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,
65 skimmed_fee_msat: None,
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, ..
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, ..
82 let payment_data = msgs::FinalOnionHopData { payment_secret, total_msat };
83 (Some(payment_data), None, Vec::new(), amt_msat, outgoing_cltv_value, None)
85 msgs::InboundOnionPayload::Forward { .. } => {
86 return Err(InboundOnionErr {
89 msg: "Got non final data with an HMAC of 0",
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",
98 err_data: cltv_expiry.to_be_bytes().to_vec()
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.
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(¤t_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",
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)))
121 return Err(InboundOnionErr {
123 err_data: amt_msat.to_be_bytes().to_vec(),
124 msg: "Upstream node sent less than we were supposed to receive in payment",
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 {
138 err_data: Vec::new(),
139 msg: "Payment preimage didn't match payment hash",
142 if !accept_mpp_keysend && payment_data.is_some() {
143 return Err(InboundOnionErr {
145 err_data: Vec::new(),
146 msg: "We don't support MPP keysend payments",
149 PendingHTLCRouting::ReceiveKeysend {
153 incoming_cltv_expiry: outgoing_cltv_value,
156 } else if let Some(data) = payment_data {
157 PendingHTLCRouting::Receive {
160 incoming_cltv_expiry: outgoing_cltv_value,
161 phantom_shared_secret,
165 return Err(InboundOnionErr {
166 err_code: 0x4000|0x2000|3,
167 err_data: Vec::new(),
168 msg: "We require payment_secrets",
174 incoming_shared_secret: shared_secret,
175 incoming_amt_msat: Some(amt_msat),
176 outgoing_amt_msat: onion_amt_msat,
178 skimmed_fee_msat: counterparty_skimmed_fee_msat,
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`].
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>
194 NS::Target: NodeSigner,
197 let (hop, shared_secret, next_packet_details_opt) =
198 decode_incoming_update_add_htlc_onion(msg, node_signer, logger, secp_ctx
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),
204 let msg = "Failed to decode update add htlc onion";
205 InboundOnionErr { msg, err_code, err_data }
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(),
221 if let Err((err_msg, code)) = check_incoming_htlc_cltv(
222 cur_height, outgoing_cltv_value, msg.cltv_expiry
224 return Err(InboundOnionErr {
227 err_data: Vec::new(),
230 create_fwd_pending_htlc_info(
231 msg, next_hop_data, next_hop_hmac, new_packet_bytes, shared_secret,
232 Some(next_packet_pubkey)
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,
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,
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>
255 NS::Target: NodeSigner,
258 macro_rules! return_malformed_err {
259 ($msg: expr, $err_code: expr) => {
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,
272 if let Err(_) = msg.onion_routing_packet.public_key {
273 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
276 let shared_secret = node_signer.ecdh(
277 Recipient::Node, &msg.onion_routing_packet.public_key.unwrap(), None
278 ).unwrap().secret_bytes();
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);
289 macro_rules! return_err {
290 ($msg: expr, $err_code: expr, $data: expr) => {
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),
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
308 Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
309 return_malformed_err!(err_msg, err_code);
311 Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
312 return_err!(err_msg, err_code, &[0; 0]);
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
322 let next_packet_pubkey = onion_utils::next_hop_pubkey(secp_ctx,
323 msg.onion_routing_packet.public_key.unwrap(), &shared_secret);
325 next_packet_pubkey, outgoing_scid: short_channel_id,
326 outgoing_amt_msat: amt_to_forward, outgoing_cltv_value
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 { .. }, .. } =>
333 return_err!("Final Node OnionHopData provided for us as an intermediary node", 0x4000 | 22, &[0; 0]);
337 Ok((next_hop, shared_secret, Some(next_packet_details)))
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 {
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
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));
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));
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));
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};
383 use crate::ln::onion_utils::create_payment_onion;
384 use crate::routing::router::{Path, RouteHop};
385 use crate::util::test_utils;
388 fn test_peel_payment_onion() {
390 let secp_ctx = Secp256k1::new();
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());
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);
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
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());
413 let peeled = peel_payment_onion(&msg, &&bob, &&logger, &secp_ctx, cur_height, true)
414 .map_err(|e| e.msg).unwrap();
416 let next_onion = match peeled.routing {
417 PendingHTLCRouting::Forward { onion_packet, short_channel_id: _ } => {
420 _ => panic!("expected a forwarded onion"),
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();
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);
436 _ => panic!("expected a received keysend"),
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]),
450 onion_routing_packet,
451 skimmed_fee_msat: None,
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,
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];
471 // make a route alice -> bob -> charlie
473 let recipient_amount = total_amt_msat - hop_fee;
478 cltv_expiry_delta: 42,
480 node_features: NodeFeatures::empty(),
481 channel_features: ChannelFeatures::empty(),
482 maybe_announced_channel: false,
485 pubkey: recipient_pk,
486 fee_msat: recipient_amount,
487 cltv_expiry_delta: 42,
489 node_features: NodeFeatures::empty(),
490 channel_features: ChannelFeatures::empty(),
491 maybe_announced_channel: false,
495 (session_priv, total_amt_msat, cur_height, recipient_onion, preimage, payment_hash,
496 prng_seed, hops, recipient_amount, pay_secret)