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