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 /// An intermediate node, its outbound channel, and relay parameters.
20 #[derive(Clone, Debug)]
21 pub struct ForwardNode {
22 /// The TLVs for this node's [`BlindedHop`], where the fee parameters contained within are also
23 /// used for [`BlindedPayInfo`] construction.
24 pub tlvs: ForwardTlvs,
25 /// This node's pubkey.
26 pub node_id: PublicKey,
27 /// The maximum value, in msat, that may be accepted by this node.
28 pub htlc_maximum_msat: u64,
31 /// Data to construct a [`BlindedHop`] for forwarding a payment.
32 #[derive(Clone, Debug)]
33 pub struct ForwardTlvs {
34 /// The short channel id this payment should be forwarded out over.
35 pub short_channel_id: u64,
36 /// Payment parameters for relaying over [`Self::short_channel_id`].
37 pub payment_relay: PaymentRelay,
38 /// Payment constraints for relaying over [`Self::short_channel_id`].
39 pub payment_constraints: PaymentConstraints,
40 /// Supported and required features when relaying a payment onion containing this object's
41 /// corresponding [`BlindedHop::encrypted_payload`].
43 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
44 pub features: BlindedHopFeatures,
47 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
48 /// may not be valid if received by another lightning implementation.
49 #[derive(Clone, Debug)]
50 pub struct ReceiveTlvs {
51 /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
52 pub payment_secret: PaymentSecret,
53 /// Constraints for the receiver of this payment.
54 pub payment_constraints: PaymentConstraints,
57 /// Data to construct a [`BlindedHop`] for sending a payment over.
59 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
60 pub(crate) enum BlindedPaymentTlvs {
61 /// This blinded payment data is for a forwarding node.
63 /// This blinded payment data is for the receiving node.
67 // Used to include forward and receive TLVs in the same iterator for encoding.
68 enum BlindedPaymentTlvsRef<'a> {
69 Forward(&'a ForwardTlvs),
70 Receive(&'a ReceiveTlvs),
73 /// Parameters for relaying over a given [`BlindedHop`].
75 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
76 #[derive(Clone, Debug)]
77 pub struct PaymentRelay {
78 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
79 pub cltv_expiry_delta: u16,
80 /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
81 /// this [`BlindedHop`], (i.e., 10,000 is 1%).
82 pub fee_proportional_millionths: u32,
83 /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
84 pub fee_base_msat: u32,
87 /// Constraints for relaying over a given [`BlindedHop`].
89 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
90 #[derive(Clone, Debug)]
91 pub struct PaymentConstraints {
92 /// The maximum total CLTV that is acceptable when relaying a payment over this [`BlindedHop`].
93 pub max_cltv_expiry: u32,
94 /// The minimum value, in msat, that may be accepted by the node corresponding to this
96 pub htlc_minimum_msat: u64,
99 impl Writeable for ForwardTlvs {
100 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
101 encode_tlv_stream!(w, {
102 (2, self.short_channel_id, required),
103 (10, self.payment_relay, required),
104 (12, self.payment_constraints, required),
105 (14, self.features, required)
111 impl Writeable for ReceiveTlvs {
112 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
113 encode_tlv_stream!(w, {
114 (12, self.payment_constraints, required),
115 (65536, self.payment_secret, required)
121 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
122 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
123 // TODO: write padding
125 Self::Forward(tlvs) => tlvs.write(w)?,
126 Self::Receive(tlvs) => tlvs.write(w)?,
132 impl Readable for BlindedPaymentTlvs {
133 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
134 _init_and_read_tlv_stream!(r, {
135 (1, _padding, option),
137 (10, payment_relay, option),
138 (12, payment_constraints, required),
139 (14, features, option),
140 (65536, payment_secret, option),
142 let _padding: Option<utils::Padding> = _padding;
144 if let Some(short_channel_id) = scid {
145 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
146 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
148 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
149 payment_constraints: payment_constraints.0.unwrap(),
150 features: features.ok_or(DecodeError::InvalidValue)?,
153 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
154 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
155 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
156 payment_constraints: payment_constraints.0.unwrap(),
162 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
163 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
164 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
165 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
166 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
167 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
168 .chain(core::iter::once(&payee_node_id));
169 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
170 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
171 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
174 /// `None` if underflow occurs.
175 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
176 let inbound_amt = inbound_amt_msat as u128;
177 let base = payment_relay.fee_base_msat as u128;
178 let prop = payment_relay.fee_proportional_millionths as u128;
180 let post_base_fee_inbound_amt =
181 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
182 let mut amt_to_forward =
183 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
185 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
186 if inbound_amt - fee < amt_to_forward {
187 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
188 // in fee to compensate.
191 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
192 u64::try_from(amt_to_forward).ok()
195 pub(super) fn compute_payinfo(
196 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64
197 ) -> Result<BlindedPayInfo, ()> {
198 let mut curr_base_fee: u64 = 0;
199 let mut curr_prop_mil: u64 = 0;
200 let mut cltv_expiry_delta: u16 = 0;
201 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
202 // In the future, we'll want to take the intersection of all supported features for the
203 // `BlindedPayInfo`, but there are no features in that context right now.
204 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
206 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
207 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
208 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
209 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
210 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
211 .and_then(|f| f.checked_add(1_000_000 - 1))
212 .map(|f| f / 1_000_000)
213 .and_then(|f| f.checked_add(next_base_fee))
215 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
216 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
217 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
218 .and_then(|f| f.checked_add(1_000_000 - 1))
219 .map(|f| f / 1_000_000)
220 .and_then(|f| f.checked_sub(1_000_000))
223 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
226 let mut htlc_minimum_msat: u64 = 1;
227 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
228 for node in intermediate_nodes.iter() {
229 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
230 // following hops for forwarding that min, since that fee amount will automatically be included
231 // in the amount that this node receives and contribute towards reaching its min.
232 htlc_minimum_msat = amt_to_forward_msat(
233 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
234 &node.tlvs.payment_relay
235 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
236 htlc_maximum_msat = amt_to_forward_msat(
237 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
238 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
240 htlc_minimum_msat = core::cmp::max(
241 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
243 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
245 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
247 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
248 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
252 features: BlindedHopFeatures::empty(),
256 impl_writeable_msg!(PaymentRelay, {
258 fee_proportional_millionths,
262 impl_writeable_msg!(PaymentConstraints, {
269 use bitcoin::secp256k1::PublicKey;
270 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
271 use crate::ln::PaymentSecret;
272 use crate::ln::features::BlindedHopFeatures;
275 fn compute_payinfo() {
276 // Taken from the spec example for aggregating blinded payment info. See
277 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
278 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
279 let intermediate_nodes = vec![ForwardNode {
283 payment_relay: PaymentRelay {
284 cltv_expiry_delta: 144,
285 fee_proportional_millionths: 500,
288 payment_constraints: PaymentConstraints {
290 htlc_minimum_msat: 100,
292 features: BlindedHopFeatures::empty(),
294 htlc_maximum_msat: u64::max_value(),
299 payment_relay: PaymentRelay {
300 cltv_expiry_delta: 144,
301 fee_proportional_millionths: 500,
304 payment_constraints: PaymentConstraints {
306 htlc_minimum_msat: 1_000,
308 features: BlindedHopFeatures::empty(),
310 htlc_maximum_msat: u64::max_value(),
312 let recv_tlvs = ReceiveTlvs {
313 payment_secret: PaymentSecret([0; 32]),
314 payment_constraints: PaymentConstraints {
316 htlc_minimum_msat: 1,
319 let htlc_maximum_msat = 100_000;
320 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
321 assert_eq!(blinded_payinfo.fee_base_msat, 201);
322 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
323 assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
324 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
325 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
329 fn compute_payinfo_1_hop() {
330 let recv_tlvs = ReceiveTlvs {
331 payment_secret: PaymentSecret([0; 32]),
332 payment_constraints: PaymentConstraints {
334 htlc_minimum_msat: 1,
337 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242).unwrap();
338 assert_eq!(blinded_payinfo.fee_base_msat, 0);
339 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
340 assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);
341 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
342 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
346 fn simple_aggregated_htlc_min() {
347 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
349 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
350 let intermediate_nodes = vec![ForwardNode {
354 payment_relay: PaymentRelay {
355 cltv_expiry_delta: 0,
356 fee_proportional_millionths: 0,
359 payment_constraints: PaymentConstraints {
361 htlc_minimum_msat: 1,
363 features: BlindedHopFeatures::empty(),
365 htlc_maximum_msat: u64::max_value()
370 payment_relay: PaymentRelay {
371 cltv_expiry_delta: 0,
372 fee_proportional_millionths: 0,
375 payment_constraints: PaymentConstraints {
377 htlc_minimum_msat: 2_000,
379 features: BlindedHopFeatures::empty(),
381 htlc_maximum_msat: u64::max_value()
383 let recv_tlvs = ReceiveTlvs {
384 payment_secret: PaymentSecret([0; 32]),
385 payment_constraints: PaymentConstraints {
387 htlc_minimum_msat: 3,
390 let htlc_maximum_msat = 100_000;
391 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
392 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
396 fn aggregated_htlc_min() {
397 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
398 // max (htlc_min - following_fees) along the path.
399 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
400 let intermediate_nodes = vec![ForwardNode {
404 payment_relay: PaymentRelay {
405 cltv_expiry_delta: 0,
406 fee_proportional_millionths: 500,
407 fee_base_msat: 1_000,
409 payment_constraints: PaymentConstraints {
411 htlc_minimum_msat: 5_000,
413 features: BlindedHopFeatures::empty(),
415 htlc_maximum_msat: u64::max_value()
420 payment_relay: PaymentRelay {
421 cltv_expiry_delta: 0,
422 fee_proportional_millionths: 500,
425 payment_constraints: PaymentConstraints {
427 htlc_minimum_msat: 2_000,
429 features: BlindedHopFeatures::empty(),
431 htlc_maximum_msat: u64::max_value()
433 let recv_tlvs = ReceiveTlvs {
434 payment_secret: PaymentSecret([0; 32]),
435 payment_constraints: PaymentConstraints {
437 htlc_minimum_msat: 1,
440 let htlc_minimum_msat = 3798;
441 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1).is_err());
443 let htlc_maximum_msat = htlc_minimum_msat + 1;
444 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
445 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
446 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
450 fn aggregated_htlc_max() {
451 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
452 // htlc ends up as the min (htlc_max - following_fees) along the path.
453 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
454 let intermediate_nodes = vec![ForwardNode {
458 payment_relay: PaymentRelay {
459 cltv_expiry_delta: 0,
460 fee_proportional_millionths: 500,
461 fee_base_msat: 1_000,
463 payment_constraints: PaymentConstraints {
465 htlc_minimum_msat: 1,
467 features: BlindedHopFeatures::empty(),
469 htlc_maximum_msat: 5_000,
474 payment_relay: PaymentRelay {
475 cltv_expiry_delta: 0,
476 fee_proportional_millionths: 500,
479 payment_constraints: PaymentConstraints {
481 htlc_minimum_msat: 1,
483 features: BlindedHopFeatures::empty(),
485 htlc_maximum_msat: 10_000
487 let recv_tlvs = ReceiveTlvs {
488 payment_secret: PaymentSecret([0; 32]),
489 payment_constraints: PaymentConstraints {
491 htlc_minimum_msat: 1,
495 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000).unwrap();
496 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);