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,
58 /// Data to construct a [`BlindedHop`] for sending a payment over.
60 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
61 pub(crate) enum BlindedPaymentTlvs {
62 /// This blinded payment data is for a forwarding node.
64 /// This blinded payment data is for the receiving node.
68 // Used to include forward and receive TLVs in the same iterator for encoding.
69 enum BlindedPaymentTlvsRef<'a> {
70 Forward(&'a ForwardTlvs),
71 Receive(&'a ReceiveTlvs),
74 /// Parameters for relaying over a given [`BlindedHop`].
76 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
77 #[derive(Clone, Debug)]
78 pub struct PaymentRelay {
79 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
80 pub cltv_expiry_delta: u16,
81 /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
82 /// this [`BlindedHop`], (i.e., 10,000 is 1%).
83 pub fee_proportional_millionths: u32,
84 /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
85 pub fee_base_msat: u32,
88 /// Constraints for relaying over a given [`BlindedHop`].
90 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
91 #[derive(Clone, Debug)]
92 pub struct PaymentConstraints {
93 /// The maximum total CLTV that is acceptable when relaying a payment over this [`BlindedHop`].
94 pub max_cltv_expiry: u32,
95 /// The minimum value, in msat, that may be accepted by the node corresponding to this
97 pub htlc_minimum_msat: u64,
100 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
103 fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
104 let CounterpartyForwardingInfo {
105 fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
108 // Avoid exposing esoteric CLTV expiry deltas
109 let cltv_expiry_delta = match cltv_expiry_delta {
117 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
121 impl Writeable for ForwardTlvs {
122 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
124 if self.features == BlindedHopFeatures::empty() { None }
125 else { Some(&self.features) };
126 encode_tlv_stream!(w, {
127 (2, self.short_channel_id, required),
128 (10, self.payment_relay, required),
129 (12, self.payment_constraints, required),
130 (14, features_opt, option)
136 impl Writeable for ReceiveTlvs {
137 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
138 encode_tlv_stream!(w, {
139 (12, self.payment_constraints, required),
140 (65536, self.payment_secret, required)
146 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
147 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
148 // TODO: write padding
150 Self::Forward(tlvs) => tlvs.write(w)?,
151 Self::Receive(tlvs) => tlvs.write(w)?,
157 impl Readable for BlindedPaymentTlvs {
158 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
159 _init_and_read_tlv_stream!(r, {
160 (1, _padding, option),
162 (10, payment_relay, option),
163 (12, payment_constraints, required),
164 (14, features, option),
165 (65536, payment_secret, option),
167 let _padding: Option<utils::Padding> = _padding;
169 if let Some(short_channel_id) = scid {
170 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
171 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
173 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
174 payment_constraints: payment_constraints.0.unwrap(),
175 features: features.unwrap_or_else(BlindedHopFeatures::empty),
178 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
179 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
180 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
181 payment_constraints: payment_constraints.0.unwrap(),
187 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
188 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
189 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
190 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
191 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
192 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
193 .chain(core::iter::once(&payee_node_id));
194 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
195 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
196 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
199 /// `None` if underflow occurs.
200 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
201 let inbound_amt = inbound_amt_msat as u128;
202 let base = payment_relay.fee_base_msat as u128;
203 let prop = payment_relay.fee_proportional_millionths as u128;
205 let post_base_fee_inbound_amt =
206 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
207 let mut amt_to_forward =
208 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
210 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
211 if inbound_amt - fee < amt_to_forward {
212 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
213 // in fee to compensate.
216 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
217 u64::try_from(amt_to_forward).ok()
220 pub(super) fn compute_payinfo(
221 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
222 min_final_cltv_expiry_delta: u16
223 ) -> Result<BlindedPayInfo, ()> {
224 let mut curr_base_fee: u64 = 0;
225 let mut curr_prop_mil: u64 = 0;
226 let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
227 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
228 // In the future, we'll want to take the intersection of all supported features for the
229 // `BlindedPayInfo`, but there are no features in that context right now.
230 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
232 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
233 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
234 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
235 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
236 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
237 .and_then(|f| f.checked_add(1_000_000 - 1))
238 .map(|f| f / 1_000_000)
239 .and_then(|f| f.checked_add(next_base_fee))
241 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
242 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
243 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
244 .and_then(|f| f.checked_add(1_000_000 - 1))
245 .map(|f| f / 1_000_000)
246 .and_then(|f| f.checked_sub(1_000_000))
249 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
252 let mut htlc_minimum_msat: u64 = 1;
253 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
254 for node in intermediate_nodes.iter() {
255 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
256 // following hops for forwarding that min, since that fee amount will automatically be included
257 // in the amount that this node receives and contribute towards reaching its min.
258 htlc_minimum_msat = amt_to_forward_msat(
259 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
260 &node.tlvs.payment_relay
261 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
262 htlc_maximum_msat = amt_to_forward_msat(
263 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
264 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
266 htlc_minimum_msat = core::cmp::max(
267 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
269 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
271 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
273 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
274 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
278 features: BlindedHopFeatures::empty(),
282 impl Writeable for PaymentRelay {
283 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
284 self.cltv_expiry_delta.write(w)?;
285 self.fee_proportional_millionths.write(w)?;
286 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
289 impl Readable for PaymentRelay {
290 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
291 let cltv_expiry_delta: u16 = Readable::read(r)?;
292 let fee_proportional_millionths: u32 = Readable::read(r)?;
293 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
294 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
298 impl Writeable for PaymentConstraints {
299 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
300 self.max_cltv_expiry.write(w)?;
301 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
304 impl Readable for PaymentConstraints {
305 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
306 let max_cltv_expiry: u32 = Readable::read(r)?;
307 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
308 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
314 use bitcoin::secp256k1::PublicKey;
315 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
316 use crate::ln::PaymentSecret;
317 use crate::ln::features::BlindedHopFeatures;
318 use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
321 fn compute_payinfo() {
322 // Taken from the spec example for aggregating blinded payment info. See
323 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
324 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
325 let intermediate_nodes = vec![ForwardNode {
329 payment_relay: PaymentRelay {
330 cltv_expiry_delta: 144,
331 fee_proportional_millionths: 500,
334 payment_constraints: PaymentConstraints {
336 htlc_minimum_msat: 100,
338 features: BlindedHopFeatures::empty(),
340 htlc_maximum_msat: u64::max_value(),
345 payment_relay: PaymentRelay {
346 cltv_expiry_delta: 144,
347 fee_proportional_millionths: 500,
350 payment_constraints: PaymentConstraints {
352 htlc_minimum_msat: 1_000,
354 features: BlindedHopFeatures::empty(),
356 htlc_maximum_msat: u64::max_value(),
358 let recv_tlvs = ReceiveTlvs {
359 payment_secret: PaymentSecret([0; 32]),
360 payment_constraints: PaymentConstraints {
362 htlc_minimum_msat: 1,
365 let htlc_maximum_msat = 100_000;
366 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
367 assert_eq!(blinded_payinfo.fee_base_msat, 201);
368 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
369 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
370 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
371 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
375 fn compute_payinfo_1_hop() {
376 let recv_tlvs = ReceiveTlvs {
377 payment_secret: PaymentSecret([0; 32]),
378 payment_constraints: PaymentConstraints {
380 htlc_minimum_msat: 1,
383 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
384 assert_eq!(blinded_payinfo.fee_base_msat, 0);
385 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
386 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
387 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
388 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
392 fn simple_aggregated_htlc_min() {
393 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
395 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
396 let intermediate_nodes = vec![ForwardNode {
400 payment_relay: PaymentRelay {
401 cltv_expiry_delta: 0,
402 fee_proportional_millionths: 0,
405 payment_constraints: PaymentConstraints {
407 htlc_minimum_msat: 1,
409 features: BlindedHopFeatures::empty(),
411 htlc_maximum_msat: u64::max_value()
416 payment_relay: PaymentRelay {
417 cltv_expiry_delta: 0,
418 fee_proportional_millionths: 0,
421 payment_constraints: PaymentConstraints {
423 htlc_minimum_msat: 2_000,
425 features: BlindedHopFeatures::empty(),
427 htlc_maximum_msat: u64::max_value()
429 let recv_tlvs = ReceiveTlvs {
430 payment_secret: PaymentSecret([0; 32]),
431 payment_constraints: PaymentConstraints {
433 htlc_minimum_msat: 3,
436 let htlc_maximum_msat = 100_000;
437 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
438 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
442 fn aggregated_htlc_min() {
443 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
444 // max (htlc_min - following_fees) along the path.
445 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
446 let intermediate_nodes = vec![ForwardNode {
450 payment_relay: PaymentRelay {
451 cltv_expiry_delta: 0,
452 fee_proportional_millionths: 500,
453 fee_base_msat: 1_000,
455 payment_constraints: PaymentConstraints {
457 htlc_minimum_msat: 5_000,
459 features: BlindedHopFeatures::empty(),
461 htlc_maximum_msat: u64::max_value()
466 payment_relay: PaymentRelay {
467 cltv_expiry_delta: 0,
468 fee_proportional_millionths: 500,
471 payment_constraints: PaymentConstraints {
473 htlc_minimum_msat: 2_000,
475 features: BlindedHopFeatures::empty(),
477 htlc_maximum_msat: u64::max_value()
479 let recv_tlvs = ReceiveTlvs {
480 payment_secret: PaymentSecret([0; 32]),
481 payment_constraints: PaymentConstraints {
483 htlc_minimum_msat: 1,
486 let htlc_minimum_msat = 3798;
487 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
489 let htlc_maximum_msat = htlc_minimum_msat + 1;
490 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
491 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
492 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
496 fn aggregated_htlc_max() {
497 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
498 // htlc ends up as the min (htlc_max - following_fees) along the path.
499 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
500 let intermediate_nodes = vec![ForwardNode {
504 payment_relay: PaymentRelay {
505 cltv_expiry_delta: 0,
506 fee_proportional_millionths: 500,
507 fee_base_msat: 1_000,
509 payment_constraints: PaymentConstraints {
511 htlc_minimum_msat: 1,
513 features: BlindedHopFeatures::empty(),
515 htlc_maximum_msat: 5_000,
520 payment_relay: PaymentRelay {
521 cltv_expiry_delta: 0,
522 fee_proportional_millionths: 500,
525 payment_constraints: PaymentConstraints {
527 htlc_minimum_msat: 1,
529 features: BlindedHopFeatures::empty(),
531 htlc_maximum_msat: 10_000
533 let recv_tlvs = ReceiveTlvs {
534 payment_secret: PaymentSecret([0; 32]),
535 payment_constraints: PaymentConstraints {
537 htlc_minimum_msat: 1,
541 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
542 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);