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