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