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