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::channelmanager::CounterpartyForwardingInfo;
12 use crate::ln::features::BlindedHopFeatures;
13 use crate::ln::msgs::DecodeError;
14 use crate::offers::invoice::BlindedPayInfo;
15 use crate::offers::offer::OfferId;
16 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, Writeable, Writer};
18 #[allow(unused_imports)]
19 use crate::prelude::*;
21 /// An intermediate node, its outbound channel, and relay parameters.
22 #[derive(Clone, Debug)]
23 pub struct ForwardNode {
24 /// The TLVs for this node's [`BlindedHop`], where the fee parameters contained within are also
25 /// used for [`BlindedPayInfo`] construction.
26 pub tlvs: ForwardTlvs,
27 /// This node's pubkey.
28 pub node_id: PublicKey,
29 /// The maximum value, in msat, that may be accepted by this node.
30 pub htlc_maximum_msat: u64,
33 /// Data to construct a [`BlindedHop`] for forwarding a payment.
34 #[derive(Clone, Debug)]
35 pub struct ForwardTlvs {
36 /// The short channel id this payment should be forwarded out over.
37 pub short_channel_id: u64,
38 /// Payment parameters for relaying over [`Self::short_channel_id`].
39 pub payment_relay: PaymentRelay,
40 /// Payment constraints for relaying over [`Self::short_channel_id`].
41 pub payment_constraints: PaymentConstraints,
42 /// Supported and required features when relaying a payment onion containing this object's
43 /// corresponding [`BlindedHop::encrypted_payload`].
45 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
46 pub features: BlindedHopFeatures,
49 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
50 /// may not be valid if received by another lightning implementation.
51 #[derive(Clone, Debug)]
52 pub struct ReceiveTlvs {
53 /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
54 pub payment_secret: PaymentSecret,
55 /// Constraints for the receiver of this payment.
56 pub payment_constraints: PaymentConstraints,
57 /// Context for the receiver of this payment.
58 pub payment_context: PaymentContext,
61 /// Data to construct a [`BlindedHop`] for sending a payment over.
63 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
64 pub(crate) enum BlindedPaymentTlvs {
65 /// This blinded payment data is for a forwarding node.
67 /// This blinded payment data is for the receiving node.
71 // Used to include forward and receive TLVs in the same iterator for encoding.
72 enum BlindedPaymentTlvsRef<'a> {
73 Forward(&'a ForwardTlvs),
74 Receive(&'a ReceiveTlvs),
77 /// Parameters for relaying over a given [`BlindedHop`].
79 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
80 #[derive(Clone, Debug)]
81 pub struct PaymentRelay {
82 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
83 pub cltv_expiry_delta: u16,
84 /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
85 /// this [`BlindedHop`], (i.e., 10,000 is 1%).
86 pub fee_proportional_millionths: u32,
87 /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
88 pub fee_base_msat: u32,
91 /// Constraints for relaying over a given [`BlindedHop`].
93 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
94 #[derive(Clone, Debug)]
95 pub struct PaymentConstraints {
96 /// The maximum total CLTV that is acceptable when relaying a payment over this [`BlindedHop`].
97 pub max_cltv_expiry: u32,
98 /// The minimum value, in msat, that may be accepted by the node corresponding to this
100 pub htlc_minimum_msat: u64,
103 /// The context of an inbound payment, which is included in a [`BlindedPath`] via [`ReceiveTlvs`]
104 /// and surfaced in [`PaymentPurpose`].
106 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
107 /// [`PaymentPurpose`]: crate::events::PaymentPurpose
108 #[derive(Clone, Debug, Eq, PartialEq)]
109 pub enum PaymentContext {
110 /// The payment context was unknown.
111 Unknown(UnknownPaymentContext),
113 /// The payment was made for an invoice requested from a BOLT 12 [`Offer`].
115 /// [`Offer`]: crate::offers::offer::Offer
116 Bolt12Offer(Bolt12OfferContext),
118 /// The payment was made for an invoice sent for a BOLT 12 [`Refund`].
120 /// [`Refund`]: crate::offers::refund::Refund
121 Bolt12Refund(Bolt12RefundContext),
124 /// An unknown payment context.
125 #[derive(Clone, Debug, Eq, PartialEq)]
126 pub struct UnknownPaymentContext(());
128 /// The context of a payment made for an invoice requested from a BOLT 12 [`Offer`].
130 /// [`Offer`]: crate::offers::offer::Offer
131 #[derive(Clone, Debug, Eq, PartialEq)]
132 pub struct Bolt12OfferContext {
133 /// The identifier of the [`Offer`].
135 /// [`Offer`]: crate::offers::offer::Offer
136 pub offer_id: OfferId,
139 /// The context of a payment made for an invoice sent for a BOLT 12 [`Refund`].
141 /// [`Refund`]: crate::offers::refund::Refund
142 #[derive(Clone, Debug, Eq, PartialEq)]
143 pub struct Bolt12RefundContext {}
145 impl PaymentContext {
146 pub(crate) fn unknown() -> Self {
147 PaymentContext::Unknown(UnknownPaymentContext(()))
151 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
154 fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
155 let CounterpartyForwardingInfo {
156 fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
159 // Avoid exposing esoteric CLTV expiry deltas
160 let cltv_expiry_delta = match cltv_expiry_delta {
168 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
172 impl Writeable for ForwardTlvs {
173 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
175 if self.features == BlindedHopFeatures::empty() { None }
176 else { Some(&self.features) };
177 encode_tlv_stream!(w, {
178 (2, self.short_channel_id, required),
179 (10, self.payment_relay, required),
180 (12, self.payment_constraints, required),
181 (14, features_opt, option)
187 impl Writeable for ReceiveTlvs {
188 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
189 encode_tlv_stream!(w, {
190 (12, self.payment_constraints, required),
191 (65536, self.payment_secret, required),
192 (65537, self.payment_context, required)
198 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
199 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
200 // TODO: write padding
202 Self::Forward(tlvs) => tlvs.write(w)?,
203 Self::Receive(tlvs) => tlvs.write(w)?,
209 impl Readable for BlindedPaymentTlvs {
210 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
211 _init_and_read_tlv_stream!(r, {
212 (1, _padding, option),
214 (10, payment_relay, option),
215 (12, payment_constraints, required),
216 (14, features, option),
217 (65536, payment_secret, option),
218 (65537, payment_context, (default_value, PaymentContext::unknown())),
220 let _padding: Option<utils::Padding> = _padding;
222 if let Some(short_channel_id) = scid {
223 if payment_secret.is_some() {
224 return Err(DecodeError::InvalidValue)
226 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
228 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
229 payment_constraints: payment_constraints.0.unwrap(),
230 features: features.unwrap_or_else(BlindedHopFeatures::empty),
233 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
234 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
235 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
236 payment_constraints: payment_constraints.0.unwrap(),
237 payment_context: payment_context.0.unwrap(),
243 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
244 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
245 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
246 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
247 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
248 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
249 .chain(core::iter::once(&payee_node_id));
250 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
251 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
252 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
255 /// `None` if underflow occurs.
256 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
257 let inbound_amt = inbound_amt_msat as u128;
258 let base = payment_relay.fee_base_msat as u128;
259 let prop = payment_relay.fee_proportional_millionths as u128;
261 let post_base_fee_inbound_amt =
262 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
263 let mut amt_to_forward =
264 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
266 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
267 if inbound_amt - fee < amt_to_forward {
268 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
269 // in fee to compensate.
272 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
273 u64::try_from(amt_to_forward).ok()
276 pub(super) fn compute_payinfo(
277 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
278 min_final_cltv_expiry_delta: u16
279 ) -> Result<BlindedPayInfo, ()> {
280 let mut curr_base_fee: u64 = 0;
281 let mut curr_prop_mil: u64 = 0;
282 let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
283 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
284 // In the future, we'll want to take the intersection of all supported features for the
285 // `BlindedPayInfo`, but there are no features in that context right now.
286 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
288 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
289 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
290 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
291 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
292 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
293 .and_then(|f| f.checked_add(1_000_000 - 1))
294 .map(|f| f / 1_000_000)
295 .and_then(|f| f.checked_add(next_base_fee))
297 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
298 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
299 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
300 .and_then(|f| f.checked_add(1_000_000 - 1))
301 .map(|f| f / 1_000_000)
302 .and_then(|f| f.checked_sub(1_000_000))
305 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
308 let mut htlc_minimum_msat: u64 = 1;
309 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
310 for node in intermediate_nodes.iter() {
311 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
312 // following hops for forwarding that min, since that fee amount will automatically be included
313 // in the amount that this node receives and contribute towards reaching its min.
314 htlc_minimum_msat = amt_to_forward_msat(
315 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
316 &node.tlvs.payment_relay
317 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
318 htlc_maximum_msat = amt_to_forward_msat(
319 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
320 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
322 htlc_minimum_msat = core::cmp::max(
323 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
325 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
327 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
329 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
330 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
334 features: BlindedHopFeatures::empty(),
338 impl Writeable for PaymentRelay {
339 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
340 self.cltv_expiry_delta.write(w)?;
341 self.fee_proportional_millionths.write(w)?;
342 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
345 impl Readable for PaymentRelay {
346 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
347 let cltv_expiry_delta: u16 = Readable::read(r)?;
348 let fee_proportional_millionths: u32 = Readable::read(r)?;
349 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
350 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
354 impl Writeable for PaymentConstraints {
355 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
356 self.max_cltv_expiry.write(w)?;
357 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
360 impl Readable for PaymentConstraints {
361 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
362 let max_cltv_expiry: u32 = Readable::read(r)?;
363 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
364 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
368 impl_writeable_tlv_based_enum!(PaymentContext,
375 impl Writeable for UnknownPaymentContext {
376 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
381 impl Readable for UnknownPaymentContext {
382 fn read<R: io::Read>(_r: &mut R) -> Result<Self, DecodeError> {
383 Ok(UnknownPaymentContext(()))
387 impl_writeable_tlv_based!(Bolt12OfferContext, {
388 (0, offer_id, required),
391 impl_writeable_tlv_based!(Bolt12RefundContext, {});
395 use bitcoin::secp256k1::PublicKey;
396 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentContext, PaymentRelay};
397 use crate::ln::PaymentSecret;
398 use crate::ln::features::BlindedHopFeatures;
399 use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
402 fn compute_payinfo() {
403 // Taken from the spec example for aggregating blinded payment info. See
404 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
405 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
406 let intermediate_nodes = vec![ForwardNode {
410 payment_relay: PaymentRelay {
411 cltv_expiry_delta: 144,
412 fee_proportional_millionths: 500,
415 payment_constraints: PaymentConstraints {
417 htlc_minimum_msat: 100,
419 features: BlindedHopFeatures::empty(),
421 htlc_maximum_msat: u64::max_value(),
426 payment_relay: PaymentRelay {
427 cltv_expiry_delta: 144,
428 fee_proportional_millionths: 500,
431 payment_constraints: PaymentConstraints {
433 htlc_minimum_msat: 1_000,
435 features: BlindedHopFeatures::empty(),
437 htlc_maximum_msat: u64::max_value(),
439 let recv_tlvs = ReceiveTlvs {
440 payment_secret: PaymentSecret([0; 32]),
441 payment_constraints: PaymentConstraints {
443 htlc_minimum_msat: 1,
445 payment_context: PaymentContext::unknown(),
447 let htlc_maximum_msat = 100_000;
448 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
449 assert_eq!(blinded_payinfo.fee_base_msat, 201);
450 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
451 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
452 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
453 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
457 fn compute_payinfo_1_hop() {
458 let recv_tlvs = ReceiveTlvs {
459 payment_secret: PaymentSecret([0; 32]),
460 payment_constraints: PaymentConstraints {
462 htlc_minimum_msat: 1,
464 payment_context: PaymentContext::unknown(),
466 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
467 assert_eq!(blinded_payinfo.fee_base_msat, 0);
468 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
469 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
470 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
471 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
475 fn simple_aggregated_htlc_min() {
476 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
478 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
479 let intermediate_nodes = vec![ForwardNode {
483 payment_relay: PaymentRelay {
484 cltv_expiry_delta: 0,
485 fee_proportional_millionths: 0,
488 payment_constraints: PaymentConstraints {
490 htlc_minimum_msat: 1,
492 features: BlindedHopFeatures::empty(),
494 htlc_maximum_msat: u64::max_value()
499 payment_relay: PaymentRelay {
500 cltv_expiry_delta: 0,
501 fee_proportional_millionths: 0,
504 payment_constraints: PaymentConstraints {
506 htlc_minimum_msat: 2_000,
508 features: BlindedHopFeatures::empty(),
510 htlc_maximum_msat: u64::max_value()
512 let recv_tlvs = ReceiveTlvs {
513 payment_secret: PaymentSecret([0; 32]),
514 payment_constraints: PaymentConstraints {
516 htlc_minimum_msat: 3,
518 payment_context: PaymentContext::unknown(),
520 let htlc_maximum_msat = 100_000;
521 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
522 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
526 fn aggregated_htlc_min() {
527 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
528 // max (htlc_min - following_fees) along the path.
529 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
530 let intermediate_nodes = vec![ForwardNode {
534 payment_relay: PaymentRelay {
535 cltv_expiry_delta: 0,
536 fee_proportional_millionths: 500,
537 fee_base_msat: 1_000,
539 payment_constraints: PaymentConstraints {
541 htlc_minimum_msat: 5_000,
543 features: BlindedHopFeatures::empty(),
545 htlc_maximum_msat: u64::max_value()
550 payment_relay: PaymentRelay {
551 cltv_expiry_delta: 0,
552 fee_proportional_millionths: 500,
555 payment_constraints: PaymentConstraints {
557 htlc_minimum_msat: 2_000,
559 features: BlindedHopFeatures::empty(),
561 htlc_maximum_msat: u64::max_value()
563 let recv_tlvs = ReceiveTlvs {
564 payment_secret: PaymentSecret([0; 32]),
565 payment_constraints: PaymentConstraints {
567 htlc_minimum_msat: 1,
569 payment_context: PaymentContext::unknown(),
571 let htlc_minimum_msat = 3798;
572 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
574 let htlc_maximum_msat = htlc_minimum_msat + 1;
575 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
576 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
577 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
581 fn aggregated_htlc_max() {
582 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
583 // htlc ends up as the min (htlc_max - following_fees) along the path.
584 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
585 let intermediate_nodes = vec![ForwardNode {
589 payment_relay: PaymentRelay {
590 cltv_expiry_delta: 0,
591 fee_proportional_millionths: 500,
592 fee_base_msat: 1_000,
594 payment_constraints: PaymentConstraints {
596 htlc_minimum_msat: 1,
598 features: BlindedHopFeatures::empty(),
600 htlc_maximum_msat: 5_000,
605 payment_relay: PaymentRelay {
606 cltv_expiry_delta: 0,
607 fee_proportional_millionths: 500,
610 payment_constraints: PaymentConstraints {
612 htlc_minimum_msat: 1,
614 features: BlindedHopFeatures::empty(),
616 htlc_maximum_msat: 10_000
618 let recv_tlvs = ReceiveTlvs {
619 payment_secret: PaymentSecret([0; 32]),
620 payment_constraints: PaymentConstraints {
622 htlc_minimum_msat: 1,
624 payment_context: PaymentContext::unknown(),
627 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
628 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);