Support receiving to 1-hop blinded payment paths.
[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 // This will be removed once we support forwarding blinded HTLCs, because we'll always read a
123 // `BlindedPaymentTlvs` instead.
124 impl Readable for ReceiveTlvs {
125         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
126                 _init_and_read_tlv_stream!(r, {
127                         (12, payment_constraints, required),
128                         (65536, payment_secret, required),
129                 });
130                 Ok(Self {
131                         payment_secret: payment_secret.0.unwrap(),
132                         payment_constraints: payment_constraints.0.unwrap()
133                 })
134         }
135 }
136
137 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
138         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
139                 // TODO: write padding
140                 match self {
141                         Self::Forward(tlvs) => tlvs.write(w)?,
142                         Self::Receive(tlvs) => tlvs.write(w)?,
143                 }
144                 Ok(())
145         }
146 }
147
148 impl Readable for BlindedPaymentTlvs {
149         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
150                 _init_and_read_tlv_stream!(r, {
151                         (1, _padding, option),
152                         (2, scid, option),
153                         (10, payment_relay, option),
154                         (12, payment_constraints, required),
155                         (14, features, option),
156                         (65536, payment_secret, option),
157                 });
158                 let _padding: Option<utils::Padding> = _padding;
159
160                 if let Some(short_channel_id) = scid {
161                         if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
162                         Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
163                                 short_channel_id,
164                                 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
165                                 payment_constraints: payment_constraints.0.unwrap(),
166                                 features: features.ok_or(DecodeError::InvalidValue)?,
167                         }))
168                 } else {
169                         if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
170                         Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
171                                 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
172                                 payment_constraints: payment_constraints.0.unwrap(),
173                         }))
174                 }
175         }
176 }
177
178 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
179 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
180         secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
181         payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
182 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
183         let pks = intermediate_nodes.iter().map(|node| &node.node_id)
184                 .chain(core::iter::once(&payee_node_id));
185         let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
186                 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
187         utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
188 }
189
190 /// `None` if underflow occurs.
191 fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
192         let inbound_amt = inbound_amt_msat as u128;
193         let base = payment_relay.fee_base_msat as u128;
194         let prop = payment_relay.fee_proportional_millionths as u128;
195
196         let post_base_fee_inbound_amt =
197                 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
198         let mut amt_to_forward =
199                 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
200
201         let fee = ((amt_to_forward * prop) / 1_000_000) + base;
202         if inbound_amt - fee < amt_to_forward {
203                 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
204                 // in fee to compensate.
205                 amt_to_forward -= 1;
206         }
207         debug_assert_eq!(amt_to_forward + fee, inbound_amt);
208         u64::try_from(amt_to_forward).ok()
209 }
210
211 pub(super) fn compute_payinfo(
212         intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64
213 ) -> Result<BlindedPayInfo, ()> {
214         let mut curr_base_fee: u64 = 0;
215         let mut curr_prop_mil: u64 = 0;
216         let mut cltv_expiry_delta: u16 = 0;
217         for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
218                 // In the future, we'll want to take the intersection of all supported features for the
219                 // `BlindedPayInfo`, but there are no features in that context right now.
220                 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
221
222                 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
223                 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
224                 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
225                 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
226                 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
227                         .and_then(|f| f.checked_add(1_000_000 - 1))
228                         .map(|f| f / 1_000_000)
229                         .and_then(|f| f.checked_add(next_base_fee))
230                         .ok_or(())?;
231                 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
232                 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
233                         .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
234                         .and_then(|f| f.checked_add(1_000_000 - 1))
235                         .map(|f| f / 1_000_000)
236                         .and_then(|f| f.checked_sub(1_000_000))
237                         .ok_or(())?;
238
239                 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
240         }
241
242         let mut htlc_minimum_msat: u64 = 1;
243         let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
244         for node in intermediate_nodes.iter() {
245                 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
246                 // following hops for forwarding that min, since that fee amount will automatically be included
247                 // in the amount that this node receives and contribute towards reaching its min.
248                 htlc_minimum_msat = amt_to_forward_msat(
249                         core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
250                         &node.tlvs.payment_relay
251                 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
252                 htlc_maximum_msat = amt_to_forward_msat(
253                         core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
254                 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
255         }
256         htlc_minimum_msat = core::cmp::max(
257                 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
258         );
259         htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
260
261         if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
262         Ok(BlindedPayInfo {
263                 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
264                 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
265                 cltv_expiry_delta,
266                 htlc_minimum_msat,
267                 htlc_maximum_msat,
268                 features: BlindedHopFeatures::empty(),
269         })
270 }
271
272 impl_writeable_msg!(PaymentRelay, {
273         cltv_expiry_delta,
274         fee_proportional_millionths,
275         fee_base_msat
276 }, {});
277
278 impl_writeable_msg!(PaymentConstraints, {
279         max_cltv_expiry,
280         htlc_minimum_msat
281 }, {});
282
283 #[cfg(test)]
284 mod tests {
285         use bitcoin::secp256k1::PublicKey;
286         use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
287         use crate::ln::PaymentSecret;
288         use crate::ln::features::BlindedHopFeatures;
289
290         #[test]
291         fn compute_payinfo() {
292                 // Taken from the spec example for aggregating blinded payment info. See
293                 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
294                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
295                 let intermediate_nodes = vec![ForwardNode {
296                         node_id: dummy_pk,
297                         tlvs: ForwardTlvs {
298                                 short_channel_id: 0,
299                                 payment_relay: PaymentRelay {
300                                         cltv_expiry_delta: 144,
301                                         fee_proportional_millionths: 500,
302                                         fee_base_msat: 100,
303                                 },
304                                 payment_constraints: PaymentConstraints {
305                                         max_cltv_expiry: 0,
306                                         htlc_minimum_msat: 100,
307                                 },
308                                 features: BlindedHopFeatures::empty(),
309                         },
310                         htlc_maximum_msat: u64::max_value(),
311                 }, ForwardNode {
312                         node_id: dummy_pk,
313                         tlvs: ForwardTlvs {
314                                 short_channel_id: 0,
315                                 payment_relay: PaymentRelay {
316                                         cltv_expiry_delta: 144,
317                                         fee_proportional_millionths: 500,
318                                         fee_base_msat: 100,
319                                 },
320                                 payment_constraints: PaymentConstraints {
321                                         max_cltv_expiry: 0,
322                                         htlc_minimum_msat: 1_000,
323                                 },
324                                 features: BlindedHopFeatures::empty(),
325                         },
326                         htlc_maximum_msat: u64::max_value(),
327                 }];
328                 let recv_tlvs = ReceiveTlvs {
329                         payment_secret: PaymentSecret([0; 32]),
330                         payment_constraints: PaymentConstraints {
331                                 max_cltv_expiry: 0,
332                                 htlc_minimum_msat: 1,
333                         },
334                 };
335                 let htlc_maximum_msat = 100_000;
336                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
337                 assert_eq!(blinded_payinfo.fee_base_msat, 201);
338                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
339                 assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
340                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
341                 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
342         }
343
344         #[test]
345         fn compute_payinfo_1_hop() {
346                 let recv_tlvs = ReceiveTlvs {
347                         payment_secret: PaymentSecret([0; 32]),
348                         payment_constraints: PaymentConstraints {
349                                 max_cltv_expiry: 0,
350                                 htlc_minimum_msat: 1,
351                         },
352                 };
353                 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242).unwrap();
354                 assert_eq!(blinded_payinfo.fee_base_msat, 0);
355                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
356                 assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);
357                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
358                 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
359         }
360
361         #[test]
362         fn simple_aggregated_htlc_min() {
363                 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
364                 // along the path.
365                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
366                 let intermediate_nodes = vec![ForwardNode {
367                         node_id: dummy_pk,
368                         tlvs: ForwardTlvs {
369                                 short_channel_id: 0,
370                                 payment_relay: PaymentRelay {
371                                         cltv_expiry_delta: 0,
372                                         fee_proportional_millionths: 0,
373                                         fee_base_msat: 0,
374                                 },
375                                 payment_constraints: PaymentConstraints {
376                                         max_cltv_expiry: 0,
377                                         htlc_minimum_msat: 1,
378                                 },
379                                 features: BlindedHopFeatures::empty(),
380                         },
381                         htlc_maximum_msat: u64::max_value()
382                 }, ForwardNode {
383                         node_id: dummy_pk,
384                         tlvs: ForwardTlvs {
385                                 short_channel_id: 0,
386                                 payment_relay: PaymentRelay {
387                                         cltv_expiry_delta: 0,
388                                         fee_proportional_millionths: 0,
389                                         fee_base_msat: 0,
390                                 },
391                                 payment_constraints: PaymentConstraints {
392                                         max_cltv_expiry: 0,
393                                         htlc_minimum_msat: 2_000,
394                                 },
395                                 features: BlindedHopFeatures::empty(),
396                         },
397                         htlc_maximum_msat: u64::max_value()
398                 }];
399                 let recv_tlvs = ReceiveTlvs {
400                         payment_secret: PaymentSecret([0; 32]),
401                         payment_constraints: PaymentConstraints {
402                                 max_cltv_expiry: 0,
403                                 htlc_minimum_msat: 3,
404                         },
405                 };
406                 let htlc_maximum_msat = 100_000;
407                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
408                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
409         }
410
411         #[test]
412         fn aggregated_htlc_min() {
413                 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
414                 // max (htlc_min - following_fees) along the path.
415                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
416                 let intermediate_nodes = vec![ForwardNode {
417                         node_id: dummy_pk,
418                         tlvs: ForwardTlvs {
419                                 short_channel_id: 0,
420                                 payment_relay: PaymentRelay {
421                                         cltv_expiry_delta: 0,
422                                         fee_proportional_millionths: 500,
423                                         fee_base_msat: 1_000,
424                                 },
425                                 payment_constraints: PaymentConstraints {
426                                         max_cltv_expiry: 0,
427                                         htlc_minimum_msat: 5_000,
428                                 },
429                                 features: BlindedHopFeatures::empty(),
430                         },
431                         htlc_maximum_msat: u64::max_value()
432                 }, ForwardNode {
433                         node_id: dummy_pk,
434                         tlvs: ForwardTlvs {
435                                 short_channel_id: 0,
436                                 payment_relay: PaymentRelay {
437                                         cltv_expiry_delta: 0,
438                                         fee_proportional_millionths: 500,
439                                         fee_base_msat: 200,
440                                 },
441                                 payment_constraints: PaymentConstraints {
442                                         max_cltv_expiry: 0,
443                                         htlc_minimum_msat: 2_000,
444                                 },
445                                 features: BlindedHopFeatures::empty(),
446                         },
447                         htlc_maximum_msat: u64::max_value()
448                 }];
449                 let recv_tlvs = ReceiveTlvs {
450                         payment_secret: PaymentSecret([0; 32]),
451                         payment_constraints: PaymentConstraints {
452                                 max_cltv_expiry: 0,
453                                 htlc_minimum_msat: 1,
454                         },
455                 };
456                 let htlc_minimum_msat = 3798;
457                 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1).is_err());
458
459                 let htlc_maximum_msat = htlc_minimum_msat + 1;
460                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
461                 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
462                 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
463         }
464
465         #[test]
466         fn aggregated_htlc_max() {
467                 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
468                 // htlc ends up as the min (htlc_max - following_fees) along the path.
469                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
470                 let intermediate_nodes = vec![ForwardNode {
471                         node_id: dummy_pk,
472                         tlvs: ForwardTlvs {
473                                 short_channel_id: 0,
474                                 payment_relay: PaymentRelay {
475                                         cltv_expiry_delta: 0,
476                                         fee_proportional_millionths: 500,
477                                         fee_base_msat: 1_000,
478                                 },
479                                 payment_constraints: PaymentConstraints {
480                                         max_cltv_expiry: 0,
481                                         htlc_minimum_msat: 1,
482                                 },
483                                 features: BlindedHopFeatures::empty(),
484                         },
485                         htlc_maximum_msat: 5_000,
486                 }, ForwardNode {
487                         node_id: dummy_pk,
488                         tlvs: ForwardTlvs {
489                                 short_channel_id: 0,
490                                 payment_relay: PaymentRelay {
491                                         cltv_expiry_delta: 0,
492                                         fee_proportional_millionths: 500,
493                                         fee_base_msat: 1,
494                                 },
495                                 payment_constraints: PaymentConstraints {
496                                         max_cltv_expiry: 0,
497                                         htlc_minimum_msat: 1,
498                                 },
499                                 features: BlindedHopFeatures::empty(),
500                         },
501                         htlc_maximum_msat: 10_000
502                 }];
503                 let recv_tlvs = ReceiveTlvs {
504                         payment_secret: PaymentSecret([0; 32]),
505                         payment_constraints: PaymentConstraints {
506                                 max_cltv_expiry: 0,
507                                 htlc_minimum_msat: 1,
508                         },
509                 };
510
511                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000).unwrap();
512                 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);
513         }
514 }