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 relayed over this [`BlindedHop`].
88 pub htlc_minimum_msat: u64,
91 impl_writeable_tlv_based!(ForwardTlvs, {
92 (2, short_channel_id, required),
93 (10, payment_relay, required),
94 (12, payment_constraints, required),
95 (14, features, required),
98 impl_writeable_tlv_based!(ReceiveTlvs, {
99 (12, payment_constraints, required),
100 (65536, payment_secret, required),
103 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
104 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
105 // TODO: write padding
107 Self::Forward(tlvs) => tlvs.write(w)?,
108 Self::Receive(tlvs) => tlvs.write(w)?,
114 impl Readable for BlindedPaymentTlvs {
115 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
116 _init_and_read_tlv_stream!(r, {
117 (1, _padding, option),
119 (10, payment_relay, option),
120 (12, payment_constraints, required),
121 (14, features, option),
122 (65536, payment_secret, option),
124 let _padding: Option<utils::Padding> = _padding;
126 if let Some(short_channel_id) = scid {
127 if payment_secret.is_some() { return Err(DecodeError::InvalidValue) }
128 Ok(BlindedPaymentTlvs::Forward(ForwardTlvs {
130 payment_relay: payment_relay.ok_or(DecodeError::InvalidValue)?,
131 payment_constraints: payment_constraints.0.unwrap(),
132 features: features.ok_or(DecodeError::InvalidValue)?,
135 if payment_relay.is_some() || features.is_some() { return Err(DecodeError::InvalidValue) }
136 Ok(BlindedPaymentTlvs::Receive(ReceiveTlvs {
137 payment_secret: payment_secret.ok_or(DecodeError::InvalidValue)?,
138 payment_constraints: payment_constraints.0.unwrap(),
144 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
145 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
146 secp_ctx: &Secp256k1<T>, intermediate_nodes: &[(PublicKey, ForwardTlvs)],
147 payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
148 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
149 let pks = intermediate_nodes.iter().map(|(pk, _)| pk)
150 .chain(core::iter::once(&payee_node_id));
151 let tlvs = intermediate_nodes.iter().map(|(_, tlvs)| BlindedPaymentTlvsRef::Forward(tlvs))
152 .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
153 utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
156 pub(super) fn compute_payinfo(
157 intermediate_nodes: &[(PublicKey, ForwardTlvs)], payee_tlvs: &ReceiveTlvs
158 ) -> Result<BlindedPayInfo, ()> {
159 let mut curr_base_fee: u64 = 0;
160 let mut curr_prop_mil: u64 = 0;
161 let mut cltv_expiry_delta: u16 = 0;
162 for (_, tlvs) in intermediate_nodes.iter().rev() {
163 // In the future, we'll want to take the intersection of all supported features for the
164 // `BlindedPayInfo`, but there are no features in that context right now.
165 if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
167 let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
168 let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
169 // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
170 // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
171 curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
172 .and_then(|f| f.checked_add(1_000_000 - 1))
173 .map(|f| f / 1_000_000)
174 .and_then(|f| f.checked_add(next_base_fee))
176 // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
177 curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
178 .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
179 .and_then(|f| f.checked_add(1_000_000 - 1))
180 .map(|f| f / 1_000_000)
181 .and_then(|f| f.checked_sub(1_000_000))
184 cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
187 fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
188 fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
190 htlc_minimum_msat: 1, // TODO
191 htlc_maximum_msat: 21_000_000 * 100_000_000 * 1_000, // TODO
192 features: BlindedHopFeatures::empty(),
196 impl_writeable_msg!(PaymentRelay, {
198 fee_proportional_millionths,
202 impl_writeable_msg!(PaymentConstraints, {
209 use bitcoin::secp256k1::PublicKey;
210 use crate::blinded_path::payment::{ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
211 use crate::ln::PaymentSecret;
212 use crate::ln::features::BlindedHopFeatures;
215 fn compute_payinfo() {
216 // Taken from the spec example for aggregating blinded payment info. See
217 // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
218 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
219 let intermediate_nodes = vec![(dummy_pk, ForwardTlvs {
221 payment_relay: PaymentRelay {
222 cltv_expiry_delta: 144,
223 fee_proportional_millionths: 500,
226 payment_constraints: PaymentConstraints {
228 htlc_minimum_msat: 100,
230 features: BlindedHopFeatures::empty(),
231 }), (dummy_pk, ForwardTlvs {
233 payment_relay: PaymentRelay {
234 cltv_expiry_delta: 144,
235 fee_proportional_millionths: 500,
238 payment_constraints: PaymentConstraints {
240 htlc_minimum_msat: 1_000,
242 features: BlindedHopFeatures::empty(),
244 let recv_tlvs = ReceiveTlvs {
245 payment_secret: PaymentSecret([0; 32]),
246 payment_constraints: PaymentConstraints {
248 htlc_minimum_msat: 1,
251 let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs).unwrap();
252 assert_eq!(blinded_payinfo.fee_base_msat, 201);
253 assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
254 assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
258 fn compute_payinfo_1_hop() {
259 let recv_tlvs = ReceiveTlvs {
260 payment_secret: PaymentSecret([0; 32]),
261 payment_constraints: PaymentConstraints {
263 htlc_minimum_msat: 1,
266 let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs).unwrap();
267 assert_eq!(blinded_payinfo.fee_base_msat, 0);
268 assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
269 assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);