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),
119 /// An unknown payment context.
120 #[derive(Clone, Debug, Eq, PartialEq)]
121 pub struct UnknownPaymentContext(());
123 /// The context of a payment made for an invoice requested from a BOLT 12 [`Offer`].
125 /// [`Offer`]: crate::offers::offer::Offer
126 #[derive(Clone, Debug, Eq, PartialEq)]
127 pub struct Bolt12OfferContext {
128 /// The identifier of the [`Offer`].
130 /// [`Offer`]: crate::offers::offer::Offer
131 pub offer_id: OfferId,
134 impl PaymentContext {
135 pub(crate) fn unknown() -> Self {
136 PaymentContext::Unknown(UnknownPaymentContext(()))
140 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
143 fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
144 let CounterpartyForwardingInfo {
145 fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
148 // Avoid exposing esoteric CLTV expiry deltas
149 let cltv_expiry_delta = match cltv_expiry_delta {
157 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
161 impl Writeable for ForwardTlvs {
162 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
164 if self.features == BlindedHopFeatures::empty() { None }
165 else { Some(&self.features) };
166 encode_tlv_stream!(w, {
167 (2, self.short_channel_id, required),
168 (10, self.payment_relay, required),
169 (12, self.payment_constraints, required),
170 (14, features_opt, option)
176 impl Writeable for ReceiveTlvs {
177 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
178 encode_tlv_stream!(w, {
179 (12, self.payment_constraints, required),
180 (65536, self.payment_secret, required),
181 (65537, self.payment_context, required)
187 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
188 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
189 // TODO: write padding
191 Self::Forward(tlvs) => tlvs.write(w)?,
192 Self::Receive(tlvs) => tlvs.write(w)?,
198 impl Readable for BlindedPaymentTlvs {
199 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
200 _init_and_read_tlv_stream!(r, {
201 (1, _padding, option),
203 (10, payment_relay, option),
204 (12, payment_constraints, required),
205 (14, features, option),
206 (65536, payment_secret, option),
207 (65537, payment_context, (default_value, PaymentContext::unknown())),
209 let _padding: Option<utils::Padding> = _padding;
211 if let Some(short_channel_id) = scid {
212 if payment_secret.is_some() {
213 return Err(DecodeError::InvalidValue)
215 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
217 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
218 payment_constraints: payment_constraints.0.unwrap(),
219 features: features.unwrap_or_else(BlindedHopFeatures::empty),
222 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
223 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
224 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
225 payment_constraints: payment_constraints.0.unwrap(),
226 payment_context: payment_context.0.unwrap(),
232 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
233 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
234 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
235 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
236 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
237 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
238 .chain(core::iter::once(&payee_node_id));
239 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
240 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
241 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
244 /// `None` if underflow occurs.
245 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
246 let inbound_amt = inbound_amt_msat as u128;
247 let base = payment_relay.fee_base_msat as u128;
248 let prop = payment_relay.fee_proportional_millionths as u128;
250 let post_base_fee_inbound_amt =
251 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
252 let mut amt_to_forward =
253 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
255 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
256 if inbound_amt - fee < amt_to_forward {
257 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
258 // in fee to compensate.
261 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
262 u64::try_from(amt_to_forward).ok()
265 pub(super) fn compute_payinfo(
266 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
267 min_final_cltv_expiry_delta: u16
268 ) -> Result<BlindedPayInfo, ()> {
269 let mut curr_base_fee: u64 = 0;
270 let mut curr_prop_mil: u64 = 0;
271 let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
272 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
273 // In the future, we'll want to take the intersection of all supported features for the
274 // `BlindedPayInfo`, but there are no features in that context right now.
275 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
277 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
278 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
279 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
280 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
281 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
282 .and_then(|f| f.checked_add(1_000_000 - 1))
283 .map(|f| f / 1_000_000)
284 .and_then(|f| f.checked_add(next_base_fee))
286 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
287 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
288 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
289 .and_then(|f| f.checked_add(1_000_000 - 1))
290 .map(|f| f / 1_000_000)
291 .and_then(|f| f.checked_sub(1_000_000))
294 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
297 let mut htlc_minimum_msat: u64 = 1;
298 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
299 for node in intermediate_nodes.iter() {
300 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
301 // following hops for forwarding that min, since that fee amount will automatically be included
302 // in the amount that this node receives and contribute towards reaching its min.
303 htlc_minimum_msat = amt_to_forward_msat(
304 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
305 &node.tlvs.payment_relay
306 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
307 htlc_maximum_msat = amt_to_forward_msat(
308 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
309 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
311 htlc_minimum_msat = core::cmp::max(
312 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
314 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
316 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
318 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
319 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
323 features: BlindedHopFeatures::empty(),
327 impl Writeable for PaymentRelay {
328 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
329 self.cltv_expiry_delta.write(w)?;
330 self.fee_proportional_millionths.write(w)?;
331 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
334 impl Readable for PaymentRelay {
335 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
336 let cltv_expiry_delta: u16 = Readable::read(r)?;
337 let fee_proportional_millionths: u32 = Readable::read(r)?;
338 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
339 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
343 impl Writeable for PaymentConstraints {
344 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
345 self.max_cltv_expiry.write(w)?;
346 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
349 impl Readable for PaymentConstraints {
350 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
351 let max_cltv_expiry: u32 = Readable::read(r)?;
352 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
353 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
357 impl_writeable_tlv_based_enum!(PaymentContext,
363 impl Writeable for UnknownPaymentContext {
364 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
369 impl Readable for UnknownPaymentContext {
370 fn read<R: io::Read>(_r: &mut R) -> Result<Self, DecodeError> {
371 Ok(UnknownPaymentContext(()))
375 impl_writeable_tlv_based!(Bolt12OfferContext, {
376 (0, offer_id, required),
381 use bitcoin::secp256k1::PublicKey;
382 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentContext, PaymentRelay};
383 use crate::ln::PaymentSecret;
384 use crate::ln::features::BlindedHopFeatures;
385 use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
388 fn compute_payinfo() {
389 // Taken from the spec example for aggregating blinded payment info. See
390 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
391 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
392 let intermediate_nodes = vec![ForwardNode {
396 payment_relay: PaymentRelay {
397 cltv_expiry_delta: 144,
398 fee_proportional_millionths: 500,
401 payment_constraints: PaymentConstraints {
403 htlc_minimum_msat: 100,
405 features: BlindedHopFeatures::empty(),
407 htlc_maximum_msat: u64::max_value(),
412 payment_relay: PaymentRelay {
413 cltv_expiry_delta: 144,
414 fee_proportional_millionths: 500,
417 payment_constraints: PaymentConstraints {
419 htlc_minimum_msat: 1_000,
421 features: BlindedHopFeatures::empty(),
423 htlc_maximum_msat: u64::max_value(),
425 let recv_tlvs = ReceiveTlvs {
426 payment_secret: PaymentSecret([0; 32]),
427 payment_constraints: PaymentConstraints {
429 htlc_minimum_msat: 1,
431 payment_context: PaymentContext::unknown(),
433 let htlc_maximum_msat = 100_000;
434 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
435 assert_eq!(blinded_payinfo.fee_base_msat, 201);
436 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
437 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
438 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
439 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
443 fn compute_payinfo_1_hop() {
444 let recv_tlvs = ReceiveTlvs {
445 payment_secret: PaymentSecret([0; 32]),
446 payment_constraints: PaymentConstraints {
448 htlc_minimum_msat: 1,
450 payment_context: PaymentContext::unknown(),
452 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
453 assert_eq!(blinded_payinfo.fee_base_msat, 0);
454 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
455 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
456 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
457 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
461 fn simple_aggregated_htlc_min() {
462 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
464 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
465 let intermediate_nodes = vec![ForwardNode {
469 payment_relay: PaymentRelay {
470 cltv_expiry_delta: 0,
471 fee_proportional_millionths: 0,
474 payment_constraints: PaymentConstraints {
476 htlc_minimum_msat: 1,
478 features: BlindedHopFeatures::empty(),
480 htlc_maximum_msat: u64::max_value()
485 payment_relay: PaymentRelay {
486 cltv_expiry_delta: 0,
487 fee_proportional_millionths: 0,
490 payment_constraints: PaymentConstraints {
492 htlc_minimum_msat: 2_000,
494 features: BlindedHopFeatures::empty(),
496 htlc_maximum_msat: u64::max_value()
498 let recv_tlvs = ReceiveTlvs {
499 payment_secret: PaymentSecret([0; 32]),
500 payment_constraints: PaymentConstraints {
502 htlc_minimum_msat: 3,
504 payment_context: PaymentContext::unknown(),
506 let htlc_maximum_msat = 100_000;
507 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
508 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
512 fn aggregated_htlc_min() {
513 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
514 // max (htlc_min - following_fees) along the path.
515 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
516 let intermediate_nodes = vec![ForwardNode {
520 payment_relay: PaymentRelay {
521 cltv_expiry_delta: 0,
522 fee_proportional_millionths: 500,
523 fee_base_msat: 1_000,
525 payment_constraints: PaymentConstraints {
527 htlc_minimum_msat: 5_000,
529 features: BlindedHopFeatures::empty(),
531 htlc_maximum_msat: u64::max_value()
536 payment_relay: PaymentRelay {
537 cltv_expiry_delta: 0,
538 fee_proportional_millionths: 500,
541 payment_constraints: PaymentConstraints {
543 htlc_minimum_msat: 2_000,
545 features: BlindedHopFeatures::empty(),
547 htlc_maximum_msat: u64::max_value()
549 let recv_tlvs = ReceiveTlvs {
550 payment_secret: PaymentSecret([0; 32]),
551 payment_constraints: PaymentConstraints {
553 htlc_minimum_msat: 1,
555 payment_context: PaymentContext::unknown(),
557 let htlc_minimum_msat = 3798;
558 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
560 let htlc_maximum_msat = htlc_minimum_msat + 1;
561 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
562 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
563 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
567 fn aggregated_htlc_max() {
568 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
569 // htlc ends up as the min (htlc_max - following_fees) along the path.
570 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
571 let intermediate_nodes = vec![ForwardNode {
575 payment_relay: PaymentRelay {
576 cltv_expiry_delta: 0,
577 fee_proportional_millionths: 500,
578 fee_base_msat: 1_000,
580 payment_constraints: PaymentConstraints {
582 htlc_minimum_msat: 1,
584 features: BlindedHopFeatures::empty(),
586 htlc_maximum_msat: 5_000,
591 payment_relay: PaymentRelay {
592 cltv_expiry_delta: 0,
593 fee_proportional_millionths: 500,
596 payment_constraints: PaymentConstraints {
598 htlc_minimum_msat: 1,
600 features: BlindedHopFeatures::empty(),
602 htlc_maximum_msat: 10_000
604 let recv_tlvs = ReceiveTlvs {
605 payment_secret: PaymentSecret([0; 32]),
606 payment_constraints: PaymentConstraints {
608 htlc_minimum_msat: 1,
610 payment_context: PaymentContext::unknown(),
613 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
614 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);