Merge pull request #2567 from G8XSU/payment-id
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Mon, 11 Sep 2023 23:15:49 +0000 (23:15 +0000)
committerGitHub <noreply@github.com>
Mon, 11 Sep 2023 23:15:49 +0000 (23:15 +0000)
Add PaymentId in ChannelManager.list_recent_payments()

lightning-persister/src/fs_store.rs
lightning/src/blinded_path/mod.rs
lightning/src/blinded_path/payment.rs
lightning/src/ln/functional_tests.rs
lightning/src/util/persist.rs

index 56d071da9f0b86ad4cf3571b9e64e8dc3c950e0e..81f9709c45467d4e6725ef83f11ba10a33734b68 100644 (file)
@@ -26,7 +26,7 @@ macro_rules! call {
 }
 
 #[cfg(target_os = "windows")]
-fn path_to_windows_str<T: AsRef<OsStr>>(path: T) -> Vec<u16> {
+fn path_to_windows_str<T: AsRef<OsStr>>(path: &T) -> Vec<u16> {
        path.as_ref().encode_wide().chain(Some(0)).collect()
 }
 
@@ -164,8 +164,8 @@ impl KVStore for FilesystemStore {
                                let res = if dest_file_path.exists() {
                                        call!(unsafe {
                                                windows_sys::Win32::Storage::FileSystem::ReplaceFileW(
-                                                       path_to_windows_str(dest_file_path.clone()).as_ptr(),
-                                                       path_to_windows_str(tmp_file_path).as_ptr(),
+                                                       path_to_windows_str(&dest_file_path).as_ptr(),
+                                                       path_to_windows_str(&tmp_file_path).as_ptr(),
                                                        std::ptr::null(),
                                                        windows_sys::Win32::Storage::FileSystem::REPLACEFILE_IGNORE_MERGE_ERRORS,
                                                        std::ptr::null_mut() as *const core::ffi::c_void,
@@ -175,8 +175,8 @@ impl KVStore for FilesystemStore {
                                } else {
                                        call!(unsafe {
                                                windows_sys::Win32::Storage::FileSystem::MoveFileExW(
-                                                       path_to_windows_str(tmp_file_path).as_ptr(),
-                                                       path_to_windows_str(dest_file_path.clone()).as_ptr(),
+                                                       path_to_windows_str(&tmp_file_path).as_ptr(),
+                                                       path_to_windows_str(&dest_file_path).as_ptr(),
                                                        windows_sys::Win32::Storage::FileSystem::MOVEFILE_WRITE_THROUGH
                                                        | windows_sys::Win32::Storage::FileSystem::MOVEFILE_REPLACE_EXISTING,
                                                        )
@@ -263,8 +263,8 @@ impl KVStore for FilesystemStore {
 
                                        call!(unsafe {
                                                windows_sys::Win32::Storage::FileSystem::MoveFileExW(
-                                                       path_to_windows_str(dest_file_path).as_ptr(),
-                                                       path_to_windows_str(trash_file_path.clone()).as_ptr(),
+                                                       path_to_windows_str(&dest_file_path).as_ptr(),
+                                                       path_to_windows_str(&trash_file_path).as_ptr(),
                                                        windows_sys::Win32::Storage::FileSystem::MOVEFILE_WRITE_THROUGH
                                                        | windows_sys::Win32::Storage::FileSystem::MOVEFILE_REPLACE_EXISTING,
                                                        )
index 89087a10cd414ac9fdeae4331490ef97e73666ea..927bbea9f6e99ab6e15db2cbb619af0e187060ec 100644 (file)
@@ -15,8 +15,9 @@ pub(crate) mod utils;
 
 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
 
-use crate::sign::EntropySource;
 use crate::ln::msgs::DecodeError;
+use crate::offers::invoice::BlindedPayInfo;
+use crate::sign::EntropySource;
 use crate::util::ser::{Readable, Writeable, Writer};
 
 use crate::io;
@@ -75,25 +76,31 @@ impl BlindedPath {
                })
        }
 
-       /// Create a blinded path for a payment, to be forwarded along `path`. The last node
-       /// in `path` will be the destination node.
+       /// Create a blinded path for a payment, to be forwarded along `intermediate_nodes`.
+       ///
+       /// Errors if:
+       /// * a provided node id is invalid
+       /// * [`BlindedPayInfo`] calculation results in an integer overflow
+       /// * any unknown features are required in the provided [`ForwardTlvs`]
        ///
-       /// Errors if `path` is empty or a node id in `path` is invalid.
+       /// [`ForwardTlvs`]: crate::blinded_path::payment::ForwardTlvs
        //  TODO: make all payloads the same size with padding + add dummy hops
        pub fn new_for_payment<ES: EntropySource, T: secp256k1::Signing + secp256k1::Verification>(
-               intermediate_nodes: &[(PublicKey, payment::ForwardTlvs)], payee_node_id: PublicKey,
-               payee_tlvs: payment::ReceiveTlvs, entropy_source: &ES, secp_ctx: &Secp256k1<T>
-       ) -> Result<Self, ()> {
+               intermediate_nodes: &[payment::ForwardNode], payee_node_id: PublicKey,
+               payee_tlvs: payment::ReceiveTlvs, htlc_maximum_msat: u64, entropy_source: &ES,
+               secp_ctx: &Secp256k1<T>
+       ) -> Result<(BlindedPayInfo, Self), ()> {
                let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
                let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
 
-               Ok(BlindedPath {
-                       introduction_node_id: intermediate_nodes.first().map_or(payee_node_id, |n| n.0),
+               let blinded_payinfo = payment::compute_payinfo(intermediate_nodes, &payee_tlvs, htlc_maximum_msat)?;
+               Ok((blinded_payinfo, BlindedPath {
+                       introduction_node_id: intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id),
                        blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
                        blinded_hops: payment::blinded_hops(
                                secp_ctx, intermediate_nodes, payee_node_id, payee_tlvs, &blinding_secret
                        ).map_err(|_| ())?,
-               })
+               }))
        }
 }
 
index 0f6cf01858dc5666411ca6f1d6fe10cfc3f9a323..32181f7889c350fa3f23f2bdfe37a437d99808d4 100644 (file)
@@ -10,31 +10,48 @@ use crate::io;
 use crate::ln::PaymentSecret;
 use crate::ln::features::BlindedHopFeatures;
 use crate::ln::msgs::DecodeError;
+use crate::offers::invoice::BlindedPayInfo;
 use crate::prelude::*;
 use crate::util::ser::{Readable, Writeable, Writer};
 
+use core::convert::TryFrom;
+
+/// An intermediate node, its outbound channel, and relay parameters.
+#[derive(Clone, Debug)]
+pub struct ForwardNode {
+       /// The TLVs for this node's [`BlindedHop`], where the fee parameters contained within are also
+       /// used for [`BlindedPayInfo`] construction.
+       pub tlvs: ForwardTlvs,
+       /// This node's pubkey.
+       pub node_id: PublicKey,
+       /// The maximum value, in msat, that may be accepted by this node.
+       pub htlc_maximum_msat: u64,
+}
+
 /// Data to construct a [`BlindedHop`] for forwarding a payment.
+#[derive(Clone, Debug)]
 pub struct ForwardTlvs {
        /// The short channel id this payment should be forwarded out over.
-       short_channel_id: u64,
+       pub short_channel_id: u64,
        /// Payment parameters for relaying over [`Self::short_channel_id`].
-       payment_relay: PaymentRelay,
+       pub payment_relay: PaymentRelay,
        /// Payment constraints for relaying over [`Self::short_channel_id`].
-       payment_constraints: PaymentConstraints,
+       pub payment_constraints: PaymentConstraints,
        /// Supported and required features when relaying a payment onion containing this object's
        /// corresponding [`BlindedHop::encrypted_payload`].
        ///
        /// [`BlindedHop::encrypted_payload`]: crate::blinded_path::BlindedHop::encrypted_payload
-       features: BlindedHopFeatures,
+       pub features: BlindedHopFeatures,
 }
 
 /// Data to construct a [`BlindedHop`] for receiving a payment. This payload is custom to LDK and
 /// may not be valid if received by another lightning implementation.
+#[derive(Clone, Debug)]
 pub struct ReceiveTlvs {
        /// Used to authenticate the sender of a payment to the receiver and tie MPP HTLCs together.
-       payment_secret: PaymentSecret,
+       pub payment_secret: PaymentSecret,
        /// Constraints for the receiver of this payment.
-       payment_constraints: PaymentConstraints,
+       pub payment_constraints: PaymentConstraints,
 }
 
 /// Data to construct a [`BlindedHop`] for sending a payment over.
@@ -56,46 +73,51 @@ enum BlindedPaymentTlvsRef<'a> {
 /// Parameters for relaying over a given [`BlindedHop`].
 ///
 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
+#[derive(Clone, Debug)]
 pub struct PaymentRelay {
        /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
-       ///
-       ///[`BlindedHop`]: crate::blinded_path::BlindedHop
        pub cltv_expiry_delta: u16,
        /// Liquidity fee charged (in millionths of the amount transferred) for relaying a payment over
        /// this [`BlindedHop`], (i.e., 10,000 is 1%).
-       ///
-       ///[`BlindedHop`]: crate::blinded_path::BlindedHop
        pub fee_proportional_millionths: u32,
        /// Base fee charged (in millisatoshi) for relaying a payment over this [`BlindedHop`].
-       ///
-       ///[`BlindedHop`]: crate::blinded_path::BlindedHop
        pub fee_base_msat: u32,
 }
 
 /// Constraints for relaying over a given [`BlindedHop`].
 ///
 /// [`BlindedHop`]: crate::blinded_path::BlindedHop
+#[derive(Clone, Debug)]
 pub struct PaymentConstraints {
        /// The maximum total CLTV delta that is acceptable when relaying a payment over this
        /// [`BlindedHop`].
-       ///
-       ///[`BlindedHop`]: crate::blinded_path::BlindedHop
        pub max_cltv_expiry: u32,
-       /// The minimum value, in msat, that may be relayed over this [`BlindedHop`].
+       /// The minimum value, in msat, that may be accepted by the node corresponding to this
+       /// [`BlindedHop`].
        pub htlc_minimum_msat: u64,
 }
 
-impl_writeable_tlv_based!(ForwardTlvs, {
-       (2, short_channel_id, required),
-       (10, payment_relay, required),
-       (12, payment_constraints, required),
-       (14, features, required),
-});
+impl Writeable for ForwardTlvs {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+               encode_tlv_stream!(w, {
+                       (2, self.short_channel_id, required),
+                       (10, self.payment_relay, required),
+                       (12, self.payment_constraints, required),
+                       (14, self.features, required)
+               });
+               Ok(())
+       }
+}
 
-impl_writeable_tlv_based!(ReceiveTlvs, {
-       (12, payment_constraints, required),
-       (65536, payment_secret, required),
-});
+impl Writeable for ReceiveTlvs {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+               encode_tlv_stream!(w, {
+                       (12, self.payment_constraints, required),
+                       (65536, self.payment_secret, required)
+               });
+               Ok(())
+       }
+}
 
 impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
@@ -140,16 +162,98 @@ impl Readable for BlindedPaymentTlvs {
 
 /// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
-       secp_ctx: &Secp256k1<T>, intermediate_nodes: &[(PublicKey, ForwardTlvs)],
+       secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode],
        payee_node_id: PublicKey, payee_tlvs: ReceiveTlvs, session_priv: &SecretKey
 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
-       let pks = intermediate_nodes.iter().map(|(pk, _)| pk)
+       let pks = intermediate_nodes.iter().map(|node| &node.node_id)
                .chain(core::iter::once(&payee_node_id));
-       let tlvs = intermediate_nodes.iter().map(|(_, tlvs)| BlindedPaymentTlvsRef::Forward(tlvs))
+       let tlvs = intermediate_nodes.iter().map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
                .chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
        utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
 }
 
+/// `None` if underflow occurs.
+fn amt_to_forward_msat(inbound_amt_msat: u64, payment_relay: &PaymentRelay) -> Option<u64> {
+       let inbound_amt = inbound_amt_msat as u128;
+       let base = payment_relay.fee_base_msat as u128;
+       let prop = payment_relay.fee_proportional_millionths as u128;
+
+       let post_base_fee_inbound_amt =
+               if let Some(amt) = inbound_amt.checked_sub(base) { amt } else { return None };
+       let mut amt_to_forward =
+               (post_base_fee_inbound_amt * 1_000_000 + 1_000_000 + prop - 1) / (prop + 1_000_000);
+
+       let fee = ((amt_to_forward * prop) / 1_000_000) + base;
+       if inbound_amt - fee < amt_to_forward {
+               // Rounding up the forwarded amount resulted in underpaying this node, so take an extra 1 msat
+               // in fee to compensate.
+               amt_to_forward -= 1;
+       }
+       debug_assert_eq!(amt_to_forward + fee, inbound_amt);
+       u64::try_from(amt_to_forward).ok()
+}
+
+pub(super) fn compute_payinfo(
+       intermediate_nodes: &[ForwardNode], payee_tlvs: &ReceiveTlvs, payee_htlc_maximum_msat: u64
+) -> Result<BlindedPayInfo, ()> {
+       let mut curr_base_fee: u64 = 0;
+       let mut curr_prop_mil: u64 = 0;
+       let mut cltv_expiry_delta: u16 = 0;
+       for tlvs in intermediate_nodes.iter().rev().map(|n| &n.tlvs) {
+               // In the future, we'll want to take the intersection of all supported features for the
+               // `BlindedPayInfo`, but there are no features in that context right now.
+               if tlvs.features.requires_unknown_bits_from(&BlindedHopFeatures::empty()) { return Err(()) }
+
+               let next_base_fee = tlvs.payment_relay.fee_base_msat as u64;
+               let next_prop_mil = tlvs.payment_relay.fee_proportional_millionths as u64;
+               // Use integer arithmetic to compute `ceil(a/b)` as `(a+b-1)/b`
+               // ((curr_base_fee * (1_000_000 + next_prop_mil)) / 1_000_000) + next_base_fee
+               curr_base_fee = curr_base_fee.checked_mul(1_000_000 + next_prop_mil)
+                       .and_then(|f| f.checked_add(1_000_000 - 1))
+                       .map(|f| f / 1_000_000)
+                       .and_then(|f| f.checked_add(next_base_fee))
+                       .ok_or(())?;
+               // ceil(((curr_prop_mil + 1_000_000) * (next_prop_mil + 1_000_000)) / 1_000_000) - 1_000_000
+               curr_prop_mil = curr_prop_mil.checked_add(1_000_000)
+                       .and_then(|f1| next_prop_mil.checked_add(1_000_000).and_then(|f2| f2.checked_mul(f1)))
+                       .and_then(|f| f.checked_add(1_000_000 - 1))
+                       .map(|f| f / 1_000_000)
+                       .and_then(|f| f.checked_sub(1_000_000))
+                       .ok_or(())?;
+
+               cltv_expiry_delta = cltv_expiry_delta.checked_add(tlvs.payment_relay.cltv_expiry_delta).ok_or(())?;
+       }
+
+       let mut htlc_minimum_msat: u64 = 1;
+       let mut htlc_maximum_msat: u64 = 21_000_000 * 100_000_000 * 1_000; // Total bitcoin supply
+       for node in intermediate_nodes.iter() {
+               // The min htlc for an intermediate node is that node's min minus the fees charged by all of the
+               // following hops for forwarding that min, since that fee amount will automatically be included
+               // in the amount that this node receives and contribute towards reaching its min.
+               htlc_minimum_msat = amt_to_forward_msat(
+                       core::cmp::max(node.tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat),
+                       &node.tlvs.payment_relay
+               ).unwrap_or(1); // If underflow occurs, we definitely reached this node's min
+               htlc_maximum_msat = amt_to_forward_msat(
+                       core::cmp::min(node.htlc_maximum_msat, htlc_maximum_msat), &node.tlvs.payment_relay
+               ).ok_or(())?; // If underflow occurs, we cannot send to this hop without exceeding their max
+       }
+       htlc_minimum_msat = core::cmp::max(
+               payee_tlvs.payment_constraints.htlc_minimum_msat, htlc_minimum_msat
+       );
+       htlc_maximum_msat = core::cmp::min(payee_htlc_maximum_msat, htlc_maximum_msat);
+
+       if htlc_maximum_msat < htlc_minimum_msat { return Err(()) }
+       Ok(BlindedPayInfo {
+               fee_base_msat: u32::try_from(curr_base_fee).map_err(|_| ())?,
+               fee_proportional_millionths: u32::try_from(curr_prop_mil).map_err(|_| ())?,
+               cltv_expiry_delta,
+               htlc_minimum_msat,
+               htlc_maximum_msat,
+               features: BlindedHopFeatures::empty(),
+       })
+}
+
 impl_writeable_msg!(PaymentRelay, {
        cltv_expiry_delta,
        fee_proportional_millionths,
@@ -160,3 +264,236 @@ impl_writeable_msg!(PaymentConstraints, {
        max_cltv_expiry,
        htlc_minimum_msat
 }, {});
+
+#[cfg(test)]
+mod tests {
+       use bitcoin::secp256k1::PublicKey;
+       use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, ReceiveTlvs, PaymentConstraints, PaymentRelay};
+       use crate::ln::PaymentSecret;
+       use crate::ln::features::BlindedHopFeatures;
+
+       #[test]
+       fn compute_payinfo() {
+               // Taken from the spec example for aggregating blinded payment info. See
+               // https://github.com/lightning/bolts/blob/master/proposals/route-blinding.md#blinded-payments
+               let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
+               let intermediate_nodes = vec![ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 144,
+                                       fee_proportional_millionths: 500,
+                                       fee_base_msat: 100,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 100,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: u64::max_value(),
+               }, ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 144,
+                                       fee_proportional_millionths: 500,
+                                       fee_base_msat: 100,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 1_000,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: u64::max_value(),
+               }];
+               let recv_tlvs = ReceiveTlvs {
+                       payment_secret: PaymentSecret([0; 32]),
+                       payment_constraints: PaymentConstraints {
+                               max_cltv_expiry: 0,
+                               htlc_minimum_msat: 1,
+                       },
+               };
+               let htlc_maximum_msat = 100_000;
+               let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
+               assert_eq!(blinded_payinfo.fee_base_msat, 201);
+               assert_eq!(blinded_payinfo.fee_proportional_millionths, 1001);
+               assert_eq!(blinded_payinfo.cltv_expiry_delta, 288);
+               assert_eq!(blinded_payinfo.htlc_minimum_msat, 900);
+               assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
+       }
+
+       #[test]
+       fn compute_payinfo_1_hop() {
+               let recv_tlvs = ReceiveTlvs {
+                       payment_secret: PaymentSecret([0; 32]),
+                       payment_constraints: PaymentConstraints {
+                               max_cltv_expiry: 0,
+                               htlc_minimum_msat: 1,
+                       },
+               };
+               let blinded_payinfo = super::compute_payinfo(&[], &recv_tlvs, 4242).unwrap();
+               assert_eq!(blinded_payinfo.fee_base_msat, 0);
+               assert_eq!(blinded_payinfo.fee_proportional_millionths, 0);
+               assert_eq!(blinded_payinfo.cltv_expiry_delta, 0);
+               assert_eq!(blinded_payinfo.htlc_minimum_msat, 1);
+               assert_eq!(blinded_payinfo.htlc_maximum_msat, 4242);
+       }
+
+       #[test]
+       fn simple_aggregated_htlc_min() {
+               // If no hops charge fees, the htlc_minimum_msat should just be the maximum htlc_minimum_msat
+               // along the path.
+               let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
+               let intermediate_nodes = vec![ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 0,
+                                       fee_proportional_millionths: 0,
+                                       fee_base_msat: 0,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 1,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: u64::max_value()
+               }, ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 0,
+                                       fee_proportional_millionths: 0,
+                                       fee_base_msat: 0,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 2_000,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: u64::max_value()
+               }];
+               let recv_tlvs = ReceiveTlvs {
+                       payment_secret: PaymentSecret([0; 32]),
+                       payment_constraints: PaymentConstraints {
+                               max_cltv_expiry: 0,
+                               htlc_minimum_msat: 3,
+                       },
+               };
+               let htlc_maximum_msat = 100_000;
+               let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
+               assert_eq!(blinded_payinfo.htlc_minimum_msat, 2_000);
+       }
+
+       #[test]
+       fn aggregated_htlc_min() {
+               // Create a path with varying fees and htlc_mins, and make sure htlc_minimum_msat ends up as the
+               // max (htlc_min - following_fees) along the path.
+               let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
+               let intermediate_nodes = vec![ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 0,
+                                       fee_proportional_millionths: 500,
+                                       fee_base_msat: 1_000,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 5_000,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: u64::max_value()
+               }, ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 0,
+                                       fee_proportional_millionths: 500,
+                                       fee_base_msat: 200,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 2_000,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: u64::max_value()
+               }];
+               let recv_tlvs = ReceiveTlvs {
+                       payment_secret: PaymentSecret([0; 32]),
+                       payment_constraints: PaymentConstraints {
+                               max_cltv_expiry: 0,
+                               htlc_minimum_msat: 1,
+                       },
+               };
+               let htlc_minimum_msat = 3798;
+               assert!(super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_minimum_msat - 1).is_err());
+
+               let htlc_maximum_msat = htlc_minimum_msat + 1;
+               let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, htlc_maximum_msat).unwrap();
+               assert_eq!(blinded_payinfo.htlc_minimum_msat, htlc_minimum_msat);
+               assert_eq!(blinded_payinfo.htlc_maximum_msat, htlc_maximum_msat);
+       }
+
+       #[test]
+       fn aggregated_htlc_max() {
+               // Create a path with varying fees and `htlc_maximum_msat`s, and make sure the aggregated max
+               // htlc ends up as the min (htlc_max - following_fees) along the path.
+               let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
+               let intermediate_nodes = vec![ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 0,
+                                       fee_proportional_millionths: 500,
+                                       fee_base_msat: 1_000,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 1,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: 5_000,
+               }, ForwardNode {
+                       node_id: dummy_pk,
+                       tlvs: ForwardTlvs {
+                               short_channel_id: 0,
+                               payment_relay: PaymentRelay {
+                                       cltv_expiry_delta: 0,
+                                       fee_proportional_millionths: 500,
+                                       fee_base_msat: 1,
+                               },
+                               payment_constraints: PaymentConstraints {
+                                       max_cltv_expiry: 0,
+                                       htlc_minimum_msat: 1,
+                               },
+                               features: BlindedHopFeatures::empty(),
+                       },
+                       htlc_maximum_msat: 10_000
+               }];
+               let recv_tlvs = ReceiveTlvs {
+                       payment_secret: PaymentSecret([0; 32]),
+                       payment_constraints: PaymentConstraints {
+                               max_cltv_expiry: 0,
+                               htlc_minimum_msat: 1,
+                       },
+               };
+
+               let blinded_payinfo = super::compute_payinfo(&intermediate_nodes[..], &recv_tlvs, 10_000).unwrap();
+               assert_eq!(blinded_payinfo.htlc_maximum_msat, 3997);
+       }
+}
index 12195519012a14096af531d4cb87127156888a66..0a685f534b6456b811505e059574ecafb8db9071 100644 (file)
@@ -4093,6 +4093,73 @@ fn test_channel_ready_without_best_block_updated() {
        nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
 }
 
