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 /// Data to construct a [`BlindedHop`] for forwarding a payment.
20 pub struct ForwardTlvs {
21 /// The short channel id this payment should be forwarded out over.
22 short_channel_id: u64,
23 /// Payment parameters for relaying over [`Self::short_channel_id`].
24 payment_relay: PaymentRelay,
25 /// Payment constraints for relaying over [`Self::short_channel_id`].
26 payment_constraints: PaymentConstraints,
27 /// Supported and required features when relaying a payment onion containing this object's
28 /// corresponding [`BlindedHop::encrypted_payload`].
30 /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
31 features: BlindedHopFeatures,
34 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
35 /// may not be valid if received by another lightning implementation.
36 pub struct ReceiveTlvs {
37 /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
38 payment_secret: PaymentSecret,
39 /// Constraints for the receiver of this payment.
40 payment_constraints: PaymentConstraints,
43 /// Data to construct a [`BlindedHop`] for sending a payment over.
45 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
46 pub(crate) enum BlindedPaymentTlvs {
47 /// This blinded payment data is for a forwarding node.
49 /// This blinded payment data is for the receiving node.
53 // Used to include forward and receive TLVs in the same iterator for encoding.
54 enum BlindedPaymentTlvsRef<'a> {
55 Forward(&'a ForwardTlvs),
56 Receive(&'a ReceiveTlvs),
59 /// Parameters for relaying over a given [`BlindedHop`].
61 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
62 pub struct PaymentRelay {
63 /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
65 ///[`BlindedHop`]: crate::blinded_path::BlindedHop
66 pub cltv_expiry_delta: u16,
67 /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
68 /// this [`BlindedHop`], (i.e., 10,000 is 1%).
70 ///[`BlindedHop`]: crate::blinded_path::BlindedHop
71 pub fee_proportional_millionths: u32,
72 /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
74 ///[`BlindedHop`]: crate::blinded_path::BlindedHop
75 pub fee_base_msat: u32,
78 /// Constraints for relaying over a given [`BlindedHop`].
80 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
81 pub struct PaymentConstraints {
82 /// The maximum total CLTV delta that is acceptable when relaying a payment over this
85 ///[`BlindedHop`]: crate::blinded_path::BlindedHop
86 pub max_cltv_expiry: u32,
87 /// The minimum value, in msat, that may be accepted by the node corresponding to this
89 pub htlc_minimum_msat: u64,
92 impl_writeable_tlv_based!(ForwardTlvs, {
93 (2, short_channel_id, required),
94 (10, payment_relay, required),
95 (12, payment_constraints, required),
96 (14, features, required),
99 impl_writeable_tlv_based!(ReceiveTlvs, {
100 (12, payment_constraints, required),
101 (65536, payment_secret, required),
104 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
105 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
106 // TODO: write padding
108 Self::Forward(tlvs) => tlvs.write(w)?,
109 Self::Receive(tlvs) => tlvs.write(w)?,
115 impl Readable for BlindedPaymentTlvs {
116 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
117 _init_and_read_tlv_stream!(r, {
118 (1, _padding, option),
120 (10, payment_relay, option),
121 (12, payment_constraints, required),
122 (14, features, option),
123 (65536, payment_secret, option),
125 let _padding: Option<utils::Padding> = _padding;
127 if let Some(short_channel_id) = scid {
128 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
129 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
131 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
132 payment_constraints: payment_constraints.0.unwrap(),
133 features: features.ok_or(DecodeError::InvalidValue)?,
136 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
137 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
138 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
139 payment_constraints: payment_constraints.0.unwrap(),
145 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
146 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
147 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[(PublicKey, ForwardTlvs)],
148 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
149 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
150 let pks = intermediate_nodes.iter().map(|(pk, _)| pk)
151 .chain(core::iter::once(&payee_node_id));
152 let tlvs = intermediate_nodes.iter().map(|(_, tlvs)| BlindedPaymentTlvsRef::Forward(tlvs))
153 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
154 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
157 /// `None` if underflow occurs.
158 fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
159 let inbound_amt = inbound_amt_msat as u128;
160 let base = payment_relay.fee_base_msat as u128;
161 let prop = payment_relay.fee_proportional_millionths as u128;
163 let post_base_fee_inbound_amt =
164 if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
165 let mut amt_to_forward =
166 (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
168 let fee = ((amt_to_forward * prop) / 1_000_000) + base;
169 if inbound_amt - fee < amt_to_forward {
170 // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
171 // in fee to compensate.
174 debug_assert_eq!(amt_to_forward + fee, inbound_amt);
175 u64::try_from(amt_to_forward).ok()
178 pub(super) fn compute_payinfo(
179 intermediate_nodes: &[(PublicKey, ForwardTlvs)], payee_tlvs: &ReceiveTlvs
180 ) -> Result<BlindedPayInfo, ()> {
181 let mut curr_base_fee: u64 = 0;
182 let mut curr_prop_mil: u64 = 0;
183 let mut cltv_expiry_delta: u16 = 0;
184 for (_, tlvs) in intermediate_nodes.iter().rev() {
185 // In the future, we'll want to take the intersection of all supported features for the
186 // `BlindedPayInfo`, but there are no features in that context right now.
187 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
189 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
190 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
191 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
192 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
193 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
194 .and_then(|f| f.checked_add(1_000_000 - 1))
195 .map(|f| f / 1_000_000)
196 .and_then(|f| f.checked_add(next_base_fee))
198 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
199 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
200 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
201 .and_then(|f| f.checked_add(1_000_000 - 1))
202 .map(|f| f / 1_000_000)
203 .and_then(|f| f.checked_sub(1_000_000))
206 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
209 let mut htlc_minimum_msat: u64 = 1;
210 for (_, tlvs) in intermediate_nodes.iter() {
211 // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
212 // following hops for forwarding that min, since that fee amount will automatically be included
213 // in the amount that this node receives and contribute towards reaching its min.
214 htlc_minimum_msat = amt_to_forward_msat(
215 core::cmp::max(tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
217 ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
219 htlc_minimum_msat = core::cmp::max(
220 payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
224 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
225 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
228 htlc_maximum_msat: 21_000_000 * 100_000_000 * 1_000, // TODO
229 features: BlindedHopFeatures::empty(),
233 impl_writeable_msg!(PaymentRelay, {
235 fee_proportional_millionths,
239 impl_writeable_msg!(PaymentConstraints, {
246 use bitcoin::secp256k1::PublicKey;
247 use crate::blinded_path::payment::{ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
248 use crate::ln::PaymentSecret;
249 use crate::ln::features::BlindedHopFeatures;
252 fn compute_payinfo() {
253 // Taken from the spec example for aggregating blinded payment info. See
254 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
255 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
256 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
258 payment_relay: PaymentRelay {
259 cltv_expiry_delta: 144,
260 fee_proportional_millionths: 500,
263 payment_constraints: PaymentConstraints {
265 htlc_minimum_msat: 100,
267 features: BlindedHopFeatures::empty(),
268 }), (dummy_pk, ForwardTlvs {
270 payment_relay: PaymentRelay {
271 cltv_expiry_delta: 144,
272 fee_proportional_millionths: 500,
275 payment_constraints: PaymentConstraints {
277 htlc_minimum_msat: 1_000,
279 features: BlindedHopFeatures::empty(),
281 let recv_tlvs = ReceiveTlvs {
282 payment_secret: PaymentSecret([0; 32]),
283 payment_constraints: PaymentConstraints {
285 htlc_minimum_msat: 1,
288 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
289 assert_eq!(blinded_payinfo.fee_base_msat, 201);
290 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
291 assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
292 assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
296 fn compute_payinfo_1_hop() {
297 let recv_tlvs = ReceiveTlvs {
298 payment_secret: PaymentSecret([0; 32]),
299 payment_constraints: PaymentConstraints {
301 htlc_minimum_msat: 1,
304 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs).unwrap();
305 assert_eq!(blinded_payinfo.fee_base_msat, 0);
306 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
307 assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);
308 assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
312 fn simple_aggregated_htlc_min() {
313 // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
315 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
316 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
318 payment_relay: PaymentRelay {
319 cltv_expiry_delta: 0,
320 fee_proportional_millionths: 0,
323 payment_constraints: PaymentConstraints {
325 htlc_minimum_msat: 1,
327 features: BlindedHopFeatures::empty(),
328 }), (dummy_pk, ForwardTlvs {
330 payment_relay: PaymentRelay {
331 cltv_expiry_delta: 0,
332 fee_proportional_millionths: 0,
335 payment_constraints: PaymentConstraints {
337 htlc_minimum_msat: 2_000,
339 features: BlindedHopFeatures::empty(),
341 let recv_tlvs = ReceiveTlvs {
342 payment_secret: PaymentSecret([0; 32]),
343 payment_constraints: PaymentConstraints {
345 htlc_minimum_msat: 3,
348 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
349 assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
353 fn aggregated_htlc_min() {
354 // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
355 // max (htlc_min - following_fees) along the path.
356 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
357 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
359 payment_relay: PaymentRelay {
360 cltv_expiry_delta: 0,
361 fee_proportional_millionths: 500,
362 fee_base_msat: 1_000,
364 payment_constraints: PaymentConstraints {
366 htlc_minimum_msat: 5_000,
368 features: BlindedHopFeatures::empty(),
369 }), (dummy_pk, ForwardTlvs {
371 payment_relay: PaymentRelay {
372 cltv_expiry_delta: 0,
373 fee_proportional_millionths: 500,
376 payment_constraints: PaymentConstraints {
378 htlc_minimum_msat: 2_000,
380 features: BlindedHopFeatures::empty(),
382 let recv_tlvs = ReceiveTlvs {
383 payment_secret: PaymentSecret([0; 32]),
384 payment_constraints: PaymentConstraints {
386 htlc_minimum_msat: 1,
389 let htlc_minimum_msat = 3798;
390 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
391 assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);