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