99979ecf4a37140ef5f7375fdc2c0cc67e0eaa7b
[rust-lightning] / lightning / src / blinded_path / payment.rs
1 //! Data structures and methods for constructing [`BlindedPath`]s to send a payment over.
2 //!
3 //! [`BlindedPath`]: crate::blinded_path::BlindedPath
4
5 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
6
7 use crate::blinded_path::BlindedHop;
8 use crate::blinded_path::utils;
9 use crate::io;
10 use crate::ln::PaymentSecret;
11 use crate::ln::channelmanager::CounterpartyForwardingInfo;
12 use crate::ln::features::BlindedHopFeatures;
13 use crate::ln::msgs::DecodeError;
14 use crate::offers::invoice::BlindedPayInfo;
15 use crate::offers::offer::OfferId;
16 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, Writeable, Writer};
17
18 #[allow(unused_imports)]
19 use crate::prelude::*;
20
21 /// An intermediate node, its outbound channel, and relay parameters.
22 #[derive(Clone, Debug)]
23 pub struct ForwardNode {
24         /// The TLVs for this node's [`BlindedHop`], where the fee parameters contained within are also
25         /// used for [`BlindedPayInfo`] construction.
26         pub tlvs: ForwardTlvs,
27         /// This node's pubkey.
28         pub node_id: PublicKey,
29         /// The maximum value, in msat, that may be accepted by this node.
30         pub htlc_maximum_msat: u64,
31 }
32
33 /// Data to construct a [`BlindedHop`] for forwarding a payment.
34 #[derive(Clone, Debug)]
35 pub struct ForwardTlvs {
36         /// The short channel id this payment should be forwarded out over.
37         pub short_channel_id: u64,
38         /// Payment parameters for relaying over [`Self::short_channel_id`].
39         pub payment_relay: PaymentRelay,
40         /// Payment constraints for relaying over [`Self::short_channel_id`].
41         pub payment_constraints: PaymentConstraints,
42         /// Supported and required features when relaying a payment onion containing this object's
43         /// corresponding [`BlindedHop::encrypted_payload`].
44         ///
45         /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
46         pub features: BlindedHopFeatures,
47 }
48
49 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
50 /// may not be valid if received by another lightning implementation.
51 #[derive(Clone, Debug)]
52 pub struct ReceiveTlvs {
53         /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
54         pub payment_secret: PaymentSecret,
55         /// Constraints for the receiver of this payment.
56         pub payment_constraints: PaymentConstraints,
57         /// Context for the receiver of this payment.
58         pub payment_context: PaymentContext,
59 }
60
61 /// Data to construct a [`BlindedHop`] for sending a payment over.
62 ///
63 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
64 pub(crate) enum BlindedPaymentTlvs {
65         /// This blinded payment data is for a forwarding node.
66         Forward(ForwardTlvs),
67         /// This blinded payment data is for the receiving node.
68         Receive(ReceiveTlvs),
69 }
70
71 // Used to include forward and receive TLVs in the same iterator for encoding.
72 enum BlindedPaymentTlvsRef<'a> {
73         Forward(&'a ForwardTlvs),
74         Receive(&'a ReceiveTlvs),
75 }
76
77 /// Parameters for relaying over a given [`BlindedHop`].
78 ///
79 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
80 #[derive(Clone, Debug)]
81 pub struct PaymentRelay {
82         /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
83         pub cltv_expiry_delta: u16,
84         /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
85         /// this [`BlindedHop`], (i.e., 10,000 is 1%).
86         pub fee_proportional_millionths: u32,
87         /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
88         pub fee_base_msat: u32,
89 }
90
91 /// Constraints for relaying over a given [`BlindedHop`].
92 ///
93 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
94 #[derive(Clone, Debug)]
95 pub struct PaymentConstraints {
96         /// The maximum total CLTV that is acceptable when relaying a payment over this [`BlindedHop`].
97         pub max_cltv_expiry: u32,
98         /// The minimum value, in msat, that may be accepted by the node corresponding to this
99         /// [`BlindedHop`].
100         pub htlc_minimum_msat: u64,
101 }
102
103 /// The context of an inbound payment, which is included in a [`BlindedPath`] via [`ReceiveTlvs`]
104 /// and surfaced in [`PaymentPurpose`].
105 ///
106 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
107 /// [`PaymentPurpose`]: crate::events::PaymentPurpose
108 #[derive(Clone, Debug, Eq, PartialEq)]
109 pub enum PaymentContext {
110         /// The payment context was unknown.
111         Unknown(UnknownPaymentContext),
112
113         /// The payment was made for an invoice requested from a BOLT 12 [`Offer`].
114         ///
115         /// [`Offer`]: crate::offers::offer::Offer
116         Bolt12Offer(Bolt12OfferContext),
117 }
118
119 /// An unknown payment context.
120 #[derive(Clone, Debug, Eq, PartialEq)]
121 pub struct UnknownPaymentContext(());
122
123 /// The context of a payment made for an invoice requested from a BOLT 12 [`Offer`].
124 ///
125 /// [`Offer`]: crate::offers::offer::Offer
126 #[derive(Clone, Debug, Eq, PartialEq)]
127 pub struct Bolt12OfferContext {
128         /// The identifier of the [`Offer`].
129         ///
130         /// [`Offer`]: crate::offers::offer::Offer
131         pub offer_id: OfferId,
132 }
133
134 impl PaymentContext {
135         pub(crate) fn unknown() -> Self {
136                 PaymentContext::Unknown(UnknownPaymentContext(()))
137         }
138 }
139
140 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
141         type Error = ();
142
143         fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
144                 let CounterpartyForwardingInfo {
145                         fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
146                 } = info;
147
148                 // Avoid exposing esoteric CLTV expiry deltas
149                 let cltv_expiry_delta = match cltv_expiry_delta {
150                         0..=40 => 40,
151                         41..=80 => 80,
152                         81..=144 => 144,
153                         145..=216 => 216,
154                         _ => return Err(()),
155                 };
156
157                 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
158         }
159 }
160
161 impl Writeable for ForwardTlvs {
162         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
163                 let features_opt =
164                         if self.features == BlindedHopFeatures::empty() { None }
165                         else { Some(&self.features) };
166                 encode_tlv_stream!(w, {
167                         (2, self.short_channel_id, required),
168                         (10, self.payment_relay, required),
169                         (12, self.payment_constraints, required),
170                         (14, features_opt, option)
171                 });
172                 Ok(())
173         }
174 }
175
176 impl Writeable for ReceiveTlvs {
177         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
178                 encode_tlv_stream!(w, {
179                         (12, self.payment_constraints, required),
180                         (65536, self.payment_secret, required),
181                         (65537, self.payment_context, required)
182                 });
183                 Ok(())
184         }
185 }
186
187 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
188         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
189                 // TODO: write padding
190                 match self {
191                         Self::Forward(tlvs) => tlvs.write(w)?,
192                         Self::Receive(tlvs) => tlvs.write(w)?,
193                 }
194                 Ok(())
195         }
196 }
197
198 impl Readable for BlindedPaymentTlvs {
199         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
200                 _init_and_read_tlv_stream!(r, {
201                         (1, _padding, option),
202                         (2, scid, option),
203                         (10, payment_relay, option),
204                         (12, payment_constraints, required),
205                         (14, features, option),
206                         (65536, payment_secret, option),
207                         (65537, payment_context, (default_value, PaymentContext::unknown())),
208                 });
209                 let _padding: Option<utils::Padding> = _padding;
210
211                 if let Some(short_channel_id) = scid {
212                         if payment_secret.is_some() {
213                                 return Err(DecodeError::InvalidValue)
214                         }
215                         Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
216                                 short_channel_id,
217                                 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
218                                 payment_constraints: payment_constraints.0.unwrap(),
219                                 features: features.unwrap_or_else(BlindedHopFeatures::empty),
220                         }))
221                 } else {
222                         if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
223                         Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
224                                 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
225                                 payment_constraints: payment_constraints.0.unwrap(),
226                                 payment_context: payment_context.0.unwrap(),
227                         }))
228                 }
229         }
230 }
231
232 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
233 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
234         secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
235         payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
236 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
237         let pks = intermediate_nodes.iter().map(|node| &node.node_id)
238                 .chain(core::iter::once(&payee_node_id));
239         let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
240                 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
241         utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
242 }
243
244 /// `None` if underflow occurs.
245 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
246         let inbound_amt = inbound_amt_msat as u128;
247         let base = payment_relay.fee_base_msat as u128;
248         let prop = payment_relay.fee_proportional_millionths as u128;
249
250         let post_base_fee_inbound_amt =
251                 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
252         let mut amt_to_forward =
253                 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
254
255         let fee = ((amt_to_forward * prop) / 1_000_000) + base;
256         if inbound_amt - fee < amt_to_forward {
257                 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
258                 // in fee to compensate.
259                 amt_to_forward -= 1;
260         }
261         debug_assert_eq!(amt_to_forward + fee, inbound_amt);
262         u64::try_from(amt_to_forward).ok()
263 }
264
265 pub(super) fn compute_payinfo(
266         intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
267         min_final_cltv_expiry_delta: u16
268 ) -> Result<BlindedPayInfo, ()> {
269         let mut curr_base_fee: u64 = 0;
270         let mut curr_prop_mil: u64 = 0;
271         let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
272         for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
273                 // In the future, we'll want to take the intersection of all supported features for the
274                 // `BlindedPayInfo`, but there are no features in that context right now.
275                 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
276
277                 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
278                 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
279                 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
280                 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
281                 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
282                         .and_then(|f| f.checked_add(1_000_000 - 1))
283                         .map(|f| f / 1_000_000)
284                         .and_then(|f| f.checked_add(next_base_fee))
285                         .ok_or(())?;
286                 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
287                 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
288                         .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
289                         .and_then(|f| f.checked_add(1_000_000 - 1))
290                         .map(|f| f / 1_000_000)
291                         .and_then(|f| f.checked_sub(1_000_000))
292                         .ok_or(())?;
293
294                 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
295         }
296
297         let mut htlc_minimum_msat: u64 = 1;
298         let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
299         for node in intermediate_nodes.iter() {
300                 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
301                 // following hops for forwarding that min, since that fee amount will automatically be included
302                 // in the amount that this node receives and contribute towards reaching its min.
303                 htlc_minimum_msat = amt_to_forward_msat(
304                         core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
305                         &node.tlvs.payment_relay
306                 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
307                 htlc_maximum_msat = amt_to_forward_msat(
308                         core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
309                 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
310         }
311         htlc_minimum_msat = core::cmp::max(
312                 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
313         );
314         htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
315
316         if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
317         Ok(BlindedPayInfo {
318                 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
319                 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
320                 cltv_expiry_delta,
321                 htlc_minimum_msat,
322                 htlc_maximum_msat,
323                 features: BlindedHopFeatures::empty(),
324         })
325 }
326
327 impl Writeable for PaymentRelay {
328         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
329                 self.cltv_expiry_delta.write(w)?;
330                 self.fee_proportional_millionths.write(w)?;
331                 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
332         }
333 }
334 impl Readable for PaymentRelay {
335         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
336                 let cltv_expiry_delta: u16 = Readable::read(r)?;
337                 let fee_proportional_millionths: u32 = Readable::read(r)?;
338                 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
339                 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
340         }
341 }
342
343 impl Writeable for PaymentConstraints {
344         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
345                 self.max_cltv_expiry.write(w)?;
346                 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
347         }
348 }
349 impl Readable for PaymentConstraints {
350         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
351                 let max_cltv_expiry: u32 = Readable::read(r)?;
352                 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
353                 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
354         }
355 }
356
357 impl_writeable_tlv_based_enum!(PaymentContext,
358         ;
359         (0, Unknown),
360         (1, Bolt12Offer),
361 );
362
363 impl Writeable for UnknownPaymentContext {
364         fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
365                 Ok(())
366         }
367 }
368
369 impl Readable for UnknownPaymentContext {
370         fn read<R: io::Read>(_r: &mut R) -> Result<Self, DecodeError> {
371                 Ok(UnknownPaymentContext(()))
372         }
373 }
374
375 impl_writeable_tlv_based!(Bolt12OfferContext, {
376         (0, offer_id, required),
377 });
378
379 #[cfg(test)]
380 mod tests {
381         use bitcoin::secp256k1::PublicKey;
382         use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentContext, PaymentRelay};
383         use crate::ln::PaymentSecret;
384         use crate::ln::features::BlindedHopFeatures;
385         use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
386
387         #[test]
388         fn compute_payinfo() {
389                 // Taken from the spec example for aggregating blinded payment info. See
390                 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
391                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
392                 let intermediate_nodes = vec![ForwardNode {
393                         node_id: dummy_pk,
394                         tlvs: ForwardTlvs {
395                                 short_channel_id: 0,
396                                 payment_relay: PaymentRelay {
397                                         cltv_expiry_delta: 144,
398                                         fee_proportional_millionths: 500,
399                                         fee_base_msat: 100,
400                                 },
401                                 payment_constraints: PaymentConstraints {
402                                         max_cltv_expiry: 0,
403                                         htlc_minimum_msat: 100,
404                                 },
405                                 features: BlindedHopFeatures::empty(),
406                         },
407                         htlc_maximum_msat: u64::max_value(),
408                 }, ForwardNode {
409                         node_id: dummy_pk,
410                         tlvs: ForwardTlvs {
411                                 short_channel_id: 0,
412                                 payment_relay: PaymentRelay {
413                                         cltv_expiry_delta: 144,
414                                         fee_proportional_millionths: 500,
415                                         fee_base_msat: 100,
416                                 },
417                                 payment_constraints: PaymentConstraints {
418                                         max_cltv_expiry: 0,
419                                         htlc_minimum_msat: 1_000,
420                                 },
421                                 features: BlindedHopFeatures::empty(),
422                         },
423                         htlc_maximum_msat: u64::max_value(),
424                 }];
425                 let recv_tlvs = ReceiveTlvs {
426                         payment_secret: PaymentSecret([0; 32]),
427                         payment_constraints: PaymentConstraints {
428                                 max_cltv_expiry: 0,
429                                 htlc_minimum_msat: 1,
430                         },
431                         payment_context: PaymentContext::unknown(),
432                 };
433                 let htlc_maximum_msat = 100_000;
434                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
435                 assert_eq!(blinded_payinfo.fee_base_msat, 201);
436                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
437                 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
438                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
439                 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
440         }
441
442         #[test]
443         fn compute_payinfo_1_hop() {
444                 let recv_tlvs = ReceiveTlvs {
445                         payment_secret: PaymentSecret([0; 32]),
446                         payment_constraints: PaymentConstraints {
447                                 max_cltv_expiry: 0,
448                                 htlc_minimum_msat: 1,
449                         },
450                         payment_context: PaymentContext::unknown(),
451                 };
452                 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
453                 assert_eq!(blinded_payinfo.fee_base_msat, 0);
454                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
455                 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
456                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
457                 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
458         }
459
460         #[test]
461         fn simple_aggregated_htlc_min() {
462                 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
463                 // along the path.
464                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
465                 let intermediate_nodes = vec![ForwardNode {
466                         node_id: dummy_pk,
467                         tlvs: ForwardTlvs {
468                                 short_channel_id: 0,
469                                 payment_relay: PaymentRelay {
470                                         cltv_expiry_delta: 0,
471                                         fee_proportional_millionths: 0,
472                                         fee_base_msat: 0,
473                                 },
474                                 payment_constraints: PaymentConstraints {
475                                         max_cltv_expiry: 0,
476                                         htlc_minimum_msat: 1,
477                                 },
478                                 features: BlindedHopFeatures::empty(),
479                         },
480                         htlc_maximum_msat: u64::max_value()
481                 }, ForwardNode {
482                         node_id: dummy_pk,
483                         tlvs: ForwardTlvs {
484                                 short_channel_id: 0,
485                                 payment_relay: PaymentRelay {
486                                         cltv_expiry_delta: 0,
487                                         fee_proportional_millionths: 0,
488                                         fee_base_msat: 0,
489                                 },
490                                 payment_constraints: PaymentConstraints {
491                                         max_cltv_expiry: 0,
492                                         htlc_minimum_msat: 2_000,
493                                 },
494                                 features: BlindedHopFeatures::empty(),
495                         },
496                         htlc_maximum_msat: u64::max_value()
497                 }];
498                 let recv_tlvs = ReceiveTlvs {
499                         payment_secret: PaymentSecret([0; 32]),
500                         payment_constraints: PaymentConstraints {
501                                 max_cltv_expiry: 0,
502                                 htlc_minimum_msat: 3,
503                         },
504                         payment_context: PaymentContext::unknown(),
505                 };
506                 let htlc_maximum_msat = 100_000;
507                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
508                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
509         }
510
511         #[test]
512         fn aggregated_htlc_min() {
513                 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
514                 // max (htlc_min - following_fees) along the path.
515                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
516                 let intermediate_nodes = vec![ForwardNode {
517                         node_id: dummy_pk,
518                         tlvs: ForwardTlvs {
519                                 short_channel_id: 0,
520                                 payment_relay: PaymentRelay {
521                                         cltv_expiry_delta: 0,
522                                         fee_proportional_millionths: 500,
523                                         fee_base_msat: 1_000,
524                                 },
525                                 payment_constraints: PaymentConstraints {
526                                         max_cltv_expiry: 0,
527                                         htlc_minimum_msat: 5_000,
528                                 },
529                                 features: BlindedHopFeatures::empty(),
530                         },
531                         htlc_maximum_msat: u64::max_value()
532                 }, ForwardNode {
533                         node_id: dummy_pk,
534                         tlvs: ForwardTlvs {
535                                 short_channel_id: 0,
536                                 payment_relay: PaymentRelay {
537                                         cltv_expiry_delta: 0,
538                                         fee_proportional_millionths: 500,
539                                         fee_base_msat: 200,
540                                 },
541                                 payment_constraints: PaymentConstraints {
542                                         max_cltv_expiry: 0,
543                                         htlc_minimum_msat: 2_000,
544                                 },
545                                 features: BlindedHopFeatures::empty(),
546                         },
547                         htlc_maximum_msat: u64::max_value()
548                 }];
549                 let recv_tlvs = ReceiveTlvs {
550                         payment_secret: PaymentSecret([0; 32]),
551                         payment_constraints: PaymentConstraints {
552                                 max_cltv_expiry: 0,
553                                 htlc_minimum_msat: 1,
554                         },
555                         payment_context: PaymentContext::unknown(),
556                 };
557                 let htlc_minimum_msat = 3798;
558                 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
559
560                 let htlc_maximum_msat = htlc_minimum_msat + 1;
561                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
562                 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
563                 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
564         }
565
566         #[test]
567         fn aggregated_htlc_max() {
568                 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
569                 // htlc ends up as the min (htlc_max - following_fees) along the path.
570                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
571                 let intermediate_nodes = vec![ForwardNode {
572                         node_id: dummy_pk,
573                         tlvs: ForwardTlvs {
574                                 short_channel_id: 0,
575                                 payment_relay: PaymentRelay {
576                                         cltv_expiry_delta: 0,
577                                         fee_proportional_millionths: 500,
578                                         fee_base_msat: 1_000,
579                                 },
580                                 payment_constraints: PaymentConstraints {
581                                         max_cltv_expiry: 0,
582                                         htlc_minimum_msat: 1,
583                                 },
584                                 features: BlindedHopFeatures::empty(),
585                         },
586                         htlc_maximum_msat: 5_000,
587                 }, ForwardNode {
588                         node_id: dummy_pk,
589                         tlvs: ForwardTlvs {
590                                 short_channel_id: 0,
591                                 payment_relay: PaymentRelay {
592                                         cltv_expiry_delta: 0,
593                                         fee_proportional_millionths: 500,
594                                         fee_base_msat: 1,
595                                 },
596                                 payment_constraints: PaymentConstraints {
597                                         max_cltv_expiry: 0,
598                                         htlc_minimum_msat: 1,
599                                 },
600                                 features: BlindedHopFeatures::empty(),
601                         },
602                         htlc_maximum_msat: 10_000
603                 }];
604                 let recv_tlvs = ReceiveTlvs {
605                         payment_secret: PaymentSecret([0; 32]),
606                         payment_constraints: PaymentConstraints {
607                                 max_cltv_expiry: 0,
608                                 htlc_minimum_msat: 1,
609                         },
610                         payment_context: PaymentContext::unknown(),
611                 };
612
613                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
614                 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);
615         }
616 }