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