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