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 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`].
30 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
31 pub features: BlindedHopFeatures,
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,
43 /// Data to construct a [`BlindedHop`] for sending a payment over.
45 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
46 pub(crate) enum BlindedPaymentTlvs {
47 /// This blinded payment data is for a forwarding node.
49 /// This blinded payment data is for the receiving node.
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),
59 /// Parameters for relaying over a given [`BlindedHop`].
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`].
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%).
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`].
74 ///[`BlindedHop`]: crate::blinded_path::BlindedHop
75 pub fee_base_msat: u32,
78 /// Constraints for relaying over a given [`BlindedHop`].
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
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
89 pub htlc_minimum_msat: u64,
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),
99 impl_writeable_tlv_based!(ReceiveTlvs, {
100 (12, payment_constraints, required),
101 (65536, payment_secret, required),
104 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
105 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
106 // TODO: write padding
108 Self::Forward(tlvs) => tlvs.write(w)?,
109 Self::Receive(tlvs) => tlvs.write(w)?,
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),
120 (10, payment_relay, option),
121 (12, payment_constraints, required),
122 (14, features, option),
123 (65536, payment_secret, option),
125 let _padding: Option<utils::Padding> = _padding;
127 if let Some(short_channel_id) = scid {
128 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
129 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
131 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
132 payment_constraints: payment_constraints.0.unwrap(),
133 features: features.ok_or(DecodeError::InvalidValue)?,
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(),
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)
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;
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);
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.
174 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
175 u64::try_from(amt_to_forward).ok()
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(()) }
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))
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))
207 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
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),
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
224 htlc_minimum_msat = core::cmp::max(
225 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
227 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
229 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
231 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
232 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
236 features: BlindedHopFeatures::empty(),
240 impl_writeable_msg!(PaymentRelay, {
242 fee_proportional_millionths,
246 impl_writeable_msg!(PaymentConstraints, {
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;
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 {
265 payment_relay: PaymentRelay {
266 cltv_expiry_delta: 144,
267 fee_proportional_millionths: 500,
270 payment_constraints: PaymentConstraints {
272 htlc_minimum_msat: 100,
274 features: BlindedHopFeatures::empty(),
275 }, u64::max_value()), (dummy_pk, ForwardTlvs {
277 payment_relay: PaymentRelay {
278 cltv_expiry_delta: 144,
279 fee_proportional_millionths: 500,
282 payment_constraints: PaymentConstraints {
284 htlc_minimum_msat: 1_000,
286 features: BlindedHopFeatures::empty(),
287 }, u64::max_value())];
288 let recv_tlvs = ReceiveTlvs {
289 payment_secret: PaymentSecret([0; 32]),
290 payment_constraints: PaymentConstraints {
292 htlc_minimum_msat: 1,
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);
305 fn compute_payinfo_1_hop() {
306 let recv_tlvs = ReceiveTlvs {
307 payment_secret: PaymentSecret([0; 32]),
308 payment_constraints: PaymentConstraints {
310 htlc_minimum_msat: 1,
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);
322 fn simple_aggregated_htlc_min() {
323 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
325 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
326 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
328 payment_relay: PaymentRelay {
329 cltv_expiry_delta: 0,
330 fee_proportional_millionths: 0,
333 payment_constraints: PaymentConstraints {
335 htlc_minimum_msat: 1,
337 features: BlindedHopFeatures::empty(),
338 }, u64::max_value()), (dummy_pk, ForwardTlvs {
340 payment_relay: PaymentRelay {
341 cltv_expiry_delta: 0,
342 fee_proportional_millionths: 0,
345 payment_constraints: PaymentConstraints {
347 htlc_minimum_msat: 2_000,
349 features: BlindedHopFeatures::empty(),
350 }, u64::max_value())];
351 let recv_tlvs = ReceiveTlvs {
352 payment_secret: PaymentSecret([0; 32]),
353 payment_constraints: PaymentConstraints {
355 htlc_minimum_msat: 3,
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);
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 {
370 payment_relay: PaymentRelay {
371 cltv_expiry_delta: 0,
372 fee_proportional_millionths: 500,
373 fee_base_msat: 1_000,
375 payment_constraints: PaymentConstraints {
377 htlc_minimum_msat: 5_000,
379 features: BlindedHopFeatures::empty(),
380 }, u64::max_value()), (dummy_pk, ForwardTlvs {
382 payment_relay: PaymentRelay {
383 cltv_expiry_delta: 0,
384 fee_proportional_millionths: 500,
387 payment_constraints: PaymentConstraints {
389 htlc_minimum_msat: 2_000,
391 features: BlindedHopFeatures::empty(),
392 }, u64::max_value())];
393 let recv_tlvs = ReceiveTlvs {
394 payment_secret: PaymentSecret([0; 32]),
395 payment_constraints: PaymentConstraints {
397 htlc_minimum_msat: 1,
400 let htlc_minimum_msat = 3798;
401 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1).is_err());
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);
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 {
416 payment_relay: PaymentRelay {
417 cltv_expiry_delta: 0,
418 fee_proportional_millionths: 500,
419 fee_base_msat: 1_000,
421 payment_constraints: PaymentConstraints {
423 htlc_minimum_msat: 1,
425 features: BlindedHopFeatures::empty(),
426 }, 5_000), (dummy_pk, ForwardTlvs {
428 payment_relay: PaymentRelay {
429 cltv_expiry_delta: 0,
430 fee_proportional_millionths: 500,
433 payment_constraints: PaymentConstraints {
435 htlc_minimum_msat: 1,
437 features: BlindedHopFeatures::empty(),
439 let recv_tlvs = ReceiveTlvs {
440 payment_secret: PaymentSecret([0; 32]),
441 payment_constraints: PaymentConstraints {
443 htlc_minimum_msat: 1,
447 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000).unwrap();
448 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);