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 delta that is acceptable when relaying a payment over this
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 Writeable for ForwardTlvs {
101 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
102 encode_tlv_stream!(w, {
103 (2, self.short_channel_id, required),
104 (10, self.payment_relay, required),
105 (12, self.payment_constraints, required),
106 (14, self.features, required)
112 impl Writeable for ReceiveTlvs {
113 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
114 encode_tlv_stream!(w, {
115 (12, self.payment_constraints, required),
116 (65536, self.payment_secret, required)
122 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
123 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
124 // TODO: write padding
126 Self::Forward(tlvs) => tlvs.write(w)?,
127 Self::Receive(tlvs) => tlvs.write(w)?,
133 impl Readable for BlindedPaymentTlvs {
134 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
135 _init_and_read_tlv_stream!(r, {
136 (1, _padding, option),
138 (10, payment_relay, option),
139 (12, payment_constraints, required),
140 (14, features, option),
141 (65536, payment_secret, option),
143 let _padding: Option<utils::Padding> = _padding;
145 if let Some(short_channel_id) = scid {
146 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
147 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
149 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
150 payment_constraints: payment_constraints.0.unwrap(),
151 features: features.ok_or(DecodeError::InvalidValue)?,
154 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
155 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
156 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
157 payment_constraints: payment_constraints.0.unwrap(),
163 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
164 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
165 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
166 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
167 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
168 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
169 .chain(core::iter::once(&payee_node_id));
170 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
171 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
172 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
175 /// `None` if underflow occurs.
176 fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
177 let inbound_amt = inbound_amt_msat as u128;
178 let base = payment_relay.fee_base_msat as u128;
179 let prop = payment_relay.fee_proportional_millionths as u128;
181 let post_base_fee_inbound_amt =
182 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
183 let mut amt_to_forward =
184 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
186 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
187 if inbound_amt - fee < amt_to_forward {
188 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
189 // in fee to compensate.
192 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
193 u64::try_from(amt_to_forward).ok()
196 pub(super) fn compute_payinfo(
197 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64
198 ) -> Result<BlindedPayInfo, ()> {
199 let mut curr_base_fee: u64 = 0;
200 let mut curr_prop_mil: u64 = 0;
201 let mut cltv_expiry_delta: u16 = 0;
202 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
203 // In the future, we'll want to take the intersection of all supported features for the
204 // `BlindedPayInfo`, but there are no features in that context right now.
205 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
207 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
208 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
209 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
210 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
211 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
212 .and_then(|f| f.checked_add(1_000_000 - 1))
213 .map(|f| f / 1_000_000)
214 .and_then(|f| f.checked_add(next_base_fee))
216 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
217 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
218 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
219 .and_then(|f| f.checked_add(1_000_000 - 1))
220 .map(|f| f / 1_000_000)
221 .and_then(|f| f.checked_sub(1_000_000))
224 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
227 let mut htlc_minimum_msat: u64 = 1;
228 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
229 for node in intermediate_nodes.iter() {
230 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
231 // following hops for forwarding that min, since that fee amount will automatically be included
232 // in the amount that this node receives and contribute towards reaching its min.
233 htlc_minimum_msat = amt_to_forward_msat(
234 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
235 &node.tlvs.payment_relay
236 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
237 htlc_maximum_msat = amt_to_forward_msat(
238 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
239 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
241 htlc_minimum_msat = core::cmp::max(
242 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
244 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
246 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
248 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
249 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
253 features: BlindedHopFeatures::empty(),
257 impl_writeable_msg!(PaymentRelay, {
259 fee_proportional_millionths,
263 impl_writeable_msg!(PaymentConstraints, {
270 use bitcoin::secp256k1::PublicKey;
271 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
272 use crate::ln::PaymentSecret;
273 use crate::ln::features::BlindedHopFeatures;
276 fn compute_payinfo() {
277 // Taken from the spec example for aggregating blinded payment info. See
278 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
279 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
280 let intermediate_nodes = vec![ForwardNode {
284 payment_relay: PaymentRelay {
285 cltv_expiry_delta: 144,
286 fee_proportional_millionths: 500,
289 payment_constraints: PaymentConstraints {
291 htlc_minimum_msat: 100,
293 features: BlindedHopFeatures::empty(),
295 htlc_maximum_msat: u64::max_value(),
300 payment_relay: PaymentRelay {
301 cltv_expiry_delta: 144,
302 fee_proportional_millionths: 500,
305 payment_constraints: PaymentConstraints {
307 htlc_minimum_msat: 1_000,
309 features: BlindedHopFeatures::empty(),
311 htlc_maximum_msat: u64::max_value(),
313 let recv_tlvs = ReceiveTlvs {
314 payment_secret: PaymentSecret([0; 32]),
315 payment_constraints: PaymentConstraints {
317 htlc_minimum_msat: 1,
320 let htlc_maximum_msat = 100_000;
321 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
322 assert_eq!(blinded_payinfo.fee_base_msat, 201);
323 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
324 assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
325 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
326 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
330 fn compute_payinfo_1_hop() {
331 let recv_tlvs = ReceiveTlvs {
332 payment_secret: PaymentSecret([0; 32]),
333 payment_constraints: PaymentConstraints {
335 htlc_minimum_msat: 1,
338 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242).unwrap();
339 assert_eq!(blinded_payinfo.fee_base_msat, 0);
340 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
341 assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);
342 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
343 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
347 fn simple_aggregated_htlc_min() {
348 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
350 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
351 let intermediate_nodes = vec![ForwardNode {
355 payment_relay: PaymentRelay {
356 cltv_expiry_delta: 0,
357 fee_proportional_millionths: 0,
360 payment_constraints: PaymentConstraints {
362 htlc_minimum_msat: 1,
364 features: BlindedHopFeatures::empty(),
366 htlc_maximum_msat: u64::max_value()
371 payment_relay: PaymentRelay {
372 cltv_expiry_delta: 0,
373 fee_proportional_millionths: 0,
376 payment_constraints: PaymentConstraints {
378 htlc_minimum_msat: 2_000,
380 features: BlindedHopFeatures::empty(),
382 htlc_maximum_msat: u64::max_value()
384 let recv_tlvs = ReceiveTlvs {
385 payment_secret: PaymentSecret([0; 32]),
386 payment_constraints: PaymentConstraints {
388 htlc_minimum_msat: 3,
391 let htlc_maximum_msat = 100_000;
392 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
393 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
397 fn aggregated_htlc_min() {
398 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
399 // max (htlc_min - following_fees) along the path.
400 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
401 let intermediate_nodes = vec![ForwardNode {
405 payment_relay: PaymentRelay {
406 cltv_expiry_delta: 0,
407 fee_proportional_millionths: 500,
408 fee_base_msat: 1_000,
410 payment_constraints: PaymentConstraints {
412 htlc_minimum_msat: 5_000,
414 features: BlindedHopFeatures::empty(),
416 htlc_maximum_msat: u64::max_value()
421 payment_relay: PaymentRelay {
422 cltv_expiry_delta: 0,
423 fee_proportional_millionths: 500,
426 payment_constraints: PaymentConstraints {
428 htlc_minimum_msat: 2_000,
430 features: BlindedHopFeatures::empty(),
432 htlc_maximum_msat: u64::max_value()
434 let recv_tlvs = ReceiveTlvs {
435 payment_secret: PaymentSecret([0; 32]),
436 payment_constraints: PaymentConstraints {
438 htlc_minimum_msat: 1,
441 let htlc_minimum_msat = 3798;
442 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1).is_err());
444 let htlc_maximum_msat = htlc_minimum_msat + 1;
445 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
446 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
447 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
451 fn aggregated_htlc_max() {
452 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
453 // htlc ends up as the min (htlc_max - following_fees) along the path.
454 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
455 let intermediate_nodes = vec![ForwardNode {
459 payment_relay: PaymentRelay {
460 cltv_expiry_delta: 0,
461 fee_proportional_millionths: 500,
462 fee_base_msat: 1_000,
464 payment_constraints: PaymentConstraints {
466 htlc_minimum_msat: 1,
468 features: BlindedHopFeatures::empty(),
470 htlc_maximum_msat: 5_000,
475 payment_relay: PaymentRelay {
476 cltv_expiry_delta: 0,
477 fee_proportional_millionths: 500,
480 payment_constraints: PaymentConstraints {
482 htlc_minimum_msat: 1,
484 features: BlindedHopFeatures::empty(),
486 htlc_maximum_msat: 10_000
488 let recv_tlvs = ReceiveTlvs {
489 payment_secret: PaymentSecret([0; 32]),
490 payment_constraints: PaymentConstraints {
492 htlc_minimum_msat: 1,
496 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000).unwrap();
497 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);