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