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 use core::convert::TryFrom;
22 /// An intermediate node, its outbound channel, and relay parameters.
23 #[derive(Clone, Debug)]
24 pub struct ForwardNode {
25 /// The TLVs for this node's [`BlindedHop`], where the fee parameters contained within are also
26 /// used for [`BlindedPayInfo`] construction.
27 pub tlvs: ForwardTlvs,
28 /// This node's pubkey.
29 pub node_id: PublicKey,
30 /// The maximum value, in msat, that may be accepted by this node.
31 pub htlc_maximum_msat: u64,
34 /// Data to construct a [`BlindedHop`] for forwarding a payment.
35 #[derive(Clone, Debug)]
36 pub struct ForwardTlvs {
37 /// The short channel id this payment should be forwarded out over.
38 pub short_channel_id: u64,
39 /// Payment parameters for relaying over [`Self::short_channel_id`].
40 pub payment_relay: PaymentRelay,
41 /// Payment constraints for relaying over [`Self::short_channel_id`].
42 pub payment_constraints: PaymentConstraints,
43 /// Supported and required features when relaying a payment onion containing this object's
44 /// corresponding [`BlindedHop::encrypted_payload`].
46 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
47 pub features: BlindedHopFeatures,
50 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
51 /// may not be valid if received by another lightning implementation.
52 #[derive(Clone, Debug)]
53 pub struct ReceiveTlvs {
54 /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
55 pub payment_secret: PaymentSecret,
56 /// Constraints for the receiver of this payment.
57 pub payment_constraints: PaymentConstraints,
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 impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
105 fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
106 let CounterpartyForwardingInfo {
107 fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
110 // Avoid exposing esoteric CLTV expiry deltas
111 let cltv_expiry_delta = match cltv_expiry_delta {
119 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
123 impl Writeable for ForwardTlvs {
124 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
126 if self.features == BlindedHopFeatures::empty() { None }
127 else { Some(&self.features) };
128 encode_tlv_stream!(w, {
129 (2, self.short_channel_id, required),
130 (10, self.payment_relay, required),
131 (12, self.payment_constraints, required),
132 (14, features_opt, option)
138 impl Writeable for ReceiveTlvs {
139 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
140 encode_tlv_stream!(w, {
141 (12, self.payment_constraints, required),
142 (65536, self.payment_secret, required)
148 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
149 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
150 // TODO: write padding
152 Self::Forward(tlvs) => tlvs.write(w)?,
153 Self::Receive(tlvs) => tlvs.write(w)?,
159 impl Readable for BlindedPaymentTlvs {
160 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
161 _init_and_read_tlv_stream!(r, {
162 (1, _padding, option),
164 (10, payment_relay, option),
165 (12, payment_constraints, required),
166 (14, features, option),
167 (65536, payment_secret, option),
169 let _padding: Option<utils::Padding> = _padding;
171 if let Some(short_channel_id) = scid {
172 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
173 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
175 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
176 payment_constraints: payment_constraints.0.unwrap(),
177 features: features.unwrap_or_else(BlindedHopFeatures::empty),
180 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
181 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
182 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
183 payment_constraints: payment_constraints.0.unwrap(),
189 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
190 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
191 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
192 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
193 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
194 let pks = intermediate_nodes.iter().map(|node| &node.node_id)
195 .chain(core::iter::once(&payee_node_id));
196 let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
197 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
198 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
201 /// `None` if underflow occurs.
202 pub(crate) fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
203 let inbound_amt = inbound_amt_msat as u128;
204 let base = payment_relay.fee_base_msat as u128;
205 let prop = payment_relay.fee_proportional_millionths as u128;
207 let post_base_fee_inbound_amt =
208 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
209 let mut amt_to_forward =
210 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
212 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
213 if inbound_amt - fee < amt_to_forward {
214 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
215 // in fee to compensate.
218 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
219 u64::try_from(amt_to_forward).ok()
222 pub(super) fn compute_payinfo(
223 intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64,
224 min_final_cltv_expiry_delta: u16
225 ) -> Result<BlindedPayInfo, ()> {
226 let mut curr_base_fee: u64 = 0;
227 let mut curr_prop_mil: u64 = 0;
228 let mut cltv_expiry_delta: u16 = min_final_cltv_expiry_delta;
229 for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
230 // In the future, we'll want to take the intersection of all supported features for the
231 // `BlindedPayInfo`, but there are no features in that context right now.
232 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
234 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
235 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
236 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
237 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
238 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
239 .and_then(|f| f.checked_add(1_000_000 - 1))
240 .map(|f| f / 1_000_000)
241 .and_then(|f| f.checked_add(next_base_fee))
243 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
244 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
245 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
246 .and_then(|f| f.checked_add(1_000_000 - 1))
247 .map(|f| f / 1_000_000)
248 .and_then(|f| f.checked_sub(1_000_000))
251 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
254 let mut htlc_minimum_msat: u64 = 1;
255 let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
256 for node in intermediate_nodes.iter() {
257 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
258 // following hops for forwarding that min, since that fee amount will automatically be included
259 // in the amount that this node receives and contribute towards reaching its min.
260 htlc_minimum_msat = amt_to_forward_msat(
261 core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
262 &node.tlvs.payment_relay
263 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
264 htlc_maximum_msat = amt_to_forward_msat(
265 core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
266 ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
268 htlc_minimum_msat = core::cmp::max(
269 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
271 htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
273 if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
275 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
276 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
280 features: BlindedHopFeatures::empty(),
284 impl Writeable for PaymentRelay {
285 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
286 self.cltv_expiry_delta.write(w)?;
287 self.fee_proportional_millionths.write(w)?;
288 HighZeroBytesDroppedBigSize(self.fee_base_msat).write(w)
291 impl Readable for PaymentRelay {
292 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
293 let cltv_expiry_delta: u16 = Readable::read(r)?;
294 let fee_proportional_millionths: u32 = Readable::read(r)?;
295 let fee_base_msat: HighZeroBytesDroppedBigSize<u32> = Readable::read(r)?;
296 Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat: fee_base_msat.0 })
300 impl Writeable for PaymentConstraints {
301 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
302 self.max_cltv_expiry.write(w)?;
303 HighZeroBytesDroppedBigSize(self.htlc_minimum_msat).write(w)
306 impl Readable for PaymentConstraints {
307 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
308 let max_cltv_expiry: u32 = Readable::read(r)?;
309 let htlc_minimum_msat: HighZeroBytesDroppedBigSize<u64> = Readable::read(r)?;
310 Ok(Self { max_cltv_expiry, htlc_minimum_msat: htlc_minimum_msat.0 })
316 use bitcoin::secp256k1::PublicKey;
317 use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
318 use crate::ln::PaymentSecret;
319 use crate::ln::features::BlindedHopFeatures;
320 use crate::ln::functional_test_utils::TEST_FINAL_CLTV;
323 fn compute_payinfo() {
324 // Taken from the spec example for aggregating blinded payment info. See
325 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
326 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
327 let intermediate_nodes = vec![ForwardNode {
331 payment_relay: PaymentRelay {
332 cltv_expiry_delta: 144,
333 fee_proportional_millionths: 500,
336 payment_constraints: PaymentConstraints {
338 htlc_minimum_msat: 100,
340 features: BlindedHopFeatures::empty(),
342 htlc_maximum_msat: u64::max_value(),
347 payment_relay: PaymentRelay {
348 cltv_expiry_delta: 144,
349 fee_proportional_millionths: 500,
352 payment_constraints: PaymentConstraints {
354 htlc_minimum_msat: 1_000,
356 features: BlindedHopFeatures::empty(),
358 htlc_maximum_msat: u64::max_value(),
360 let recv_tlvs = ReceiveTlvs {
361 payment_secret: PaymentSecret([0; 32]),
362 payment_constraints: PaymentConstraints {
364 htlc_minimum_msat: 1,
367 let htlc_maximum_msat = 100_000;
368 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, 12).unwrap();
369 assert_eq!(blinded_payinfo.fee_base_msat, 201);
370 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
371 assert_eq!(blinded_payinfo.cltv_expiry_delta, 300);
372 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
373 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
377 fn compute_payinfo_1_hop() {
378 let recv_tlvs = ReceiveTlvs {
379 payment_secret: PaymentSecret([0; 32]),
380 payment_constraints: PaymentConstraints {
382 htlc_minimum_msat: 1,
385 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242, TEST_FINAL_CLTV as u16).unwrap();
386 assert_eq!(blinded_payinfo.fee_base_msat, 0);
387 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
388 assert_eq!(blinded_payinfo.cltv_expiry_delta, TEST_FINAL_CLTV as u16);
389 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
390 assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
394 fn simple_aggregated_htlc_min() {
395 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
397 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
398 let intermediate_nodes = vec![ForwardNode {
402 payment_relay: PaymentRelay {
403 cltv_expiry_delta: 0,
404 fee_proportional_millionths: 0,
407 payment_constraints: PaymentConstraints {
409 htlc_minimum_msat: 1,
411 features: BlindedHopFeatures::empty(),
413 htlc_maximum_msat: u64::max_value()
418 payment_relay: PaymentRelay {
419 cltv_expiry_delta: 0,
420 fee_proportional_millionths: 0,
423 payment_constraints: PaymentConstraints {
425 htlc_minimum_msat: 2_000,
427 features: BlindedHopFeatures::empty(),
429 htlc_maximum_msat: u64::max_value()
431 let recv_tlvs = ReceiveTlvs {
432 payment_secret: PaymentSecret([0; 32]),
433 payment_constraints: PaymentConstraints {
435 htlc_minimum_msat: 3,
438 let htlc_maximum_msat = 100_000;
439 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
440 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
444 fn aggregated_htlc_min() {
445 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
446 // max (htlc_min - following_fees) along the path.
447 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
448 let intermediate_nodes = vec![ForwardNode {
452 payment_relay: PaymentRelay {
453 cltv_expiry_delta: 0,
454 fee_proportional_millionths: 500,
455 fee_base_msat: 1_000,
457 payment_constraints: PaymentConstraints {
459 htlc_minimum_msat: 5_000,
461 features: BlindedHopFeatures::empty(),
463 htlc_maximum_msat: u64::max_value()
468 payment_relay: PaymentRelay {
469 cltv_expiry_delta: 0,
470 fee_proportional_millionths: 500,
473 payment_constraints: PaymentConstraints {
475 htlc_minimum_msat: 2_000,
477 features: BlindedHopFeatures::empty(),
479 htlc_maximum_msat: u64::max_value()
481 let recv_tlvs = ReceiveTlvs {
482 payment_secret: PaymentSecret([0; 32]),
483 payment_constraints: PaymentConstraints {
485 htlc_minimum_msat: 1,
488 let htlc_minimum_msat = 3798;
489 assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1, TEST_FINAL_CLTV as u16).is_err());
491 let htlc_maximum_msat = htlc_minimum_msat + 1;
492 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat, TEST_FINAL_CLTV as u16).unwrap();
493 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
494 assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
498 fn aggregated_htlc_max() {
499 // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
500 // htlc ends up as the min (htlc_max - following_fees) along the path.
501 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
502 let intermediate_nodes = vec![ForwardNode {
506 payment_relay: PaymentRelay {
507 cltv_expiry_delta: 0,
508 fee_proportional_millionths: 500,
509 fee_base_msat: 1_000,
511 payment_constraints: PaymentConstraints {
513 htlc_minimum_msat: 1,
515 features: BlindedHopFeatures::empty(),
517 htlc_maximum_msat: 5_000,
522 payment_relay: PaymentRelay {
523 cltv_expiry_delta: 0,
524 fee_proportional_millionths: 500,
527 payment_constraints: PaymentConstraints {
529 htlc_minimum_msat: 1,
531 features: BlindedHopFeatures::empty(),
533 htlc_maximum_msat: 10_000
535 let recv_tlvs = ReceiveTlvs {
536 payment_secret: PaymentSecret([0; 32]),
537 payment_constraints: PaymentConstraints {
539 htlc_minimum_msat: 1,
543 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000, TEST_FINAL_CLTV as u16).unwrap();
544 assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);