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