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