ad7b229b53fa1c830d042d24a892360666bf5b65
[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         /// The payment was made for an invoice sent for a BOLT 12 [`Refund`].
119         ///
120         /// [`Refund`]: crate::offers::refund::Refund
121         Bolt12Refund(Bolt12RefundContext),
122 }
123
124 /// An unknown payment context.
125 #[derive(Clone, Debug, Eq, PartialEq)]
126 pub struct UnknownPaymentContext(());
127
128 /// The context of a payment made for an invoice requested from a BOLT 12 [`Offer`].
129 ///
130 /// [`Offer`]: crate::offers::offer::Offer
131 #[derive(Clone, Debug, Eq, PartialEq)]
132 pub struct Bolt12OfferContext {
133         /// The identifier of the [`Offer`].
134         ///
135         /// [`Offer`]: crate::offers::offer::Offer
136         pub offer_id: OfferId,
137 }
138
139 /// The context of a payment made for an invoice sent for a BOLT 12 [`Refund`].
140 ///
141 /// [`Refund`]: crate::offers::refund::Refund
142 #[derive(Clone, Debug, Eq, PartialEq)]
143 pub struct Bolt12RefundContext {}
144
145 impl PaymentContext {
146         pub(crate) fn unknown() -> Self {
147                 PaymentContext::Unknown(UnknownPaymentContext(()))
148         }
149 }
150
151 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
152         type Error = ();
153
154         fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
155                 let CounterpartyForwardingInfo {
156                         fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
157                 } = info;
158
159                 // Avoid exposing esoteric CLTV expiry deltas
160                 let cltv_expiry_delta = match cltv_expiry_delta {
161                         0..=40 => 40,
162                         41..=80 => 80,
163                         81..=144 => 144,
164                         145..=216 => 216,
165                         _ => return Err(()),
166                 };
167
168                 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
169         }
170 }
171
172 impl Writeable for ForwardTlvs {
173         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
174                 let features_opt =
175                         if self.features == BlindedHopFeatures::empty() { None }
176                         else { Some(&self.features) };
177                 encode_tlv_stream!(w, {
178                         (2, self.short_channel_id, required),
179                         (10, self.payment_relay, required),
180                         (12, self.payment_constraints, required),
181                         (14, features_opt, option)
182                 });
183                 Ok(())
184         }
185 }
186
187 impl Writeable for ReceiveTlvs {
188         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
189                 encode_tlv_stream!(w, {
190                         (12, self.payment_constraints, required),
191                         (65536, self.payment_secret, required),
192                         (65537, self.payment_context, required)
193                 });
194                 Ok(())
195         }
196 }
197
198 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
199         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
200                 // TODO: write padding
201                 match self {
202                         Self::Forward(tlvs) => tlvs.write(w)?,
203                         Self::Receive(tlvs) => tlvs.write(w)?,
204                 }
205                 Ok(())
206         }
207 }
208
209 impl Readable for BlindedPaymentTlvs {
210         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
211                 _init_and_read_tlv_stream!(r, {
212                         (1, _padding, option),
213                         (2, scid, option),
214                         (10, payment_relay, option),
215                         (12, payment_constraints, required),
216                         (14, features, option),
217                         (65536, payment_secret, option),
218                         (65537, payment_context, (default_value, PaymentContext::unknown())),
219                 });
220                 let _padding: Option<utils::Padding> = _padding;
221
222                 if let Some(short_channel_id) = scid {
223                         if payment_secret.is_some() {
224                                 return Err(DecodeError::InvalidValue)
225                         }
226                         Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
227                                 short_channel_id,
228                                 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
229                                 payment_constraints: payment_constraints.0.unwrap(),
230                                 features: features.unwrap_or_else(BlindedHopFeatures::empty),
231                         }))
232                 } else {
233                         if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
234                         Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
235                                 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
236                                 payment_constraints: payment_constraints.0.unwrap(),
237                                 payment_context: payment_context.0.unwrap(),
238                         }))
239                 }
240         }
241 }
242
243 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
244 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
245         secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
246         payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
247 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
248         let pks = intermediate_nodes.iter().map(|node| &node.node_id)
249                 .chain(core::iter::once(&payee_node_id));
250         let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
251                 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
252         utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
253 }
254
255 /// `None` if underflow occurs.
256 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
257         let inbound_amt = inbound_amt_msat as u128;
258         let base = payment_relay.fee_base_msat as u128;
259         let prop = payment_relay.fee_proportional_millionths as u128;
260
261         let post_base_fee_inbound_amt =
262                 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
263         let mut amt_to_forward =
264                 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
265
266         let fee = ((amt_to_forward * prop) / 1_000_000) + base;
267         if inbound_amt - fee < amt_to_forward {
268                 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
269                 // in fee to compensate.
270                 amt_to_forward -= 1;
271         }
272         debug_assert_eq!(amt_to_forward + fee, inbound_amt);
273         u64::try_from(amt_to_forward).ok()
274 }
275
276 pub(super) fn compute_payinfo(
277         intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
278         min_final_cltv_expiry_delta: u16
279 ) -> Result<BlindedPayInfo, ()> {
280         let mut curr_base_fee: u64 = 0;
281         let mut curr_prop_mil: u64 = 0;
282         let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
283         for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
284                 // In the future, we'll want to take the intersection of all supported features for the
285                 // `BlindedPayInfo`, but there are no features in that context right now.
286                 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
287
288                 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
289                 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
290                 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
291                 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
292                 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
293                         .and_then(|f| f.checked_add(1_000_000 - 1))
294                         .map(|f| f / 1_000_000)
295                         .and_then(|f| f.checked_add(next_base_fee))
296                         .ok_or(())?;
297                 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
298                 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
299                         .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
300                         .and_then(|f| f.checked_add(1_000_000 - 1))
301                         .map(|f| f / 1_000_000)
302                         .and_then(|f| f.checked_sub(1_000_000))
303                         .ok_or(())?;
304
305                 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
306         }
307
308         let mut htlc_minimum_msat: u64 = 1;
309         let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
310         for node in intermediate_nodes.iter() {
311                 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
312                 // following hops for forwarding that min, since that fee amount will automatically be included
313                 // in the amount that this node receives and contribute towards reaching its min.
314                 htlc_minimum_msat = amt_to_forward_msat(
315                         core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
316                         &node.tlvs.payment_relay
317                 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
318                 htlc_maximum_msat = amt_to_forward_msat(
319                         core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
320                 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
321         }
322         htlc_minimum_msat = core::cmp::max(
323                 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
324         );
325         htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
326
327         if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
328         Ok(BlindedPayInfo {
329                 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
330                 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
331                 cltv_expiry_delta,
332                 htlc_minimum_msat,
333                 htlc_maximum_msat,
334                 features: BlindedHopFeatures::empty(),
335         })
336 }
337
338 impl Writeable for PaymentRelay {
339         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
340                 self.cltv_expiry_delta.write(w)?;
341                 self.fee_proportional_millionths.write(w)?;
342                 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
343         }
344 }
345 impl Readable for PaymentRelay {
346         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
347                 let cltv_expiry_delta: u16 = Readable::read(r)?;
348                 let fee_proportional_millionths: u32 = Readable::read(r)?;
349                 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
350                 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
351         }
352 }
353
354 impl Writeable for PaymentConstraints {
355         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
356                 self.max_cltv_expiry.write(w)?;
357                 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
358         }
359 }
360 impl Readable for PaymentConstraints {
361         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
362                 let max_cltv_expiry: u32 = Readable::read(r)?;
363                 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
364                 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
365         }
366 }
367
368 impl_writeable_tlv_based_enum!(PaymentContext,
369         ;
370         (0, Unknown),
371         (1, Bolt12Offer),
372         (2, Bolt12Refund),
373 );
374
375 impl Writeable for UnknownPaymentContext {
376         fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
377                 Ok(())
378         }
379 }
380
381 impl Readable for UnknownPaymentContext {
382         fn read<R: io::Read>(_r: &mut R) -> Result<Self, DecodeError> {
383                 Ok(UnknownPaymentContext(()))
384         }
385 }
386
387 impl_writeable_tlv_based!(Bolt12OfferContext, {
388         (0, offer_id, required),
389 });
390
391 impl_writeable_tlv_based!(Bolt12RefundContext, {});
392
393 #[cfg(test)]
394 mod tests {
395         use bitcoin::secp256k1::PublicKey;
396         use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentContext, PaymentRelay};
397         use crate::ln::PaymentSecret;
398         use crate::ln::features::BlindedHopFeatures;
399         use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
400
401         #[test]
402         fn compute_payinfo() {
403                 // Taken from the spec example for aggregating blinded payment info. See
404                 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
405                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
406                 let intermediate_nodes = vec![ForwardNode {
407                         node_id: dummy_pk,
408                         tlvs: ForwardTlvs {
409                                 short_channel_id: 0,
410                                 payment_relay: PaymentRelay {
411                                         cltv_expiry_delta: 144,
412                                         fee_proportional_millionths: 500,
413                                         fee_base_msat: 100,
414                                 },
415                                 payment_constraints: PaymentConstraints {
416                                         max_cltv_expiry: 0,
417                                         htlc_minimum_msat: 100,
418                                 },
419                                 features: BlindedHopFeatures::empty(),
420                         },
421                         htlc_maximum_msat: u64::max_value(),
422                 }, ForwardNode {
423                         node_id: dummy_pk,
424                         tlvs: ForwardTlvs {
425                                 short_channel_id: 0,
426                                 payment_relay: PaymentRelay {
427                                         cltv_expiry_delta: 144,
428                                         fee_proportional_millionths: 500,
429                                         fee_base_msat: 100,
430                                 },
431                                 payment_constraints: PaymentConstraints {
432                                         max_cltv_expiry: 0,
433                                         htlc_minimum_msat: 1_000,
434                                 },
435                                 features: BlindedHopFeatures::empty(),
436                         },
437                         htlc_maximum_msat: u64::max_value(),
438                 }];
439                 let recv_tlvs = ReceiveTlvs {
440                         payment_secret: PaymentSecret([0; 32]),
441                         payment_constraints: PaymentConstraints {
442                                 max_cltv_expiry: 0,
443                                 htlc_minimum_msat: 1,
444                         },
445                         payment_context: PaymentContext::unknown(),
446                 };
447                 let htlc_maximum_msat = 100_000;
448                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
449                 assert_eq!(blinded_payinfo.fee_base_msat, 201);
450                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
451                 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
452                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
453                 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
454         }
455
456         #[test]
457         fn compute_payinfo_1_hop() {
458                 let recv_tlvs = ReceiveTlvs {
459                         payment_secret: PaymentSecret([0; 32]),
460                         payment_constraints: PaymentConstraints {
461                                 max_cltv_expiry: 0,
462                                 htlc_minimum_msat: 1,
463                         },
464                         payment_context: PaymentContext::unknown(),
465                 };
466                 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
467                 assert_eq!(blinded_payinfo.fee_base_msat, 0);
468                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
469                 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
470                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
471                 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
472         }
473
474         #[test]
475         fn simple_aggregated_htlc_min() {
476                 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
477                 // along the path.
478                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
479                 let intermediate_nodes = vec![ForwardNode {
480                         node_id: dummy_pk,
481                         tlvs: ForwardTlvs {
482                                 short_channel_id: 0,
483                                 payment_relay: PaymentRelay {
484                                         cltv_expiry_delta: 0,
485                                         fee_proportional_millionths: 0,
486                                         fee_base_msat: 0,
487                                 },
488                                 payment_constraints: PaymentConstraints {
489                                         max_cltv_expiry: 0,
490                                         htlc_minimum_msat: 1,
491                                 },
492                                 features: BlindedHopFeatures::empty(),
493                         },
494                         htlc_maximum_msat: u64::max_value()
495                 }, ForwardNode {
496                         node_id: dummy_pk,
497                         tlvs: ForwardTlvs {
498                                 short_channel_id: 0,
499                                 payment_relay: PaymentRelay {
500                                         cltv_expiry_delta: 0,
501                                         fee_proportional_millionths: 0,
502                                         fee_base_msat: 0,
503                                 },
504                                 payment_constraints: PaymentConstraints {
505                                         max_cltv_expiry: 0,
506                                         htlc_minimum_msat: 2_000,
507                                 },
508                                 features: BlindedHopFeatures::empty(),
509                         },
510                         htlc_maximum_msat: u64::max_value()
511                 }];
512                 let recv_tlvs = ReceiveTlvs {
513                         payment_secret: PaymentSecret([0; 32]),
514                         payment_constraints: PaymentConstraints {
515                                 max_cltv_expiry: 0,
516                                 htlc_minimum_msat: 3,
517                         },
518                         payment_context: PaymentContext::unknown(),
519                 };
520                 let htlc_maximum_msat = 100_000;
521                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
522                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
523         }
524
525         #[test]
526         fn aggregated_htlc_min() {
527                 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
528                 // max (htlc_min - following_fees) along the path.
529                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
530                 let intermediate_nodes = vec![ForwardNode {
531                         node_id: dummy_pk,
532                         tlvs: ForwardTlvs {
533                                 short_channel_id: 0,
534                                 payment_relay: PaymentRelay {
535                                         cltv_expiry_delta: 0,
536                                         fee_proportional_millionths: 500,
537                                         fee_base_msat: 1_000,
538                                 },
539                                 payment_constraints: PaymentConstraints {
540                                         max_cltv_expiry: 0,
541                                         htlc_minimum_msat: 5_000,
542                                 },
543                                 features: BlindedHopFeatures::empty(),
544                         },
545                         htlc_maximum_msat: u64::max_value()
546                 }, ForwardNode {
547                         node_id: dummy_pk,
548                         tlvs: ForwardTlvs {
549                                 short_channel_id: 0,
550                                 payment_relay: PaymentRelay {
551                                         cltv_expiry_delta: 0,
552                                         fee_proportional_millionths: 500,
553                                         fee_base_msat: 200,
554                                 },
555                                 payment_constraints: PaymentConstraints {
556                                         max_cltv_expiry: 0,
557                                         htlc_minimum_msat: 2_000,
558                                 },
559                                 features: BlindedHopFeatures::empty(),
560                         },
561                         htlc_maximum_msat: u64::max_value()
562                 }];
563                 let recv_tlvs = ReceiveTlvs {
564                         payment_secret: PaymentSecret([0; 32]),
565                         payment_constraints: PaymentConstraints {
566                                 max_cltv_expiry: 0,
567                                 htlc_minimum_msat: 1,
568                         },
569                         payment_context: PaymentContext::unknown(),
570                 };
571                 let htlc_minimum_msat = 3798;
572                 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
573
574                 let htlc_maximum_msat = htlc_minimum_msat + 1;
575                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
576                 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
577                 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
578         }
579
580         #[test]
581         fn aggregated_htlc_max() {
582                 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
583                 // htlc ends up as the min (htlc_max - following_fees) along the path.
584                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
585                 let intermediate_nodes = vec![ForwardNode {
586                         node_id: dummy_pk,
587                         tlvs: ForwardTlvs {
588                                 short_channel_id: 0,
589                                 payment_relay: PaymentRelay {
590                                         cltv_expiry_delta: 0,
591                                         fee_proportional_millionths: 500,
592                                         fee_base_msat: 1_000,
593                                 },
594                                 payment_constraints: PaymentConstraints {
595                                         max_cltv_expiry: 0,
596                                         htlc_minimum_msat: 1,
597                                 },
598                                 features: BlindedHopFeatures::empty(),
599                         },
600                         htlc_maximum_msat: 5_000,
601                 }, ForwardNode {
602                         node_id: dummy_pk,
603                         tlvs: ForwardTlvs {
604                                 short_channel_id: 0,
605                                 payment_relay: PaymentRelay {
606                                         cltv_expiry_delta: 0,
607                                         fee_proportional_millionths: 500,
608                                         fee_base_msat: 1,
609                                 },
610                                 payment_constraints: PaymentConstraints {
611                                         max_cltv_expiry: 0,
612                                         htlc_minimum_msat: 1,
613                                 },
614                                 features: BlindedHopFeatures::empty(),
615                         },
616                         htlc_maximum_msat: 10_000
617                 }];
618                 let recv_tlvs = ReceiveTlvs {
619                         payment_secret: PaymentSecret([0; 32]),
620                         payment_constraints: PaymentConstraints {
621                                 max_cltv_expiry: 0,
622                                 htlc_minimum_msat: 1,
623                         },
624                         payment_context: PaymentContext::unknown(),
625                 };
626
627                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
628                 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);
629         }
630 }