+#[test]
+fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       // Let channel_manager get ahead of chain_monitor by 1 block.
+       // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
+       // in case where client calls block_connect on channel_manager first and then on chain_monitor.
+       let height_1 = nodes[0].best_block_info().1 + 1;
+       let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
+
+       nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
+       nodes[0].node.block_connected(&block_1, height_1);
+
+       // Create channel, and it gets added to chain_monitor in funding_created.
+       let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
+
+       // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
+       // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
+       // was running ahead of chain_monitor at the time of funding_created.
+       // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
+       // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
+       confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
+       connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
+
+       // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
+       let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
+       nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
+}
+
+#[test]
+fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
+       let chanmon_cfgs = create_chanmon_cfgs(2);
+       let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
+       let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
+
+       // Let chain_monitor get ahead of channel_manager by 1 block.
+       // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
+       // in case where client calls block_connect on chain_monitor first and then on channel_manager.
+       let height_1 = nodes[0].best_block_info().1 + 1;
+       let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
+
+       nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
+       nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
+
+       // Create channel, and it gets added to chain_monitor in funding_created.
+       let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
+
+       // channel_manager can't really skip block_1, it should get it eventually.
+       nodes[0].node.block_connected(&block_1, height_1);
+
+       // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
+       // the block before block_1, since that was populated by channel_manager, and channel_manager was
+       // running behind at the time of funding_created.
+       // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
+       // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
+       confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
+       connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
+
+       // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
+       let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
+       nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
+}
+
 #[test]
 fn test_drop_messages_peer_disconnect_dual_htlc() {
        // Test that we can handle reconnecting when both sides of a channel have pending
index ca0605c95983afd3b370cafddaf82de2868dadfb..372a094a931bed6dcca159e4bab310cdd7863a4b 100644 (file)
@@ -216,6 +216,12 @@ where
        for stored_key in kv_store.list(
                CHANNEL_MONITOR_PERSISTENCE_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE)?
        {
+               if stored_key.len() < 66 {
+                       return Err(io::Error::new(
+                               io::ErrorKind::InvalidData,
+                               "Stored key has invalid length"));
+               }
+
                let txid = Txid::from_hex(stored_key.split_at(64).0).map_err(|_| {
                        io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
                })?;