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