1 //! Data structures and methods for constructing [`BlindedPath`]s to send a payment over.
3 //! [`BlindedPath`]: crate::blinded_path::BlindedPath
5 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
7 use crate::blinded_path::BlindedHop;
8 use crate::blinded_path::utils;
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};
17 use core::convert::TryFrom;
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`].
31 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
32 pub features: BlindedHopFeatures,
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,
45 /// Data to construct a [`BlindedHop`] for sending a payment over.
47 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
48 pub(crate) enum BlindedPaymentTlvs {
49 /// This blinded payment data is for a forwarding node.
51 /// This blinded payment data is for the receiving node.
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),
61 /// Parameters for relaying over a given [`BlindedHop`].
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`].
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%).
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`].
77 ///[`BlindedHop`]: crate::blinded_path::BlindedHop
78 pub fee_base_msat: u32,
81 /// Constraints for relaying over a given [`BlindedHop`].
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
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
93 pub htlc_minimum_msat: u64,
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),
103 impl_writeable_tlv_based!(ReceiveTlvs, {
104 (12, payment_constraints, required),
105 (65536, payment_secret, required),
108 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
109 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
110 // TODO: write padding
112 Self::Forward(tlvs) => tlvs.write(w)?,
113 Self::Receive(tlvs) => tlvs.write(w)?,
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),
124 (10, payment_relay, option),
125 (12, payment_constraints, required),
126 (14, features, option),
127 (65536, payment_secret, option),
129 let _padding: Option<utils::Padding> = _padding;
131 if let Some(short_channel_id) = scid {
132 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
133 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
135 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
136 payment_constraints: payment_constraints.0.unwrap(),
137 features: features.ok_or(DecodeError::InvalidValue)?,
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(),
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)
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;
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);
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.
178 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
179 u64::try_from(amt_to_forward).ok()
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(()) }
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))
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))
211 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
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),
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
228 htlc_minimum_msat = core::cmp::max(
229 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
231 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
233 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
235 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
236 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
240 features: BlindedHopFeatures::empty(),
244 impl_writeable_msg!(PaymentRelay, {
246 fee_proportional_millionths,
250 impl_writeable_msg!(PaymentConstraints, {
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;
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 {
269 payment_relay: PaymentRelay {
270 cltv_expiry_delta: 144,
271 fee_proportional_millionths: 500,
274 payment_constraints: PaymentConstraints {
276 htlc_minimum_msat: 100,
278 features: BlindedHopFeatures::empty(),
279 }, u64::max_value()), (dummy_pk, ForwardTlvs {
281 payment_relay: PaymentRelay {
282 cltv_expiry_delta: 144,
283 fee_proportional_millionths: 500,
286 payment_constraints: PaymentConstraints {
288 htlc_minimum_msat: 1_000,
290 features: BlindedHopFeatures::empty(),
291 }, u64::max_value())];
292 let recv_tlvs = ReceiveTlvs {
293 payment_secret: PaymentSecret([0; 32]),
294 payment_constraints: PaymentConstraints {
296 htlc_minimum_msat: 1,
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);
309 fn compute_payinfo_1_hop() {
310 let recv_tlvs = ReceiveTlvs {
311 payment_secret: PaymentSecret([0; 32]),
312 payment_constraints: PaymentConstraints {
314 htlc_minimum_msat: 1,
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);
326 fn simple_aggregated_htlc_min() {
327 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
329 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
330 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
332 payment_relay: PaymentRelay {
333 cltv_expiry_delta: 0,
334 fee_proportional_millionths: 0,
337 payment_constraints: PaymentConstraints {
339 htlc_minimum_msat: 1,
341 features: BlindedHopFeatures::empty(),
342 }, u64::max_value()), (dummy_pk, ForwardTlvs {
344 payment_relay: PaymentRelay {
345 cltv_expiry_delta: 0,
346 fee_proportional_millionths: 0,
349 payment_constraints: PaymentConstraints {
351 htlc_minimum_msat: 2_000,
353 features: BlindedHopFeatures::empty(),
354 }, u64::max_value())];
355 let recv_tlvs = ReceiveTlvs {
356 payment_secret: PaymentSecret([0; 32]),
357 payment_constraints: PaymentConstraints {
359 htlc_minimum_msat: 3,
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);
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 {
374 payment_relay: PaymentRelay {
375 cltv_expiry_delta: 0,
376 fee_proportional_millionths: 500,
377 fee_base_msat: 1_000,
379 payment_constraints: PaymentConstraints {
381 htlc_minimum_msat: 5_000,
383 features: BlindedHopFeatures::empty(),
384 }, u64::max_value()), (dummy_pk, ForwardTlvs {
386 payment_relay: PaymentRelay {
387 cltv_expiry_delta: 0,
388 fee_proportional_millionths: 500,
391 payment_constraints: PaymentConstraints {
393 htlc_minimum_msat: 2_000,
395 features: BlindedHopFeatures::empty(),
396 }, u64::max_value())];
397 let recv_tlvs = ReceiveTlvs {
398 payment_secret: PaymentSecret([0; 32]),
399 payment_constraints: PaymentConstraints {
401 htlc_minimum_msat: 1,
404 let htlc_minimum_msat = 3798;
405 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1).is_err());
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);
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 {
420 payment_relay: PaymentRelay {
421 cltv_expiry_delta: 0,
422 fee_proportional_millionths: 500,
423 fee_base_msat: 1_000,
425 payment_constraints: PaymentConstraints {
427 htlc_minimum_msat: 1,
429 features: BlindedHopFeatures::empty(),
430 }, 5_000), (dummy_pk, ForwardTlvs {
432 payment_relay: PaymentRelay {
433 cltv_expiry_delta: 0,
434 fee_proportional_millionths: 500,
437 payment_constraints: PaymentConstraints {
439 htlc_minimum_msat: 1,
441 features: BlindedHopFeatures::empty(),
443 let recv_tlvs = ReceiveTlvs {
444 payment_secret: PaymentSecret([0; 32]),
445 payment_constraints: PaymentConstraints {
447 htlc_minimum_msat: 1,
451 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000).unwrap();
452 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);