Support aggregating htlc_minimum_msat for BlindedPayInfo
[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         short_channel_id: u64,
23         /// Payment parameters for relaying over [`Self::short_channel_id`].
24         payment_relay: PaymentRelay,
25         /// Payment constraints for relaying over [`Self::short_channel_id`].
26         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         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         payment_secret: PaymentSecret,
39         /// Constraints for the receiver of this payment.
40         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)],
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)], payee_tlvs: &ReceiveTlvs
180 ) -> Result<BlindedPayInfo, ()> {
181         let mut curr_base_fee: u64 = 0;
182         let mut curr_prop_mil: u64 = 0;
183         let mut cltv_expiry_delta: u16 = 0;
184         for (_, tlvs) in intermediate_nodes.iter().rev() {
185                 // In the future, we'll want to take the intersection of all supported features for the
186                 // `BlindedPayInfo`, but there are no features in that context right now.
187                 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
188
189                 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
190                 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
191                 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
192                 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
193                 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
194                         .and_then(|f| f.checked_add(1_000_000 - 1))
195                         .map(|f| f / 1_000_000)
196                         .and_then(|f| f.checked_add(next_base_fee))
197                         .ok_or(())?;
198                 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
199                 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
200                         .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
201                         .and_then(|f| f.checked_add(1_000_000 - 1))
202                         .map(|f| f / 1_000_000)
203                         .and_then(|f| f.checked_sub(1_000_000))
204                         .ok_or(())?;
205
206                 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
207         }
208
209         let mut htlc_minimum_msat: u64 = 1;
210         for (_, tlvs) in intermediate_nodes.iter() {
211                 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
212                 // following hops for forwarding that min, since that fee amount will automatically be included
213                 // in the amount that this node receives and contribute towards reaching its min.
214                 htlc_minimum_msat = amt_to_forward_msat(
215                         core::cmp::max(tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
216                         &tlvs.payment_relay
217                 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
218         }
219         htlc_minimum_msat = core::cmp::max(
220                 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
221         );
222
223         Ok(BlindedPayInfo {
224                 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
225                 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
226                 cltv_expiry_delta,
227                 htlc_minimum_msat,
228                 htlc_maximum_msat: 21_000_000 * 100_000_000 * 1_000, // TODO
229                 features: BlindedHopFeatures::empty(),
230         })
231 }
232
233 impl_writeable_msg!(PaymentRelay, {
234         cltv_expiry_delta,
235         fee_proportional_millionths,
236         fee_base_msat
237 }, {});
238
239 impl_writeable_msg!(PaymentConstraints, {
240         max_cltv_expiry,
241         htlc_minimum_msat
242 }, {});
243
244 #[cfg(test)]
245 mod tests {
246         use bitcoin::secp256k1::PublicKey;
247         use crate::blinded_path::payment::{ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
248         use crate::ln::PaymentSecret;
249         use crate::ln::features::BlindedHopFeatures;
250
251         #[test]
252         fn compute_payinfo() {
253                 // Taken from the spec example for aggregating blinded payment info. See
254                 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
255                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
256                 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
257                         short_channel_id: 0,
258                         payment_relay: PaymentRelay {
259                                 cltv_expiry_delta: 144,
260                                 fee_proportional_millionths: 500,
261                                 fee_base_msat: 100,
262                         },
263                         payment_constraints: PaymentConstraints {
264                                 max_cltv_expiry: 0,
265                                 htlc_minimum_msat: 100,
266                         },
267                         features: BlindedHopFeatures::empty(),
268                 }), (dummy_pk, ForwardTlvs {
269                         short_channel_id: 0,
270                         payment_relay: PaymentRelay {
271                                 cltv_expiry_delta: 144,
272                                 fee_proportional_millionths: 500,
273                                 fee_base_msat: 100,
274                         },
275                         payment_constraints: PaymentConstraints {
276                                 max_cltv_expiry: 0,
277                                 htlc_minimum_msat: 1_000,
278                         },
279                         features: BlindedHopFeatures::empty(),
280                 })];
281                 let recv_tlvs = ReceiveTlvs {
282                         payment_secret: PaymentSecret([0; 32]),
283                         payment_constraints: PaymentConstraints {
284                                 max_cltv_expiry: 0,
285                                 htlc_minimum_msat: 1,
286                         },
287                 };
288                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
289                 assert_eq!(blinded_payinfo.fee_base_msat, 201);
290                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
291                 assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
292                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
293         }
294
295         #[test]
296         fn compute_payinfo_1_hop() {
297                 let recv_tlvs = ReceiveTlvs {
298                         payment_secret: PaymentSecret([0; 32]),
299                         payment_constraints: PaymentConstraints {
300                                 max_cltv_expiry: 0,
301                                 htlc_minimum_msat: 1,
302                         },
303                 };
304                 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs).unwrap();
305                 assert_eq!(blinded_payinfo.fee_base_msat, 0);
306                 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
307                 assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);
308                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
309         }
310
311         #[test]
312         fn simple_aggregated_htlc_min() {
313                 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
314                 // along the path.
315                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
316                 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
317                         short_channel_id: 0,
318                         payment_relay: PaymentRelay {
319                                 cltv_expiry_delta: 0,
320                                 fee_proportional_millionths: 0,
321                                 fee_base_msat: 0,
322                         },
323                         payment_constraints: PaymentConstraints {
324                                 max_cltv_expiry: 0,
325                                 htlc_minimum_msat: 1,
326                         },
327                         features: BlindedHopFeatures::empty(),
328                 }), (dummy_pk, ForwardTlvs {
329                         short_channel_id: 0,
330                         payment_relay: PaymentRelay {
331                                 cltv_expiry_delta: 0,
332                                 fee_proportional_millionths: 0,
333                                 fee_base_msat: 0,
334                         },
335                         payment_constraints: PaymentConstraints {
336                                 max_cltv_expiry: 0,
337                                 htlc_minimum_msat: 2_000,
338                         },
339                         features: BlindedHopFeatures::empty(),
340                 })];
341                 let recv_tlvs = ReceiveTlvs {
342                         payment_secret: PaymentSecret([0; 32]),
343                         payment_constraints: PaymentConstraints {
344                                 max_cltv_expiry: 0,
345                                 htlc_minimum_msat: 3,
346                         },
347                 };
348                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
349                 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
350         }
351
352         #[test]
353         fn aggregated_htlc_min() {
354                 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
355                 // max (htlc_min - following_fees) along the path.
356                 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
357                 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
358                         short_channel_id: 0,
359                         payment_relay: PaymentRelay {
360                                 cltv_expiry_delta: 0,
361                                 fee_proportional_millionths: 500,
362                                 fee_base_msat: 1_000,
363                         },
364                         payment_constraints: PaymentConstraints {
365                                 max_cltv_expiry: 0,
366                                 htlc_minimum_msat: 5_000,
367                         },
368                         features: BlindedHopFeatures::empty(),
369                 }), (dummy_pk, ForwardTlvs {
370                         short_channel_id: 0,
371                         payment_relay: PaymentRelay {
372                                 cltv_expiry_delta: 0,
373                                 fee_proportional_millionths: 500,
374                                 fee_base_msat: 200,
375                         },
376                         payment_constraints: PaymentConstraints {
377                                 max_cltv_expiry: 0,
378                                 htlc_minimum_msat: 2_000,
379                         },
380                         features: BlindedHopFeatures::empty(),
381                 })];
382                 let recv_tlvs = ReceiveTlvs {
383                         payment_secret: PaymentSecret([0; 32]),
384                         payment_constraints: PaymentConstraints {
385                                 max_cltv_expiry: 0,
386                                 htlc_minimum_msat: 1,
387                         },
388                 };
389                 let htlc_minimum_msat = 3798;
390                 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
391                 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
392         }
393 }