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