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