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