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::util::ser::{HighZeroBytesDroppedBigSize, Readable, Writeable, Writer};
17 #[allow(unused_imports)]
18 use crate::prelude::*;
20 /// An intermediate node, its outbound channel, and relay parameters.
21 #[derive(Clone, Debug)]
22 pub struct ForwardNode {
23 /// The TLVs for this node's [`BlindedHop`], where the fee parameters contained within are also
24 /// used for [`BlindedPayInfo`] construction.
25 pub tlvs: ForwardTlvs,
26 /// This node's pubkey.
27 pub node_id: PublicKey,
28 /// The maximum value, in msat, that may be accepted by this node.
29 pub htlc_maximum_msat: u64,
32 /// Data to construct a [`BlindedHop`] for forwarding a payment.
33 #[derive(Clone, Debug)]
34 pub struct ForwardTlvs {
35 /// The short channel id this payment should be forwarded out over.
36 pub short_channel_id: u64,
37 /// Payment parameters for relaying over [`Self::short_channel_id`].
38 pub payment_relay: PaymentRelay,
39 /// Payment constraints for relaying over [`Self::short_channel_id`].
40 pub payment_constraints: PaymentConstraints,
41 /// Supported and required features when relaying a payment onion containing this object's
42 /// corresponding [`BlindedHop::encrypted_payload`].
44 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
45 pub features: BlindedHopFeatures,
48 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
49 /// may not be valid if received by another lightning implementation.
50 #[derive(Clone, Debug)]
51 pub struct ReceiveTlvs {
52 /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
53 pub payment_secret: PaymentSecret,
54 /// Constraints for the receiver of this payment.
55 pub payment_constraints: PaymentConstraints,
56 /// Context for the receiver of this payment.
57 pub payment_context: PaymentContext,
60 /// Data to construct a [`BlindedHop`] for sending a payment over.
62 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
63 pub(crate) enum BlindedPaymentTlvs {
64 /// This blinded payment data is for a forwarding node.
66 /// This blinded payment data is for the receiving node.
70 // Used to include forward and receive TLVs in the same iterator for encoding.
71 enum BlindedPaymentTlvsRef<'a> {
72 Forward(&'a ForwardTlvs),
73 Receive(&'a ReceiveTlvs),
76 /// Parameters for relaying over a given [`BlindedHop`].
78 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
79 #[derive(Clone, Debug)]
80 pub struct PaymentRelay {
81 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
82 pub cltv_expiry_delta: u16,
83 /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
84 /// this [`BlindedHop`], (i.e., 10,000 is 1%).
85 pub fee_proportional_millionths: u32,
86 /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
87 pub fee_base_msat: u32,
90 /// Constraints for relaying over a given [`BlindedHop`].
92 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
93 #[derive(Clone, Debug)]
94 pub struct PaymentConstraints {
95 /// The maximum total CLTV that is acceptable when relaying a payment over this [`BlindedHop`].
96 pub max_cltv_expiry: u32,
97 /// The minimum value, in msat, that may be accepted by the node corresponding to this
99 pub htlc_minimum_msat: u64,
102 /// The context of an inbound payment, which is included in a [`BlindedPath`] via [`ReceiveTlvs`]
103 /// and surfaced in [`PaymentPurpose`].
105 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
106 /// [`PaymentPurpose`]: crate::events::PaymentPurpose
107 #[derive(Clone, Debug)]
108 pub enum PaymentContext {
109 /// The payment context was unknown.
110 Unknown(UnknownPaymentContext),
113 /// An unknown payment context.
114 #[derive(Clone, Debug)]
115 pub struct UnknownPaymentContext(());
117 impl PaymentContext {
118 pub(crate) fn unknown() -> Self {
119 PaymentContext::Unknown(UnknownPaymentContext(()))
123 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
126 fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
127 let CounterpartyForwardingInfo {
128 fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
131 // Avoid exposing esoteric CLTV expiry deltas
132 let cltv_expiry_delta = match cltv_expiry_delta {
140 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
144 impl Writeable for ForwardTlvs {
145 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
147 if self.features == BlindedHopFeatures::empty() { None }
148 else { Some(&self.features) };
149 encode_tlv_stream!(w, {
150 (2, self.short_channel_id, required),
151 (10, self.payment_relay, required),
152 (12, self.payment_constraints, required),
153 (14, features_opt, option)
159 impl Writeable for ReceiveTlvs {
160 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
161 encode_tlv_stream!(w, {
162 (12, self.payment_constraints, required),
163 (65536, self.payment_secret, required),
164 (65537, self.payment_context, required)
170 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
171 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
172 // TODO: write padding
174 Self::Forward(tlvs) => tlvs.write(w)?,
175 Self::Receive(tlvs) => tlvs.write(w)?,
181 impl Readable for BlindedPaymentTlvs {
182 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
183 _init_and_read_tlv_stream!(r, {
184 (1, _padding, option),
186 (10, payment_relay, option),
187 (12, payment_constraints, required),
188 (14, features, option),
189 (65536, payment_secret, option),
190 (65537, payment_context, (default_value, PaymentContext::unknown())),
192 let _padding: Option<utils::Padding> = _padding;
194 if let Some(short_channel_id) = scid {
195 if payment_secret.is_some() {
196 return Err(DecodeError::InvalidValue)
198 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
200 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
201 payment_constraints: payment_constraints.0.unwrap(),
202 features: features.unwrap_or_else(BlindedHopFeatures::empty),
205 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
206 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
207 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
208 payment_constraints: payment_constraints.0.unwrap(),
209 payment_context: payment_context.0.unwrap(),
215 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
216 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
217 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
218 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
219 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
220 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
221 .chain(core::iter::once(&payee_node_id));
222 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
223 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
224 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
227 /// `None` if underflow occurs.
228 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
229 let inbound_amt = inbound_amt_msat as u128;
230 let base = payment_relay.fee_base_msat as u128;
231 let prop = payment_relay.fee_proportional_millionths as u128;
233 let post_base_fee_inbound_amt =
234 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
235 let mut amt_to_forward =
236 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
238 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
239 if inbound_amt - fee < amt_to_forward {
240 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
241 // in fee to compensate.
244 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
245 u64::try_from(amt_to_forward).ok()
248 pub(super) fn compute_payinfo(
249 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
250 min_final_cltv_expiry_delta: u16
251 ) -> Result<BlindedPayInfo, ()> {
252 let mut curr_base_fee: u64 = 0;
253 let mut curr_prop_mil: u64 = 0;
254 let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
255 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
256 // In the future, we'll want to take the intersection of all supported features for the
257 // `BlindedPayInfo`, but there are no features in that context right now.
258 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
260 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
261 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
262 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
263 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
264 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
265 .and_then(|f| f.checked_add(1_000_000 - 1))
266 .map(|f| f / 1_000_000)
267 .and_then(|f| f.checked_add(next_base_fee))
269 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
270 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
271 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
272 .and_then(|f| f.checked_add(1_000_000 - 1))
273 .map(|f| f / 1_000_000)
274 .and_then(|f| f.checked_sub(1_000_000))
277 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
280 let mut htlc_minimum_msat: u64 = 1;
281 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
282 for node in intermediate_nodes.iter() {
283 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
284 // following hops for forwarding that min, since that fee amount will automatically be included
285 // in the amount that this node receives and contribute towards reaching its min.
286 htlc_minimum_msat = amt_to_forward_msat(
287 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
288 &node.tlvs.payment_relay
289 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
290 htlc_maximum_msat = amt_to_forward_msat(
291 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
292 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
294 htlc_minimum_msat = core::cmp::max(
295 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
297 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
299 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
301 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
302 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
306 features: BlindedHopFeatures::empty(),
310 impl Writeable for PaymentRelay {
311 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
312 self.cltv_expiry_delta.write(w)?;
313 self.fee_proportional_millionths.write(w)?;
314 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
317 impl Readable for PaymentRelay {
318 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
319 let cltv_expiry_delta: u16 = Readable::read(r)?;
320 let fee_proportional_millionths: u32 = Readable::read(r)?;
321 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
322 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
326 impl Writeable for PaymentConstraints {
327 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
328 self.max_cltv_expiry.write(w)?;
329 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
332 impl Readable for PaymentConstraints {
333 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
334 let max_cltv_expiry: u32 = Readable::read(r)?;
335 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
336 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
340 impl_writeable_tlv_based_enum!(PaymentContext,
345 impl Writeable for UnknownPaymentContext {
346 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
351 impl Readable for UnknownPaymentContext {
352 fn read<R: io::Read>(_r: &mut R) -> Result<Self, DecodeError> {
353 Ok(UnknownPaymentContext(()))
359 use bitcoin::secp256k1::PublicKey;
360 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentContext, PaymentRelay};
361 use crate::ln::PaymentSecret;
362 use crate::ln::features::BlindedHopFeatures;
363 use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
366 fn compute_payinfo() {
367 // Taken from the spec example for aggregating blinded payment info. See
368 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
369 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
370 let intermediate_nodes = vec![ForwardNode {
374 payment_relay: PaymentRelay {
375 cltv_expiry_delta: 144,
376 fee_proportional_millionths: 500,
379 payment_constraints: PaymentConstraints {
381 htlc_minimum_msat: 100,
383 features: BlindedHopFeatures::empty(),
385 htlc_maximum_msat: u64::max_value(),
390 payment_relay: PaymentRelay {
391 cltv_expiry_delta: 144,
392 fee_proportional_millionths: 500,
395 payment_constraints: PaymentConstraints {
397 htlc_minimum_msat: 1_000,
399 features: BlindedHopFeatures::empty(),
401 htlc_maximum_msat: u64::max_value(),
403 let recv_tlvs = ReceiveTlvs {
404 payment_secret: PaymentSecret([0; 32]),
405 payment_constraints: PaymentConstraints {
407 htlc_minimum_msat: 1,
409 payment_context: PaymentContext::unknown(),
411 let htlc_maximum_msat = 100_000;
412 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
413 assert_eq!(blinded_payinfo.fee_base_msat, 201);
414 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
415 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
416 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
417 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
421 fn compute_payinfo_1_hop() {
422 let recv_tlvs = ReceiveTlvs {
423 payment_secret: PaymentSecret([0; 32]),
424 payment_constraints: PaymentConstraints {
426 htlc_minimum_msat: 1,
428 payment_context: PaymentContext::unknown(),
430 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
431 assert_eq!(blinded_payinfo.fee_base_msat, 0);
432 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
433 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
434 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
435 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
439 fn simple_aggregated_htlc_min() {
440 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
442 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
443 let intermediate_nodes = vec![ForwardNode {
447 payment_relay: PaymentRelay {
448 cltv_expiry_delta: 0,
449 fee_proportional_millionths: 0,
452 payment_constraints: PaymentConstraints {
454 htlc_minimum_msat: 1,
456 features: BlindedHopFeatures::empty(),
458 htlc_maximum_msat: u64::max_value()
463 payment_relay: PaymentRelay {
464 cltv_expiry_delta: 0,
465 fee_proportional_millionths: 0,
468 payment_constraints: PaymentConstraints {
470 htlc_minimum_msat: 2_000,
472 features: BlindedHopFeatures::empty(),
474 htlc_maximum_msat: u64::max_value()
476 let recv_tlvs = ReceiveTlvs {
477 payment_secret: PaymentSecret([0; 32]),
478 payment_constraints: PaymentConstraints {
480 htlc_minimum_msat: 3,
482 payment_context: PaymentContext::unknown(),
484 let htlc_maximum_msat = 100_000;
485 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
486 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
490 fn aggregated_htlc_min() {
491 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
492 // max (htlc_min - following_fees) along the path.
493 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
494 let intermediate_nodes = vec![ForwardNode {
498 payment_relay: PaymentRelay {
499 cltv_expiry_delta: 0,
500 fee_proportional_millionths: 500,
501 fee_base_msat: 1_000,
503 payment_constraints: PaymentConstraints {
505 htlc_minimum_msat: 5_000,
507 features: BlindedHopFeatures::empty(),
509 htlc_maximum_msat: u64::max_value()
514 payment_relay: PaymentRelay {
515 cltv_expiry_delta: 0,
516 fee_proportional_millionths: 500,
519 payment_constraints: PaymentConstraints {
521 htlc_minimum_msat: 2_000,
523 features: BlindedHopFeatures::empty(),
525 htlc_maximum_msat: u64::max_value()
527 let recv_tlvs = ReceiveTlvs {
528 payment_secret: PaymentSecret([0; 32]),
529 payment_constraints: PaymentConstraints {
531 htlc_minimum_msat: 1,
533 payment_context: PaymentContext::unknown(),
535 let htlc_minimum_msat = 3798;
536 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
538 let htlc_maximum_msat = htlc_minimum_msat + 1;
539 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
540 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
541 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
545 fn aggregated_htlc_max() {
546 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
547 // htlc ends up as the min (htlc_max - following_fees) along the path.
548 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
549 let intermediate_nodes = vec![ForwardNode {
553 payment_relay: PaymentRelay {
554 cltv_expiry_delta: 0,
555 fee_proportional_millionths: 500,
556 fee_base_msat: 1_000,
558 payment_constraints: PaymentConstraints {
560 htlc_minimum_msat: 1,
562 features: BlindedHopFeatures::empty(),
564 htlc_maximum_msat: 5_000,
569 payment_relay: PaymentRelay {
570 cltv_expiry_delta: 0,
571 fee_proportional_millionths: 500,
574 payment_constraints: PaymentConstraints {
576 htlc_minimum_msat: 1,
578 features: BlindedHopFeatures::empty(),
580 htlc_maximum_msat: 10_000
582 let recv_tlvs = ReceiveTlvs {
583 payment_secret: PaymentSecret([0; 32]),
584 payment_constraints: PaymentConstraints {
586 htlc_minimum_msat: 1,
588 payment_context: PaymentContext::unknown(),
591 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
592 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);